简体   繁体   中英

C++ std::vector - How to modify an element specified by an iterator?

I am trying to change each element of a vector, but my code doesn't compile, because of some confusion over const s. Here is a greatly simplified example (I have omitted the initialization of the vector):

std::vector<int> test;
for (auto iter = test.cbegin(); iter != test.cend(); ++iter)
{
    int v = *iter; // gets the correct element
    *iter = v * 2; // compile error
}

The compiler error is "'iter': you cannot assign to a variable that is const". What is the correct way to modify a single element, using iterators as shown?

You specifically asked compiler to make sure you will not modify the content of the vector by using cbegin() .

If you want to modify it, use non-const functions:

for(auto iter = test.begin(); iter != test.end(); ++iter)
{
    int v = *iter; // gets the correct element
    *iter = v * 2; // works
}

Or shorter version of the above loop using range-based loop:

for(auto& v : test)
{
    v *= 2;
}

There is a difference between types of iterators:

std::vector<int>::const_iterator a // not allowed to modify the content, to which iterator is pointing
*a = 5; //not allowed
a++; //allowed

const std::vector<int>::iterator b //not allowed to modify the iterator itself (e.g. increment it), but allowed to modify the content it's pointing to
*b = 5; //allowed
b++; //not allowed

std::vector<int>::iterator c //allowed to both modify the iterator and the content it's pointing to
*c = 5; //allowed
c++; //allowed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM