What is the difference between const_iterator and non-const iterator in the C++ STL?

后端 未结 7 2022
灰色年华
灰色年华 2020-11-28 19:00

What is the difference between a const_iterator and an iterator and where would you use one over the other?

7条回答
  •  庸人自扰
    2020-11-28 19:45

    ok Let me explain it with very simple example first without using constant iterator consider we have collection of random integers collection "randomData"

        for(vector::iterator i = randomData.begin() ; i != randomData.end() ; ++i)*i = 0;
    for(vector::const_iterator i = randomData.begin() ; i!= randomData.end() ; ++i)cout << *i;
    

    As can be seen for writing/editing data inside collection normal iterator is used but for reading purpose constant iterator has been used . If you try using constant iterator in first for loop you will get error . As a thumb rule use constant iterator to read data inside collection .

提交回复
热议问题