uma*_*elf 2 c++ iterator vector
代码:
#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; }
Run Code Online (Sandbox Code Playgroud)
问题:
最后一个元素(或者通常是maxval迭代器指向的元素之后的所有向量元素,包括该元素)不会改变.为什么maxval迭代器会保护后续的向量元素不被修改?
因为maxval指向test[1]并且一旦你计算0.9 / *maxval,*maxval实际上1.0,这种方式test[2]保持不变.
您可以将maxval值复制到local float变量,以更改最后一个元素:
float fmaxval = *maxval;
Run Code Online (Sandbox Code Playgroud)
及以下:
for (it = test.begin(); it != test.end(); ++it)
*it = (*it)/fmaxval;
Run Code Online (Sandbox Code Playgroud)