简体   繁体   中英

Unable to change vector elements using iterator

The code:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
using std::vector;

int main(){ 
vector<float> test;
test.push_back(0.5);
test.push_back(1.1);
test.push_back(0.9);
vector<float>::iterator maxval = max_element(test.begin(), test.end());
vector<float>::iterator it;
for (it = test.begin(); it != test.end(); ++it)
    *it = (*it)/(*maxval);
for (it = test.begin(); it != test.end(); ++it)
    cout << *it << endl;
return 0; }

The problem:

The last element (or in general all the vector elements past the element pointed to by the maxval iterator and including that element) do not change. Why does the maxval iterator protect the subsequent vector elements from being modified ?

Because maxval is pointing to test[1] and once you compute 0.9 / *maxval , *maxval is actually 1.0 , this way test[2] stays unchanged.

You can copy maxval value to local float variable, to have last element changed:

float fmaxval = *maxval;

and below:

for (it = test.begin(); it != test.end(); ++it)
    *it = (*it)/fmaxval;

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