const iterator
First look at the following program:
sum =0;
vector<int> v{1,2,3,4,5,6};
vector<int>::iterator it = v.begin();
while(it != v.end()){
sum += *it;
it++;
}
The code first obtains the iterator of the vector, and then traverses the vector and sums it. Look at the following code again:
sum =0;
constvector<int>cv{1,2,3,4,5,6};
vector<int>::iterator cit = cv.begin();
while(cit != v.end()){
sum += *cit;
cit++;
}
This code cannot be compiled because the defined vector is of const type, so the iterator must also be of const type. The code needs to be modified as follows:
sum =0;
constvector<int>cv{1,2,3,4,5,6};
vector<int>::const_iterator cit = cv.begin();
while(cit != v.end()){
sum += *cit;
cit++;
}
Another way is to use the auto type modifier:
sum =0;
auto ait = cv.begin();
while(ait != cv.end()){
I am += *he said;
belong++;
}
It saves the trouble of manually distinguishing iterator types, and does not hinder the function of const type iterators.
Go one step further
The vector itself is of type const, and the generated iterator must be of type const. In this way, possible modifications to the vector data are avoided at the compile level.
There is another case where the data itself is not a const type, but some processing should not modify the data from a design point of view. At this time, iterators of const type should also be required to avoid accidental modification of data.
C++11 provides the cbegin and cend methods for this.
vector<int> v{1,2,3,4,5,6};、
auto ait = v.cbegin();
while(ait != v.cend()){
I am += *he said;
*ait = sum; //compile error
belong++;
}
cbegin()/cend() determines that the returned iterator type is const. At this time, even if the type of the vector is not const, the misoperation of the data can be prevented.
Author's point of view
For the sake of safety, do not give what should not be given, and do not take what should not be taken. As a human being, so does programming.