mad*_*hov 13 c++ sorting vector
我在尝试对指针向量进行排序时遇到了一些麻烦.
这是我到目前为止所做的:
class Node
{
private:
vector <Node*> _children;
string _data;
...
public:
void Node::add_child(Node* child)
{
...
sort(_children.begin(), _children.end());
}
bool Node::operator<(const Node& node)
{
return (this->_data.compare(node._data) == -1);
}
};
Run Code Online (Sandbox Code Playgroud)
如果我这样写的话,我的不足运算符就可以了:
Node* root = new Node("abc");
Node* n = new Node("def");
cout << (*root<*n) << endl;
Run Code Online (Sandbox Code Playgroud)
为什么排序从不打电话给操作员?任何帮助,将不胜感激!谢谢.
madshov
San*_*ker 20
因为您对指针值进行排序,而不是Node它们指向的s.
您可以使用std::sort算法的第三个参数来指定自定义比较器.
例如 :
bool comparePtrToNode(Node* a, Node* b) { return (*a < *b); }
std::sort(_children.begin(), _children.end(), comparePtrToNode);
Run Code Online (Sandbox Code Playgroud)
(请注意,此代码只是一个指示 - 您必须在需要时添加额外的安全检查)
Rob*_*obᵩ 12
你的less-than运算符接受const Node&参数,但你的vector正在排序Node*s.您需要指定一个比较函数作为第三个参数std::sort.
class Node
{
private:
vector <Node*> _children;
string _data;
struct PointerCompare {
bool operator()(const Node* l, const Node* r) {
return *l < *r;
}
};
public:
void add_child(Node* child)
{
sort(_children.begin(), _children.end(), PointerCompare());
}
bool operator<(const Node& node) const
{
return (this->_data.compare(node._data) == -1);
}
};
Run Code Online (Sandbox Code Playgroud)
此外,您operator<需要申报const.
您operator<()对Node对象的引用进行操作; 但是载体含有指针到Node对象,它们不能与该功能相比较.您必须明确地为算法提供适当的函数(接受指针作为参数的函数)sort().
| 归档时间: |
|
| 查看次数: |
23380 次 |
| 最近记录: |