Question

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?

Was it helpful?

Solution

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){

}

OTHER TIPS

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 ) {
}

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 ){

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top