Hi guys:
I have a fairly simple question regarding the conditional operator.
For a conditional operator, the definition is given as:
condition ? expression 1 : expression 2
which means if condition is true, then execute expression 1, otherwise execute expression 2. It's easy to understand.
I wrote a simple program to find elements in a
vector<int>
that have odd value and double the value of each such element. (From C++ primer, 5th ed, Exercise 4.21).
Below is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <vector>
using std::cin; using std::cout; using std::endl; using std::vector;
int main(void)
{
vector<int> vec;
int element;
cout << "Enter the values for the vector, EOF to quit:" << endl;
while (cin >> element)
vec.push_back(element);
for (auto iter = vec.begin(); iter != vec.end(); ++iter) {
(*iter) = (*iter) % 2 ? 2 * (*iter) : (*iter);
cout << *iter << " ";
}
return 0;
}
|
The above code works correctly. If I input
1, 2, 3, 4, 5
it will yield
2, 2, 6, 4, 10
.
But why can't I even simplify line 17, just write
(*iter) % 2 ? 2 * (*iter) : (*iter);
? In this way, the odd value will not be doubled. The vector remains unchanged.
My understanding is: I test
(*iter) % 2
, if it is true, then it indicates that
(*iter)
is odd and double it, otherwise keep
(*iter)
unchanged. Why I have to use assign operator
=
to make the code work?
I am a newbie in C++, just want to clarify each concept I have encountered.
Thanks.