【发布时间】:2016-02-17 15:49:56
【问题描述】:
我有一个元素类型的向量数组。现在如何根据每个元素的中心值与 100 的距离按升序对数组进行排序?
在这种情况下,生成的 Elements 向量数组将导致向量数组被排序为类似这样...
已排序的元素:
Elements.push_back(Element(77));
Elements.push_back(Element(128));
Elements.push_back(Element(20));
Elements.push_back(Element(-370));
Elements.push_back(Element(-489));
代码:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
class Element
{
public:
int Center;
Element(int center)
{
Center = center;
}
};
int main(int)
{
cout << "Start...\n";
vector<Element> Elements;
// add test objects
Elements.push_back(Element(20));
Elements.push_back(Element(-370));
Elements.push_back(Element(128));
Elements.push_back(Element(77));
Elements.push_back(Element(-489));
//cout << "value of a: " << Elements.size() << endl;
for (vector<Element>::size_type i = 0; i != Elements.size(); i++) {
cout << "value of a: " << Elements[i].Center << endl;
}
return 0;
}
【问题讨论】:
-
将
std::sort与执行所需比较的 lambda 表达式一起使用。 -
排序最接近 100? 128和100相差28,77是23。为什么128在77之前。
-
不相关但注意并使用initializer lists(即
Element(int center) : Center(center) {}) -
@FlorisVelleman 我的错误,但我猜你明白了。