for_each and mem_fun_ref trouble

for_each and mem_fun_ref trouble

本文关键字:ref trouble fun and each for mem      更新时间:2023-10-16

我以for_each和mem_fun_ref为例,但是编译中有一些错误,有什么问题

#include<iostream>
#include<algorithm>
#include<set>
#include<iterator>
using namespace std;
class Tst
{
public:
    Tst(int a, string b):n(a),s(b)
{}
    bool operator<(const Tst& t)const
    {
        return this->n < t.n;
    }
    int GetN()const
    {
        return n;
    }   
    string GetS()const
    {   
        return s;
    }   
    void SetN(int a)
    {   
        n = a;
    }   
    void SetName(string name)
    {   
        s = name;
    }   
    void Print(void)
        {   
        cout <<"n is:" << n <<"ts is:" << s << endl;
    }
private:
    int n;
    string s;
};
int main(void)
{
    typedef set<Tst> TstSet;
TstSet tst;
tst.insert(Tst(10, "abc"));
tst.insert(Tst(1, "def"));
for_each(tst.begin(), tst.end(), mem_fun_ref(&Tst::Print));
return true;
}

:4200: 错误:对'(std::mem_fun_ref_t) (const Tst&)'的调用没有匹配,是什么原因

std::set包含的对象是const的,所以你只能对它们调用const函数。您的Print函数应标记为const

该函数应该const,因为std::set只适用于const对象

void Print(void)const
{
}