Simple STL question - using STL algorithm on STL map
-
Hi If I'm not wrong, an element in STL map is a pair of . Given a map of a number of elements, how can I use STL algorithms like for_each(), accumulate(), etc on just the data, ignoring the keys? Thanks!
The parameter of the
for_each
predicate is the result of dereferencing an iterator, which in the case of amap
is amap<key,value>::value_type
, orpair<const key,value>
. So the predicate can look at thesecond
member of thepair
:#include <map>
#include <algorithm>
typedef map<char,int> mymap;struct TotalIt
{
void operator()( mymap::value_type elt ) // same as "pair<const char,int> elt"
{
m_total += elt.second;
}int m\_total; TotalIt() : m\_total(0) { }
};
int main()
{
mymap M;M\['a'\] = 1; M\['b'\] = 2; M\['c'\] = 3; M\['d'\] = 4; M\['e'\] = 5; for\_each ( M.begin(), M.end(), TotalIt() );
}
--Mike-- Personal stuff:: Ericahist | Homepage Shareware stuff:: 1ClickPicGrabber | RightClick-Encrypt CP stuff:: CP SearchBar v2.0.2 | C++ Forum FAQ ---- If my rhyme was a drug, I'd sell it by the gram.
-
Hi If I'm not wrong, an element in STL map is a pair of . Given a map of a number of elements, how can I use STL algorithms like for_each(), accumulate(), etc on just the data, ignoring the keys? Thanks!
How about this?
#include <iostream>
#include <map>
#include <iterator>
#include <numeric>template <typename I> class Pair2ndIterator : public I
{
public :
Pair2ndIterator ( I i ) : I ( i )
{
}
typename I::value_type::second_type& operator* ()
{
return (I::operator*()).second ;
}
} ;template <typename I> Pair2ndIterator<I> MakePair2ndIterator ( I it )
{
return Pair2ndIterator<I> ( it ) ;
}int main()
{
std::map<char, int> mymap ;
mymap.insert ( std::make_pair ( 'a', 10 )) ;
mymap.insert ( std::make_pair ( 'b', 11 )) ;
mymap.insert ( std::make_pair ( 'c', 12 )) ;
mymap.insert ( std::make_pair ( 'd', 13 )) ;
mymap.insert ( std::make_pair ( 'e', 14 )) ;std::cout << "Accumulate ( mymap ) = " << std::accumulate ( MakePair2ndIterator ( mymap.begin ()), MakePair2ndIterator ( mymap.end ()), 0 ) ; return 0;
}
Paul