2
std::map< std::string , std::string > matrix_int;
typedef std::pair< std::string , std::string > lp_type;
BOOST_FOREACH( lp_type &row, matrix_int ){

}

this can not be complied: error C2440: 'initializing' : cannot convert from 'std::pair<_Ty1,_Ty2>' to 'lp_type &'

when I have ',' in element type, boost doc says I can use typedef or predefine a var; but what should I do when I want to get a reference?

Pieter
  • 2,822
  • 18
  • 17
areslp
  • 383
  • 1
  • 4
  • 17

3 Answers3

10

Your typedef is incorrect; it needs to be:

typedef std::pair< const std::string , std::string > lp_type;
                   ^ note the added const

The key element in the map pair is const-qualified.

It would be a bit cleaner to use the value_type typedef; this way you don't repeat the type information:

typedef std::map<std::string, std::string> map_t;
map_t matrix_int;
BOOST_FOREACH(map_t::value_type& row, matrix_int){

}
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 2
    Although technically correct, I would argue that using the inner typedef `value_type` of the map would be better, as it does not expose this intricacy. – Matthieu M. Jun 07 '10 at 14:36
  • @Matthieu: Yeah; three people said that while I was editing to add that as a suggestion. :-P I agree wholeheartedly. – James McNellis Jun 07 '10 at 14:39
2

See Is it possible to use boost::foreach with std::map?.

Looks like you need to do:

typedef std::map< std::string, std::string > MyMap;
BOOST_FOREACH( MyMap::value_type& row, matrix_int ) {
}
Community
  • 1
  • 1
bshields
  • 3,563
  • 16
  • 16
1

I think James McNellis is right. I'll add the suggestion that you take advantage of the value_type typedef that std::map provides. Then your code could look like this:

typedef std::map< std::string , std::string > MyMap;
MyMap matrix_int;

BOOST_FOREACH( MyMap::value_type &row, matrix_int ){

}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174