Strange initialization
Written by Antoni Boucher   
Article Index
Strange initialization
Solution

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.

 

Banner

 

Background

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) {
data.push_back(word);
}
}

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.

Puzzle

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(
istream_iterator<string>(cin),
istream_iterator<string>());
}

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>