C++ std::min_元素从类对象返回意外结果
我在我创建的具有索引的节点对象上使用std::min_元素。我有一个std::set容器,它包含10个具有不同索引的节点,然后调用std::min_元素以获取索引号最低的节点C++ std::min_元素从类对象返回意外结果,c++,C++,我在我创建的具有索引的节点对象上使用std::min_元素。我有一个std::set容器,它包含10个具有不同索引的节点,然后调用std::min_元素以获取索引号最低的节点 #include <iostream> #include <string> #include <algorithm> #include <set> using namespace std; class Node { public: Node(int index)
#include <iostream>
#include <string>
#include <algorithm>
#include <set>
using namespace std;
class Node
{
public:
Node(int index) : _index(index) {}
int index() const { return _index; }
inline bool operator< (const Node &right) { return this->index() < right.index(); }
private:
int _index;
};
int main()
{
set<Node*> s;
for(int i = 10; i > 0; i--) //10 , 9 , 8 ...
s.insert(new Node(i));
Node *lowest = *min_element(s.begin(), s.end());
cout << lowest->index() << endl;
//free
for(set<Node*>::iterator iter = s.begin(); iter != s.end(); iter++)
delete *iter;
system("pause");
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
类节点
{
公众:
节点(int-index):_-index(index){}
int index()常量{return_index;}
内联布尔运算符<(const Node&right){返回此->索引()0;i--)//10,9,8。。。
s、 插入(新节点(i));
Node*lower=*minu元素(s.begin(),s.end());
cout index()您有一个集,而不是集。因此它使用标准指针运算符。关键是s
不包含节点。它包含指针。这决定了顺序和等价性。这不是您的问题,而是使用内联布尔运算符<(const Node&right)const{…}
取而代之。谢谢!但仅出于学习目的,假设这是一个std::vector,我必须使用指向对象的指针,解决方法是什么?@Pilpel更新了我的答案来说明这一点。以前从未见过[](…){…}
语法。它做什么?它在min_元素()内创建函数吗?
std::set<Node> nodes;
// add nodes here
Node& lowest = *nodes.begin();
std::vector<Node*> nodes;
// add nodes here
auto it = std::min_element(std::begin(nodes), std::end(nodes),
[](Node* a, Node* b){ return *a < *b; }
);