如何在地图中使用排序

how do I use sort in maps?

本文关键字:排序 地图      更新时间:2023-10-16

如何在映射中排序?
我尝试过排序(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>