[英]Working with a vector of pair vectors?
我一直在Google周围搜索,但没有找到所需的东西。 我正在尝试创建一个向量,该向量可让我添加3个(然后需要存储4个)变量,对其进行访问和排序。
我正在为3个变量实现矢量,如下所示:
std::vector<std::pair<std::string, std::pair<int, double> > > chromosomes;
要添加信息(变量),我正在做:
chromosomes.emplace_back(dirp->d_name, std::make_pair(WSA, fault_percent));
如何访问每个参数并根据WSA和故障范围对它们进行排序? 就像在成对的向量中一样,我可以使用first
和second
。
对于4个变量,将如下所示?
std::vector<std::pair<std::string, std::string>, std::pair<int, double> > > chromosomes;
chromosomes.emplace_back( std::make_pair(dirp->d_name, x), std::make_pair(WSA, fault_percent));`
正如这里建议的,我认为您应该分别使用tuple<string, int, double>
s或tuple<string, string, int, double>
s的vector
。
有一个定义的tuple::operator<
,它对每个组成类型使用小于运算符(从左到右移动)。 如果每个元素的简单比较就足够了,那么您需要做的就是调用sort
:
sort(chromosomes.begin(), chromosomes.end());
如果tuple::operatior<
没有为您的需求提供足够的比较,则sort
提供需要比较lambda的重载。 您的lambda需要执行以下操作:
tuple
s的const引用 tuple
严格小于第二个tuple
tuple
则返回true
tuple
大于或等于第二个tuple
tuple
则返回false
最后,您的呼叫将如下所示:
sort(chromosomes.begin(), chromosomes.end(), [](const auto& lhs, const auto& rhs) {
// Your comparison between the two goes here
});
如果您不熟悉使用tuple
s,则在tuple
不包含重复类型的情况下,需要使用模板化的get
方法按索引或类型提取。
首先访问不同的元素:
for (auto& x :chromosomes)
cout <<x.first<<": "<<x.second.first<<" "<<x.second.second<<endl;
接下来,对WSA上的元素进行排序 :
sort(chromosomes.begin(), chromosomes.end(),
[](auto &x, auto &y) { return x.second.first<y.second.first;});
如果要根据多个条件(例如WSA和fault_percent)进行排序,则只需更改lambda函数以进行比较:
sort(chromosomes.begin(), chromosomes.end(),
[](auto &x, auto &y) { return x.second.first<y.second.first
|| (x.second.first==y.second.first
&& x.second.second<y.second.second );});
这是一个在线演示
现在让我感到困惑的是,当您可以使用更易于存储/检索并访问其成员的干净struct
时,为什么要使用成对的双元组甚至元组?
struct Chromosome {
string name;
int WSA;
double fault_percent;
};
vector <Chromosome> chromosomes;
这样,它将更具可读性和可维护性:
sort(chromosomes.begin(), chromosomes.end(),
[](auto &x, auto &y) { return x.WSA<y.WSA
|| (x.WSA==y.WSA && x.fault_percent<y.fault_percent );});
似乎您需要一个类似表的数据结构,该结构允许按多列进行排序。 C ++不是操纵表/矩阵数据结构的最简单语言,但是这里有一些链接可以帮助您入门。
表类示例: 如何按任意列对数据进行动态排序
向量/元组解决方案,是您当前正在使用的解决方案的更简洁版本: 使用stl sort对表进行排序
关于这个问题的冗长讨论,可能会给您一些其他想法: https : //softwareengineering.stackexchange.com/questions/188130/what-is-the-best-way-to-store-a-table-in-c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.