有一个项目和属性的列表。
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::sort
在 std::pair<double, Items>
的列表中(不是一对列表)并提供适当的比较功能。
关于C++按属性对项目进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932764/