[英]How to use sort function with map in c++?
Just look at my program , i have declared a vector of map objects . 看看我的程序,我已经声明了地图对象的向量。
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using std::cout;
using std::cin;
using std::endl;
using std::map;
using std::string;
using std::vector;
using std::make_pair;
using std::multimap;
using std::sort;
int main(void)
{
vector< multimap<string , string> > data;
data.resize(1);
data[0].insert(make_pair("outlook","sunny"));
data[0].insert(make_pair("wind","weak"));
data.resize(data.size() + 1);
data[1].insert(make_pair("outlook","sunny"));
data[1].insert(make_pair("wind","strong"));
data.resize(data.size() + 1);
data[2].insert(make_pair("outlook","overcast"));
data[2].insert(make_pair("wind","weak"));
data.resize(data.size() + 1);
data[3].insert(make_pair("outlook","rain"));
data[3].insert(make_pair("wind","weak"));
data.resize(data.size() + 1);
data[4].insert(make_pair("outlook","rain"));
data[4].insert(make_pair("wind","weak"));
data.resize(data.size() + 1);
data[5].insert(make_pair("outlook","rain"));
data[5].insert(make_pair("wind","strong"));
sort(data.begin() , data.end() , []( vector< multimap<string,string> > a , vector< multimap<string,string> > b)
{
return a[0].find("outlook")->second < b[0].find("outlook")->second;
});
return 0;
}
I have defined a sort function to sort vector entries with respect to the "outlook" index of map but this function is not working . 我已经定义了一个排序功能,以根据map的“ outlook”索引对矢量条目进行排序,但是此功能无法正常工作。 Can anyone tell me what is wrong with this function and the correct way of sorting ?
谁能告诉我此功能和正确的排序方式有什么问题?
The predicate for std::sort
is going to be called with arguments of type vector::value_type
, and not the vector
s themselves. std::sort
的谓词将使用vector::value_type
类型的参数调用,而不是vector
本身。 Change the lambda expression to 将lambda表达式更改为
[](multimap<string,string> const& a, multimap<string,string> const& b)
{
return a.find("outlook")->second < b.find("outlook")->second;
}
The const&
is not necessary, but you probably want to avoid making unnecessary copies of the multimap
s each time the predicate is called. const&
不是必需的,但是您可能希望避免在每次调用谓词时对multimap
进行不必要的复制。 You may also want to check the result of multimap::find
before deferencing the result. 您可能还想在延迟结果之前检查
multimap::find
的结果。
And instead of calling vector::resize
each time to add a new multimap
, you can call 而不是每次调用
vector::resize
来添加新的multimap
,您可以调用
data.emplace_back();
which will default construct a new multimap
. 默认将构造一个新的
multimap
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.