C++ primer(第五版) 练习 3.23
题目:编写一段程序,创建一个含有10个整数的vector对象,然后使用迭代器将所有元素的值都变成原来的两倍。输出vector对象的内容,检验程序是否正确。
答:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::vector;
using std::endl;
int main()
{
vector<int> v1{ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };
cout << "原来的值如下:" << endl;
for (auto a = v1.begin(); a != v1.end(); a++)
cout << *a << " ";
cout << endl;
cout << "变成两倍后的值如下:" << endl;
for (auto it = v1.begin(); it != v1.end(); it++)
*it *= 2;
for (auto b = v1.begin(); b != v1.end(); b++)
cout << *b<<" ";
cout << endl;
return 0;
}
执行结果图: