这可能是最好的例子。我有两个向量/列表:
People = {Anne, Bob, Charlie, Douglas}
Ages = {23, 28, 25, 21}
我想使用像sort(People.begin(), People.end(), CustomComparator)
这样的东西根据年龄对人进行排序,但我不知道如何编写CustomComparator
来查看年龄而不是人。
发布于 2009-11-13 00:25:15
正如其他人所指出的,你应该考虑对人和年龄进行分组。
如果您不能/不想这样做,您可以为它们创建一个“索引”,并对该索引进行排序。例如:
// Warning: Not tested
struct CompareAge : std::binary_function<size_t, size_t, bool>
{
CompareAge(const std::vector<unsigned int>& Ages)
: m_Ages(Ages)
{}
bool operator()(size_t Lhs, size_t Rhs)const
{
return m_Ages[Lhs] < m_Ages[Rhs];
}
const std::vector<unsigned int>& m_Ages;
};
std::vector<std::string> people = ...;
std::vector<unsigned int> ages = ...;
// Initialize a vector of indices
assert(people.size() == ages.size());
std::vector<size_t> pos(people.size());
for (size_t i = 0; i != pos.size(); ++i){
pos[i] = i;
}
// Sort the indices
std::sort(pos.begin(), pos.end(), CompareAge(ages));
现在,第n个人的名字是people[pos[n]]
,年龄是ages[pos[n]]
发布于 2009-11-12 23:39:05
通常,您不会将想要保存在一起的数据放在不同的容器中。为Person创建一个结构/类,并重载operator<
。
struct Person
{
std::string name;
int age;
}
bool operator< (const Person& a, const Person& b);
或者如果这是一些被丢弃的东西:
typedef std::pair<int, std::string> Person;
std::vector<Person> persons;
std::sort(persons.begin(), persons.end());
std::pair
已经实现了比较运算符。
发布于 2009-11-12 23:52:06
将它们保存在两个单独的数据结构中是没有意义的:如果对People
进行重新排序,就不再有到Ages
的合理映射。
template<class A, class B, class CA = std::less<A>, class CB = std::less<B> >
struct lessByPairSecond
: std::binary_function<std::pair<A, B>, std::pair<A, B>, bool>
{
bool operator()(const std::pair<A, B> &left, const std::pair<A, B> &right) {
if (CB()(left.second, right.second)) return true;
if (CB()(right.second, left.second)) return false;
return CA()(left.first, right.first);
}
};
std::vector<std::pair<std::string, int> > peopleAndAges;
peopleAndAges.push_back(std::pair<std::string, int>("Anne", 23));
peopleAndAges.push_back(std::pair<std::string, int>("Bob", 23));
peopleAndAges.push_back(std::pair<std::string, int>("Charlie", 23));
peopleAndAges.push_back(std::pair<std::string, int>("Douglas", 23));
std::sort(peopleAndAges.begin(), peopleAndAges.end(),
lessByPairSecond<std::string, int>());
https://stackoverflow.com/questions/1723066
复制相似问题