代码:
#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迭代器会保护后续的向量元素不被修改?
对于以下两个n元素整数向量乘法的替代方法,可以更快(在代码所需的时间方面):
{
// code for obtaining two n element int vectors, a and b
}
int temp = 0; // a temporary variable
for (int ii = 0; ii < n; ++ii)
temp += a[ii]*b[ii];
Run Code Online (Sandbox Code Playgroud)
编辑:收到几个不错的想法.我必须检查每一个,看看哪一个是最好的.当然,每个回答都告诉我一些新的东西.