1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <map>
#include <vector>
#include <string>
template < typename T, std::size_t N >
std::map< T, std::vector<std::size_t> > map_indices( const T(&array)[N] )
{
std::map< T, std::vector<std::size_t> > result ;
for( std::size_t i = 0 ; i < N ; ++i ) result[ array[i] ].push_back(i) ;
return result ;
}
template < typename T > void print( const std::map< T, std::vector<std::size_t> >& map )
{
for( typename std::map< T, std::vector<std::size_t> >::const_iterator iter = map.begin() ;
iter != map.end() ; ++iter )
{
std::cout << iter->first << " => { " ;
for( std::size_t i = 0 ; i < iter->second.size() ; ++i )
std::cout << iter->second[i] << ' ' ;
std::cout << "}\n" ;
}
}
int main()
{
const int a[] = { 1, 4, 7, 3, 3, 5, 3, 1, 7, 8, 3, 1, 7 } ;
const std::map< int, std::vector<std::size_t> > map = map_indices(a) ;
print(map) ;
std::cout << "\n-----------------------------\n" ;
const std::string b[] = { "how", "now", "brown", "cow", "now", "brown", "how", "brown", "how" } ;
print( map_indices(b) ) ;
}
|