Strange initialization |
Written by Antoni Boucher | |||
Page 1 of 2 Are you always speaking the same syntax as your compiler? This C++ puzzle looks at how you can put things together thinking they mean one thing when in fact they mean another...
Sometimes, we initialize a vector using iterators. But we can get unexpected behavior or a compiler error. Does the compiler always understand the code the same way we do? Not always. This Programmer Puzzle explores how C++ compilers interpret vector initialisation with iterators.
BackgroundHere is a simple way to get words from the user and push them into a vector: #include <iostream> This works perfectlhy and as you would expect. For example, if you want to show the first word: std::cout << data.at(0) << std::endl; The first word entered by the user is shown on the screen, as expected. PuzzleBut, perhaps you find this way of working a bit long and you decide to try a "better" way of getting words from the user. So you try the same task but with iterators:
#include <iostream> Now you run the program and it doesn't ask you to enter any thing at all. No error messages - just nothing. It is supposed to do the same thing. What is going on? Go to the next page to see the answer.
<ASIN:0321543726> <ASIN:0672329417> <ASIN:0201379260> |