Strange initialization
Written by Antoni Boucher   
Thursday, 23 June 2011
Article Index
Strange initialization

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.





Here is a simple way to get words from the user and push them into a vector:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main() {
vector<string> data;
string word;
while(cin >> word) {

This works perfectlhy and as you would expect.

For example,  if you want to show the first word:

std::cout << << std::endl;

The first word entered by the user is shown on the screen, as expected.


But, 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>
#include <iterator>
#include <string>
#include <vector>

using namespace std;

int main() {
vector<string> data(

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.





Last Updated ( Friday, 05 August 2011 )