C++ 使用STL:算法对结构进行排序
我正在寻找一种使用STL:算法库的sort()函数对结构进行排序的方法。 我发现了一些使用vector的代码。比如说C++ 使用STL:算法对结构进行排序,c++,C++,我正在寻找一种使用STL:算法库的sort()函数对结构进行排序的方法。 我发现了一些使用vector的代码。比如说 struct person { std::string name; int age; }; bool sort_by_name( const person & lhs, const person & rhs ) { return lhs.name < rhs.name; } bool sort_by_age( const person &a
struct person {
std::string name;
int age;
};
bool sort_by_name( const person & lhs, const person & rhs )
{
return lhs.name < rhs.name;
}
bool sort_by_age( const person & lhs, const person & rhs )
{
return lhs.age < rhs.age;
}
int main() {
std::vector<person> people;
// fill in the vector
std::sort( people.begin(), people.end(), sort_by_name );
std::sort( people.begin(), people.end(), sort_by_age );
}
struct-person{
std::字符串名;
智力年龄;
};
bool按名称排序(const person和lhs、const person和rhs)
{
返回lhs.name
我想知道有没有可能不用向量对它进行排序。??如果是,那么如何?算法采用3个参数:
- 将迭代器随机访问到初始位置李>
- 随机访问迭代器到最终位置和
- 排序标准
std::sort
。尽管排序条件具有严格的弱排序,但这一点很重要。您可以对数组或任何其他容器进行排序,如
deque
或list
。如何对结构进行排序?您总是可以对集合排序可能的重复项,我认为这仍然适用于普通数组,尽管它实际上不是随机访问迭代器。这是真的,还是它们只与其他事物兼容?@chris:指针是一个随机访问迭代器。(数组名在传递给函数时衰减为指向数组第一个元素的指针。)@HighCommander4,哦,我的错。我并没有深入研究迭代器本身,我只是使用了它们。谢谢你提供的免费知识。@chris:确切地说,标准库中包含的是迭代器类别而不是类,一个类别只定义迭代器的能力,类型并不重要。任何行为类似于随机迭代器的东西都是随机迭代器。