c++ - for_each 和 mem_fun_ref 麻烦

标签 c++ for-loop each

我用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

关于c++ - for_each 和 mem_fun_ref 麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863916/

相关文章:

javascript - 使用 jQuery .each() 读取任何 html 值并更改它

jquery - 打破 Jquery 每个循环的问题?

c++ - const 成员作为非常量返回

c++ - QTableWidget 中的 Star Delegate

c - C中的循环问题

javascript - 编写一个代表 8×8 网格的程序?

javascript JSON 高级

c++ - 在 Linux 和 Eclipse IDE 中使用 FFTW 库的问题

c++ - Visual Studio 2005/08/10 是否会取代嵌入式 Visual C++ 4.0?

java - 如何循环按钮?