C++ 指针的排序向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7446743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:57:07  来源:igfitidea点击:

Sorting vector of pointers

c++sortingvector

提问by madshov

I'm having a little trouble trying to sort a vector of pointers.

我在尝试对指针向量进行排序时遇到了一些麻烦。

This is what I have done so far:

这是我到目前为止所做的:

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);
    }
};

My less-than operator works, if I write like this:

我的小于运算符有效,如果我这样写:

Node* root = new Node("abc");
Node* n = new Node("def");
cout << (*root<*n) << endl;

Why does sort never call the operator?? Any help would be appreciated! Thanks.

为什么 sort 从不调用运算符?任何帮助,将不胜感激!谢谢。

madshov

马德绍夫

回答by Sander De Dycker

Because you sort the pointer values, not the Nodes they point to.

因为您对指针值进行排序,而不是对Node它们指向的s 进行排序。

You can use the third argument of the std::sortalgorithm to specify a custom comparator.

您可以使用std::sort算法的第三个参数来指定自定义比较器。

For example :

例如 :

bool comparePtrToNode(Node* a, Node* b) { return (*a < *b); }

std::sort(_children.begin(), _children.end(), comparePtrToNode);

(note that this code is just an indication - you'll have to add extra safety checks where needed)

(请注意,此代码只是一个指示 - 您必须在需要时添加额外的安全检查)

回答by Rob?

Your less-than operator takes const Node&arguments, but your vector is sorting Node*s. You need to specify a comparison function as the third parameter to std::sort.

您的小于运算符接受const Node&参数,但您的向量正在对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);
    }
};

Also, your operator<needs to be declared const.

此外,您operator<需要声明const

回答by Ernest Friedman-Hill

Your operator<()operates on references to Nodeobjects; but the vector contains pointersto Nodeobjects, which can't be compared with that function. You'll have to explicitly supply a proper function (one that accepts pointers as arguments) to the sort()algorithm.

operator<()Node对象的引用进行操作;但是载体含有指针Node对象,它们不能与该功能相比较。您必须明确地为算法提供一个适当的函数(一个接受指针作为参数的函数)sort()