views:

169

answers:

3
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?

+8  A: 

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
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.
@Matthieu: Yeah; three people said that while I was editing to add that as a suggestion. :-P I agree wholeheartedly.
James McNellis
+2  A: 

See http://stackoverflow.com/questions/2104208/is-it-possible-to-use-boostforeach-with-stdmap.

Looks like you need to do:

typedef std::map< std::string, std::string > MyMap;
BOOST_FOREACH( MyMap::value_type& row, matrix_int ) {
}
bshields
+1  A: 

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