按数组元素对数组进行排序 [英] Sorting vector of arrays by array's element

查看:147
本文介绍了按数组元素对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写解决背包问题的算法时遇到了一个问题.我有一个由3个元素组成的数组(C ++ 11)的向量,我想按这些数组的第一个元素的值对向量进行排序.

I have encountered a problem when writing algorithm for solving Knapsack problem. I have a vector of 3-element arrays (C++11) and I want to sort the vector by the value of let's say first element of these arrays.

我已经尝试使用带有预定义比较功能的std :: sort,但是它甚至没有编译.

I've tried std::sort with predefined compare function, but it doesn't even compile.

我猜我的比较功能无法正常工作:

I guess my compare function doesn't work as I expect:

bool compareByValue(const data &a, const data &b)
{
    return a[0] < b[0];
}

int main()
{
    vector<array<int, 3> > myVector;
    ...
    sort ( myVector.begin(), myVector.end(), compareByValue );
}

这不是我第一次遇到类似的问题,而是尝试在网上找到解决方案,但是没有任何令人满意的结果.

It's not the first time when I have the similar problem, I tried to find solution on the Net, but without any satisfying result.

推荐答案

我不知道您从何处获得data,但是您需要将其更改为array<int, 3>或将compareByValue用作模板:

I don't know where you got data from, but you need to change it to array<int, 3> or make compareByValue a template:

bool compareByValue(const array<int, 3> &a, const array<int, 3>&b)
{
    return a[0] < b[0];
}

这篇关于按数组元素对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆