問題:使用條件運算符從vector<int>中找到值是奇數的元素,並將這些奇數值翻倍。
1.條件運算符:a>b?c:d,爲三目運算符;
2.在遍歷和改變數組、容器等序列元素時,使用範圍for循環比較方便;(範圍for循環詳見該書168頁)
3.在給容器添加元素時,不要用下標進行操作;
4.使用while循環結束時用crtl+z;
5.system("pause");語句是爲了能顯示控制檯;
6.本人使用的平臺是vs2015;
7.望各位網友批評指正。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v_int;
int value;
cout << "請輸入元素值:";
while (cin >> value)
v_int.push_back(value);
for (auto p : v_int)
cout << p << ' ';
cout << endl;
for (auto& s : v_int)
s = ((s % 2) == 0 ? s : s * 2);
for (auto p : v_int)
cout << p << ' ';
system("pause");
return 0;
}