c++从一个map复制到另一个map

$ cat test_map.cpp
#include <iostream>
#include <map>

using namespace std;

class Test {
    public:
        int a;
        int b;
        Test(int a, int b)
        {
            this->a = a;
            this->b = b;
        }

        Test(const Test &t)
        {
            this->a = t.a;
            this->b = t.b;
        }
};

void func_1(void)
{
    Test a1(1, 2);
    Test a2(3, 4);

    map<int, Test> m1;
    m1.insert(pair<int, Test>(1, a1));
    m1.insert(pair<int, Test>(2, a2));

    cout << "iter: m1" << endl;
    map<int, Test>::iterator iter;
    for (iter = m1.begin(); iter != m1.end(); iter++) {
        Test &tmp = iter->second;
        cout << "a1[" <<  iter->first << "]: a = " << tmp.a << ", b = " << tmp.b << endl;
    }
    cout << "iter: m2" << endl;
    map<int, Test> m2;
#if 0
    m2 = m1;
#else
    m2.insert(m1.begin(), m1.end());
#endif
    for (iter = m2.begin(); iter != m2.end(); iter++) {
        Test &tmp = iter->second;
        cout << "a1[" <<  iter->first << "]: a = " << tmp.a << ", b = " << tmp.b << endl;
    }

}

void func_2(void)
{
    Test a1(1, 2);
    Test a2(3, 4);

    map<int, Test> m1;
    m1.insert(pair<int, Test>(1, a1));
    m1.insert(pair<int, Test>(2, a2));

    cout << "iter: m1" << endl;
    map<int, Test>::iterator iter;
    for (iter = m1.begin(); iter != m1.end(); iter++) {
        Test &tmp = iter->second;
        cout << "a1[" <<  iter->first << "]: a = " << tmp.a << ", b = " << tmp.b << endl;
    }
    cout << "iter: m2" << endl;
    map<int, Test> m2;

#if 1
    //m2 = m1;
    for (iter = m1.begin(); iter != m1.end(); iter++) {
        m2.insert(pair<int, Test>(iter->first, iter->second));
    }
#else
    m2.insert(m1.begin(), m1.end());
#endif
    for (iter = m2.begin(); iter != m2.end(); iter++) {
        Test &tmp = iter->second;
        cout << "a1[" <<  iter->first << "]: a = " << tmp.a << ", b = " << tmp.b << endl;
    }

}

int main()
{
    //func_1();
    func_2();
    return 0;
}
hi
# g++ test_map.cpp -std=c++11 
$ ./a.out
iter: m1
a1[1]: a = 1, b = 2
a1[2]: a = 3, b = 4
iter: m2
a1[1]: a = 1, b = 2
a1[2]: a = 3, b = 4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值