清泉逐流

做着努力,等待幸福到来

Map usage

作者:Eamonn 时间 : 2014-09-09 20:13 分类:C/C++

map<char, int> map_test;
for(int i=0; i<10; i++){
    char key = rand() % 26 + 'A';
    int value = rand() % 100;
    map_test[key] = value;
}
// find delete
map<char, int>::interacot it;
it = map_test.find('B');
if( map_test.end() != it ){
    // Found
}
// Delete
map_test.delete(<interactor>);
// Interactor
for(map<char, int>::iterator it=map_test.begin(); it!=map_test.end(); it++){
    // Key  it->first;
    // Value it->second;
}
// Sort
// Map sorted by key automatically, you cann't sort a map
// the following give the sort method with multimap
template<typename A, typename B>
std::pair<B,A> flip_pair(const std::pair<A,B> &p)
{
    return std::pair<B,A>(p.second, p.first);
}
template<typename A, typename B>
std::multimap<B,A> flip_map(const std::map<A,B> &src)
{
    std::multimap<B,A> dst;
    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()),
                   flip_pair<A,B>);
    return dst;
}
// Usage:
std::map<int, double> src;
std::multimap<double, int> dst = flip_map(src);
// dst is now sorted by what used to be the value in src!


转载注明: http://www.eamonning.com/note/view/37
» 笔记大类