对不工作的向量排序
sort a vector not working
我在Animal
中有这样的重载运算符
// A must be comparable to be used as keys
bool operator<(const Archivo &right) const
{
return nombreArchivo < right.nombreArchivo;
}
在我的main
中我调用
std::vector<Animal*> animalesConConcha;
// add some objects
std::sort(animalesConConcha.begin(), animalesConConcha.end());
std::cout<<"nnnOrdered:n";
for(it=animalesConConcha.begin(); it!=animalesConConcha.end(); it++)
{
cout<<(*it)->nombre<<" | "<<(*it)->indice<<endl;
}
在vector中存储的是指针,而不是对象。std::sort
不解引用指针,而是比较指针的实际值。(从技术上讲,这没有保证的行为,因为<
直接用于指针。)
解决方案1:将对象直接存储在vector:
vector<Animal> animalesConConcha;
sort(animalesConConcha.begin(), animalesConConcha.end());
for(it=animalesConConcha.begin(); it!=animalesConConcha.end(); it++)
{
cout<< it->nombre<<" | "<< it->indice<<endl;
}
解决方案2:为std::sort
指定一个自定义比较函子:
struct Comparison
{
bool const operator()(Animal *lhs, Animal *rhs) const
{
return (*lhs) < (*rhs);
}
};
sort(animalesConConcha.begin(), animalesConConcha.end(), Comparison());
因为您正在存储指向Animal
的指针向量,因此您没有给类的operator<()
工作的机会。sort
函数使用operator<()
作为vector对象的类型——在本例中是指向Animal
的指针,而不是Animal
的实例。
因此,数组是基于operator<()
对指针进行排序的,正如0x499602D2所说,这将导致指针数组按升序地址排序。
如果您希望它以这种方式工作,要么定义一个自定义比较器,要么使用vector<Animal>
而不是vector<Animal*>
考虑到你没有动物向量。
在你的代码中,有一个指向动物的指针向量。
改变vector<Animal*>
vector<Animal>
并告诉我们是否正在工作。
我假设这是你想要实现的多态性,这就是你使用Animal*
s而不是堆栈分配的Animal
对象的原因。由于您使用指针作为vector的值类型,因此std::sort()
使用operator<()
将解析为内置的重载,该重载将简单地比较指针的地址,而不是您的自定义操作符。
方便地,std::sort()
将谓词作为可选的第三个参数。您可以传递一个可调用实体作为比较器来调用:
std::sort(animalesConConcha.begin(), animalesConConcha.end(),
[] (Animal* lhs, Animal* rhs) {
return lhs->nombreArchivo < rhs->nombreArchivo;
});
如果您的编译器不支持lambda表达式,您可以使用带有重载operator()
的函数或类实例来代替。
相关文章:
- 将结构向量排序为子组
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 如何在对向量排序后更改索引值?c++
- C++向量排序给出0作为输出
- 将许多向量排序在一起
- 根据一个向量对多个向量排序
- 编译错误向量排序和联合
- C++我自己的函数进行向量排序
- 将字符串的向量排序为日期"yyyymmdd"
- C++ 通过使用旧向量进行预排序来改进向量排序
- C 向量排序 .h .cpp中的单独文件
- 向量排序-c++
- 将向量排序到一个无序映射c++11中
- 向量的向量排序
- c++向量排序方法编译失败,返回预期表达式
- 如何对bitset向量排序
- 向量排序的基础上只有先
- 我如何以相同的方式对两个向量排序,而条件只使用其中一个向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 如何基于第二个字符串对字符串向量的向量排序