Strange initialization |
Written by Antoni Boucher | |||||||
Page 2 of 2
SolutionYou add some code to the program in an effort find out what is happening but the result is only that you get very confused. If you add this line in the main() function, you get a compiler error: std::cout << data.at(0) << std::endl; The compiler error message gives you a hint: request for member ‘at’ in ‘data’, The cause of the problem is that the compiler thinks it is facing a function prototype! However, you want to create a vector, which is a variable definition. Clearly you are not interpreting the syntax in the same way. How does the compiler see a function prototype? Look again at this line: vector<string> data( First of all, we have the return type (vector<string>). istream_iterator<string>(cin) is seen as istream_iterator<string> cin by the compiler. The compiler saw a parameter because the parentheses are superfluous. It sees it as a pointer to a function which does not take any argument and returns istream_iterator<string>. So the line can be read and interpreted as a function prototype! To fix the problem, there are a few options: vector<string> data(( You may use the copy initialization: vector<string> data = vector<string>( And if your compiler supports C++0x, you may use initializers list: vector<string> data{ PatternOne way to avoid this problem happening is to always use copy initialization: vector<string> data = vector<string>( Using this, you are sure it won't look like a function prototype.
More Puzzles
<ASIN:0132673266> <ASIN:059600298X> <ASIN:0321334876> <ASIN:156592116X> |