【问题标题】:insert into std::map using class method使用类方法插入 std::map
【发布时间】:2017-04-27 16:39:07
【问题描述】:

我搜索了很多关于这个问题,但没有找到任何东西,如果重复,请见谅。

我在使用返回 *this 的类方法插入 std::map 时遇到问题。如果我尝试插入更多值,则实际上只插入第一个值。让我给你看我的代码:

using namespace std;

class test{
public:
   test(){}
   test Add(const int &a, const  int &b);
   void print(){
    for (auto it = map1.begin(); it != map1.end(); ++it) {
        cout << it->first << " " << it->second << endl;
    }
}

private:
   map<int,int> map1;

};

test test::Add(const int &a, const int &b) {

map1.insert(make_pair(a,b));

return *this;

}

但是当我尝试这样的事情时:

int main ( void ) {

test a;

a.Add(1,5) . Add( 4, 8);

a.print();

return 0;
}

只有第一个值被插入到地图中。我应该改变什么才能以这种方式插入地图?

非常感谢您的帮助。

【问题讨论】:

    标签: c++ class dictionary stl this


    【解决方案1】:

    你的错误是

    test Add(const int &a, const  int &b);
    

    按值返回。这意味着从Add 返回的test 与您调用它的test 不同,它是一个副本。这意味着当你做类似的事情时

    a.Add(1,5) . Add( 4, 8);
    

    . Add( 4, 8) 部分将项目添加到 a 的副本而不是 a 本身。

    解决此问题的方法是通过引用而不是值返回。当您通过引用返回时,您将使用您称为add 的项目而不是副本。这意味着您只需要将函数签名更改为

    test& Add(const int &a, const  int &b)
    

    对于声明和定义。

    【讨论】:

    • 非常感谢!它解决了问题。
    • @Cart 没问题。很高兴能提供帮助。
    【解决方案2】:

    您插入一次的原因是因为您的 Add 方法按值返回,而您的第二个 . Add( 4, 8); 最终插入到另一个地图中。要解决此问题,您需要更改您的 Add 以返回对 *this 的引用:

    using namespace std;
    
    class test
    {
    public:
        test() {}
        test& Add(const int &a, const  int &b); // < -- changed to return test&
        void print() {
            for (auto it = map1.begin(); it != map1.end(); ++it) {
                cout << it->first << " " << it->second << endl;
            }
        }
    
    private:
        map<int, int> map1;
    };
    
    test& test::Add(const int &a, const int &b) // < -- changed to return test&
    {
        map1.insert(make_pair(a, b));
        return *this;
    }
    

    Output of your program with the fix 变为:

    1 5
    4 8
    

    【讨论】:

      【解决方案3】:

      问题在于您的Add 函数正在返回当前对象的副本。要返回当前对象本身,需要将返回类型更改为引用:

      test & test::Add(const int &a, const int &b) {
      // ^^^^^
        map1.insert(make_pair(a,b));
        return *this;
      }
      

      您当前的代码将第二个Add 应用于与第一个Add 应用到的对象不同的对象,因此您永远看不到效果。但是,对于欢笑和咯咯笑声,您也可以尝试:

      a.Add(1,5) . Add( 4, 8) . print();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-13
        • 2010-09-10
        • 2011-05-30
        • 1970-01-01
        • 2019-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多