Re: searching for a value in std::map
James Barrett <xucaen@comcast.net> wrote:
Hi, I have a map<int,unsigned int>. At a certain point in my program, I
know a value that is stored in the map and I need to find the key. I
thought I remembered seeing a member function in std::map that did that.
Is there? Or am I thinking of a different container class?
Your description makes it sound like there is only one unsigned int of
the particular value in the map...
If you know that there is only one of the value you are looking for, you
can transfer the data into a map<unsigned int, int> or a multimap if you
aren't sure. That may be more trouble/time than it's worth though.
Another, and more obvious, solution is to simply search through it like
you would a vector.
template < typename Pair >
struct second_equal_to
{
typename Pair::second_type v;
second_equal_to( const typename Pair::second_type& v ): v( v ) { }
bool operator()( const Pair& m ) const {
return m.second == v;
}
};
The above will work with any sort of map (or any other pair for that
matter) and can be used like this:
int main() {
typedef map<int, unsigned int> Map;
Map m;
// fill map
unsigned int v /*= some value*/;
Map::iterator it = find_if( m.begin(), m.end(),
second_equal_to<Map::value_type>( v ) );
while ( it != m.end() ) {
// *it points to a mapped element you want
it = find_if( ++it, m.end(),
second_equal_to<Map::value_type>( v ) );
}
}
With a little effort, you can make the struct even more generic so you
can apply other binary predicates to second.
Or if you want to go all out:
Map::iterator it = find_if( m.begin(), m.end(),
compose1( bind2nd( equal_to<unsigned int>(), v ),
select2nd<Map::value_type>() ) );
Note: compose1 and select2nd are not part of the standard (although they
are part of the STL.)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]