代码:
#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; }
问题:
最后一个元素(或通常所有超过 maxval 迭代器指向的元素并包括该元素的 vector 元素)不会改变。为什么 maxval 迭代器保护后续 vector 元素不被修改?
最佳答案
因为 maxval 指向 test[1]
并且一旦计算出 0.9/*maxval
,*maxval
实际上是 1.0
,这样test[2]
保持不变。
您可以将 maxval 值复制到本地 float 变量,以更改最后一个元素:
float fmaxval = *maxval;
及以下:
for (it = test.begin(); it != test.end(); ++it)
*it = (*it)/fmaxval;
关于c++ - 无法使用迭代器更改 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23136009/