如何在地图中使用排序
how do I use sort in maps?
如何在映射中排序?
我尝试过排序(myMap.begin()
,myMap.end()
(,但它不起作用,我试图在互联网上找到答案,但没有网站专门解释如何对地图使用排序。bdw-my映射有整数及其字母表示。
int main(){
map<int,string> m;
// add integers at the end of the map
m.insert(pair<int,string>(2,"Two"));
m.insert(pair<int,string>(3,"Three"));
m.insert(pair<int,string>(4,"Four"));
m.insert(pair<int,string>(7,"Seven"));
m.insert(pair<int,string>(5,"Five"));
cout<<"Finding minimum value from map"<<endl;
map<int,string>::const_iterator it3;
it3 = min_element(m.begin(),m.end());
cout<<"The minimum value in the vector is "<<it3->first<<","<<it3->second<<endl;
cout<<endl<<endl;
cout<<"Sorting array.."<<endl;
sort(m.begin(),m.end());
cout<<"Array after sorting.."<<endl;
cout << "The size of v is: " << m.size() << "nThe capacity of v is: ";
cout<<m.max_size() <<endl;
cout<<"The content of v is:";
for (it3 = m.begin(); it3 != m.end(); it3++){
cout << it3->first << "," << it3->second << endl;
}
cout<<endl<<endl;
return 0;
}
映射按键排序;你无法改变这一点。
如果你想按关键字排序,那么你什么都不需要做。如果要按值或其他标准进行排序,则需要另一个数据结构。
C++映射通常实现为高度平衡的二进制搜索树。但总的来说,无论用于实现映射的数据结构是什么,映射背后的主要思想是它已经按键排序了。所以显式地按键排序毫无意义。如果您想按值排序,您可以使用其他数据结构,如存储反向映射等。
默认情况下,贴图已经排序,因此您不需要自己排序。默认情况下,如果您遍历std::map
,则会从最低到最高获得元素,因为std::map
的实现方式如下:
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
使用std::less<key>
作为默认的排序比较器,如果您想以不同的方式对其进行排序,只需将其声明为
std::map<Key, Value, Comparator>
而不是
std::map<Key, Value>
相关文章:
- 是否有任何C++功能可以对地图进行排序?
- 如何使地图按值C++排序
- 我正在尝试按降序对地图进行排序,但没有得到预期的结果?
- 尝试按值对地图进行排序,但出现错误
- 对双精度地图进行排序
- 如何在OMNeT++中对地图进行排序?
- 多地图<矢量<int>>,字符>如何排序?
- 少的专业化<>适用于地图但不适用于排序
- 常量地图的意外排序
- C++按值对unordered_map或地图进行排序
- 如何对其中包含地图的列表进行排序
- 为什么我无法使用函数按值对地图进行排序?
- 如何在地图中插入对象以保持其排序
- 根据地图值的属性对地图进行排序
- C++,根据秒迭代对地图内容进行排序
- 如何以相反的顺序对地图进行排序
- 在 c++ 中对地图进行排序
- 获取按地图值排序的映射键向量的最快方法
- 标准::地图按值大小排序(设置<int>)
- 对基于地图C++集合重新排序的有效方法