-4
 #include "stdafx.h"
 #include <unordered_map>
 #include <iostream> 
 using namespace std;

 typedef tr1::unordered_map<int, int>MyMap ;

 int _tmain(int argc, _TCHAR* argv[])
 {
    MyMap PolicyMap;
    PolicyMap.insert(Myap::value_type(0, 10));
    PolicyMap.insert(Myap::value_type(1, 20));
    PolicyMap.insert(Myap::value_type(2, 30));

    for (Myap::const_iterator i = PolicyMap.begin(); i != PolicyMap.end() ; i++)
    {
      cout << " [" << i->first << ", " << i->second << "]" << endl;
    } 
return 0;

}

为什么上面代码的输出是 [0, 10], [2, 30], [1, 20] 。它应该是 [2, 30], [1, 20], [0, 10]。只有当我从零开始输入键值时才会发生这种情况,请帮忙

4

2 回答 2

2

你错过了unordered_map. 它不会像 amap那样对元素进行排序,也不会按照您放入它们的顺序保留元素,它不能保证元素在底层结构中的顺序或元素的顺序使用迭代器时返回。

以上允许 C++ 实现使用更有效的底层结构(哈希表)。

于 2013-02-21T13:22:44.633 回答
2

您当前正在滥用unordered_map. 这个容器宣称它不会以任何特定的顺序保留其元素,因此结果不应该是意外的。

您应该使用 (ordered)std::map代替:

#include <map>
#include <functional>  // needed for std::greater<>

// The third template argument defines the sort direction for the map
// std::greater results in the map being ordered descending (and always by key)
typedef std::map<int, int, std::greater<int> > MyMap;
于 2013-02-21T13:23:43.260 回答