2013-12-15 29 views
0

我试图打印出五个最常用的值。但是,当我将地图更改为多地图时,我打破了向地图添加值的代码。我如何将值添加到多图?它可以以类似的方式完成,因为我将值添加到地图中?将值添加到std :: multimap

// Create a map for keeping track of how many occurences of the different colors 
    multimap<string, int> hexmap; 

    // Add the hex values to the map 
     for(int i = 0; i < imagesize; i ++) 
     { 
      hexmap[colors[i]]++; 
     } 

     typedef std::multimap<int, string> Mymap; 
     Mymap dst; 

     std::transform(hexmap.begin(), hexmap.end(), 
        std::inserter(dst, dst.begin()), 
        [](const std::pair<string,int> &p) 
        { 
        return std::pair<int, string>(p.second, p.first); 
        } 
        ); 


     Mymap::iterator st = dst.begin(),it; 
     size_t count = 5; 
     for(it = st; (it != dst.end()) && (--count); ++it) 
     std::cout << it->second << it->first << endl; 
+1

您可能感兴趣的Boost.Bimap。 –

+1

multimaps不支持通过operator []'进行访问,所以您的'hexmap [colors [i]] ++'行无效。你有把'hexmap'变成多图的原因吗?它似乎可以保留为常规地图。 – Alec

+0

@alecbenzer是的,我想从hexmap recive五个最高值,并有不止一个具有相同的映射值。 – user2520739

回答

0

“我试图列出五个最常用的值。”

在这种情况下,你不必使用hexmapstd::multimap只是std::map将使用做的工作

然而std::multimapdst应要求

+0

@POW我改变了它,我现在没有得到一个错误,但它从最小值开始到最高值。如何改变数据的写入方式? – user2520739

1

您元素添加到std::multimap<K, V>insert()emplace() ,例如:

std::multimap<std::string, int> map; 
map.insert(std::make_pair("hello" , 1)); 
map.insert({ "world", 0 }); 
map.emplace("hello", 0); 

你会找到对象在std::multimap<K, V>使用它的find()成员,例如:

std::multimap<std::string, int>::iterator it = map.find("hello");