$ cat test_map.cpp
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;
m2 = m1;
m2.insert(m1.begin(), m1.end());
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;
//m2 = m1;
for (iter = m1.begin(); iter != m1.end(); iter++) {
m2.insert(pair<int, Test>(iter->first, iter->second));
}
m2.insert(m1.begin(), m1.end());
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
$ ./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