【问题标题】:Sorting a vector of custom objects with const member使用 const 成员对自定义对象的向量进行排序
【发布时间】:2017-11-15 21:41:07
【问题描述】:

我想使用const 成员变量对包含类对象的向量进行排序。
不幸的是,我收到一条错误消息,指出 “没有用于调用“swap”的匹配函数”

当我删除 idconst 关键字时,std::sort() 可与重载的 operator<() 和自定义比较函数一起使用。

为什么会这样?我一般不能对属于具有 const 成员变量的类的对象进行排序吗?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct A
{
    const int id;
    A(int id) : id(id) {}
    bool operator<(const A &other) const
    {
        return id < other.id;
    }
};

bool cmp(const A &lhs, const A &rhs)
{
    return lhs.id < rhs.id;
}

int main()
{
    vector<A> vec;
    vec.emplace_back(3);
    vec.emplace_back(0);
    vec.emplace_back(2);
    vec.emplace_back(1);
    std::sort(vec.begin(), vec.end());
    std::sort(vec.begin(), vec.end(), cmp);
}

【问题讨论】:

  • @EvanTeran A 具有复制和移动构造函数。 std::swap 的问题在于赋值运算符。
  • @aschepler 感谢您的更正。在将我的评论转换为答案时,我确保它是正确的:-)
  • A(int id) : id(id) {} 这不是个好主意
  • @Slava 为什么不呢?

标签: c++ sorting stl


【解决方案1】:

好吧,实现排序的方式是它会根据需要交换对象。具有 const 成员且没有复制或移动赋值运算符的类不会“可交换”。

我可能会将id 成员设为私有且非常量。然后我将通过 getter 访问它(但不提供 setter)。使其在逻辑上为 const,但该类是可复制的。

类似这样的:

class A {
public:
    A(int id) : id_(id) {}

    bool operator<(const A &other) const {
        return id_ < other.id_;
    }

    int id() const { return id_; }

private:
    int id_;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多