3

Can I declare a map like this

map<string, vector<string>> mymap;

I thought it is applicable.

However, it shows not.

I tried

map<string, vector<string>*> mymap;

and then it is OK

What's the rule of this?

skydoor
  • 25,218
  • 52
  • 147
  • 201

2 Answers2

17

You need an extra space:

map<string, vector<string> > mymap;
                          ^ see the extra space

Without the extra space, the >> gets parsed as the right shift operator.

The rules have been modified in C++0x, making the extra space unnecessary. Some compilers (e.g., Visual C++ 2008 and above) already do not require the extra space.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 2
    g++ gives this nice error: `'>>' should be '> >' within a nested template argument list` –  Jun 06 '10 at 19:44
  • 1
    Actually, it's `std::map >`, but I realize I'm on a lost crusade here. – sbi Jun 06 '10 at 20:42
  • @sbi : while we're being pedantic, how do you know it's `std::`? Maybe he wrote his own. Or maybe he has `using namespace std;` or even `using std::string;` and `using std::map;` ;) Out of curiosity, why 'crusade' for the qualification? – Stephen Jun 06 '10 at 23:01
  • 1
    @Stephen: Someone who fails at the famous (and, admittedly, embarrassing) `>>` of nested templates will not have written their own C++ container matching those of the std lib. (And God help us if they had.) As for `using namespace std`, see [this answer](http://stackoverflow.com/questions/2879555/2880136#2880136). – sbi Jun 06 '10 at 23:09
  • @sbi : Yes, I was just giving you a hard time ;) Thanks for the link, the arguments are good. – Stephen Jun 06 '10 at 23:22
9

You can, as James mentioned. Stupid c++ parsing :)

However, map<string, vector<string> > is effectively a multimap<string, string>. A multimap maps a key to multiple values. It might be more convenient or more efficient, depending on your use case.

Stephen
  • 47,994
  • 7
  • 61
  • 70