std::set acting up on insert.

2019-09-19 01:19发布

问题:

This is likely very simple. I have added an std::set<int> my_set; to my header file for some class. Then, in that classes implementation, I try to insert into this set. As an example, just doing my_set.insert(1); This is not compiling, which is very strange behaviour. Here is my compiler error:

error C2663: 'std::_Tree<_Traits>::insert' : 4 overloads have no legal conversion for 'this' pointer

The file I included to use set is #include <set>. What have I done wrong? I have not called the set anywhere else in the code.

回答1:

Since you're getting an error about this, but you're trying to insert an int, I'm gonna go out on a limb here and guess you're trying to do this in a const method.

class A
{
    std::set<int> my_set;
    void foo() 
    {
       my_set.insert(1); //OK
    }
    void foo() const
    {
       my_set.insert(1); //not OK, you're trying to modify a member
                         //std::set::insert is not const, so you can't call it
    }
};

Remove the const. It seems like the logical thing to do, since you're modifying members.



标签: c++ set