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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <string>
#include <vector>
#include <map>
struct A {
std::string name ;
int number = 0 ;
// make A LessThanComparable: https://en.cppreference.com/w/cpp/named_req/LessThanComparable
// we can now use objects of type A as the keys of a map with default key compare
friend bool operator< ( const A& first, const A& second ) {
return first.name < second.name ; // compare names (case sensitive)
}
};
int main() {
// create a vector of A
const std::vector<A> vec { { "zero", 0 }, { "one", 1 }, { "two", 2 }, { "three", 3 }, { "four", 4 } } ;
{
// define an empty map with A as the key and int as the mapped value
std::map< A, int > map ;
// iterate through the vector and insert (copies of) the objects into the map
// range-based loop: http://www.stroustrup.com/C++11FAQ.html#for
for( const A& a : vec ) map.emplace( a, a.number ) ;
// print out the contents of the map
for( const auto& pair : map ) {
std::cout << "key A{" << pair.first.name << ',' << pair.first.number
<< "} mapped value: " << pair.second << '\n' ;
}
}
std::cout << "\n---------\n\n" ;
{
// define an empty map with A as the key and int as the mapped value
std::map< A, int > map ;
// iterate through the vector and insert (copies of) the objects into the map
for( auto iter = vec.begin() ; iter != vec.end() ; ++iter )
map.insert( std::make_pair( *iter, iter->number ) ) ;
// print out the contents of the map
for( auto iter = map.begin() ; iter != map.end() ; ++iter ) {
std::cout << "key A{" << iter->first.name << ',' << iter->first.number
<< "} mapped value: " << iter->second << '\n' ;
}
}
}
|