C++按属性对项目进行排序

标签 c++ sorting attributes

有一个项目和属性的列表。

struct Item { double a, b; Item (double a_, double b_): a(a_), b(b_){}};

typedef std::vector <Item> TItems;
typedef std::vector <double> TAttributes;

我正在尝试使用成对列表按属性对项目进行排序:

int main(int argc, char* argv[])
{
    TItems items;
    items.push_back(Item (1.0, 2.0 ));
    items.push_back(Item (3.0, 4.0 ));
    items.push_back(Item (5.0, 6.0 ));

    TAttributes attributes;
    attributes.push_back(8);
    attributes.push_back(7);
    attributes.push_back(9);

    std::pair <TAttributes, TItems> pairs;
    //No element has been coppied
    std::copy (pairs.first.begin(), pairs.first.end(), std::back_inserter (attributes));
     //No element has been coppied
    std::copy (pairs.second.begin(), pairs.second.end(), std::back_inserter (items)); 

    std::sort (pairs.first.begin(), pairs.first.end());
}

有两个问题:

A] 不合适的复制实现(没有元素被复制)

B] 太“搞砸”了代码。

有没有更简单的方法如何使用另一个属性列表对项目列表进行排序?

如何正确实现复制操作?

最佳答案

事实上,您没有在 pairs 中放入任何东西. 参见 std::pair 的构造函数.

std::pair <TAttributes, TItems> pairs(attributes_, items_);

另外,如果您想重新订购 Items根据属性值,您可能想调用 std::sortstd::pair<double, Items> 的列表中(不是一对列表)并提供适当的比较功能。

关于C++按属性对项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932764/

相关文章:

c++ - 访问共享内存进行读取时锁定

c++ - 在 C++ 中将 md5 字符串转换为 base 62 字符串

arrays - 根据 SWIFT 中的字符串数组对自定义数组进行排序

android - 如何在 Android 中排序和分组?

c# - 确保属性仅与静态方法一起使用

python - 在Python中通过多个类传递属性

c++ - (C/C++) 为什么使用全局变量同步单个读取器和单个写入器是有效的?

c++ - 是否可以为 boost::random::uniform_int_distribution<> 设置确定性种子?

python - 基于python中嵌套列表中的列表之一进行排序

html - 如何将 min 和 max 属性添加到 EditorFor 输入元素?