c++ - 使用 std::for_each 并在 std::set 上绑定(bind)成员函数,代码无法编译

标签 c++ c++11

当我使用 vector 时,我可以正常编译:

TEST(function_obj,bindMemeber1){

    std::vector<Person> v {234,234,1241,1241,213,124,152,421};
    std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}

但是当我使用 set 时,出现问题:

TEST(function_obj,bindMemeber1){
    std::set<Person,PersonCriterion> v{234,234,1241,1241,213,124,152,421};
    std::for_each(v.begin(),v.end(), std::bind(&Person::print,std::placeholders::_1) );
}

clion's tips IDE告诉我出了问题。当我强制IDE编译时,它也无法编译成功。

下面是Person的代码;

class Person{
private:
        size_t no;
        std::string name;
public:
        Person():no(0){};
        Person(size_t n): no(n){};
        Person(const Person& p):no(p.no),name(p.name){};
        friend class PersonCriterion;

    size_t getNo() const;
    void print(){
        std::cout<<no<<' ';
    }

    const std::string &getName() const;
};

class PersonCriterion{
public:
    bool operator()(const Person& p1,const Person& p2){
        return p1.no<=p2.no;
    }

};

size_t Person::getNo() const {
    return no;
}

const std::string &Person::getName() const {
    return name;
}

最佳答案

std::set 获取的元素是 const 限定的;它们应该是不可修改的。您应该将 Person::print 标记为 const,然后就可以在 const 对象上调用它。

class Person {
    ...
    void print() const {
    //           ^^^^^
        std::cout<<no<<' ';
    }
    ...
};

顺便说一句:最好将 PersonCriterion 中的 operator() 标记为 const

class PersonCriterion {
public:
    bool operator()(const Person& p1, const Person& p2) const {
        return p1.no<=p2.no;
    }
};

关于c++ - 使用 std::for_each 并在 std::set 上绑定(bind)成员函数,代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72095192/

相关文章:

c++ - 如何生成可变参数包?

c++ - 使用可变参数模板限制模板类的受支持类型

c++ - 调试和发布版本中的奇怪执行时间

c++ - 原始 C++ 指针是一流对象吗?

c++ - 如何比较 if 语句中的多个字符串?

c++ - shared_ptr 与 unique_ptr 与数组

c++ - std::system 即使在父进程退出后也会执行吗?

java - 如何将数据从 c++ 发送到 java - android

C++ 从无符号字符数组创建 GUID

c++ - 为什么将函数作为 &name 和 name 传递会给出不同的指针?