c++ map用法

#include <iostream>
#include <map>


using namespace std;

class Test_t {
    private:
        int a;

    public:
        Test_t(int a)
        {
            this->a = a;
        }

        ~Test_t()
        {
            cout << "destory Test_t" << endl;
        }

        void show(void)
        {
            cout << "a = " << a << endl;
        }
};

typedef map<int, Test_t *> Test_map_t;

Test_map_t g_test_map;

void init_map(void)
{
    Test_t *t1 = new Test_t(1);
    Test_t *t2 = new Test_t(2);
    pair<Test_map_t::iterator, bool> ret;

    ret = g_test_map.insert(pair<int, Test_t *>(1, t1));
    if (!ret.second) {
        cout << "Failed to insert t1 into 1" << endl;
    }

    ret = g_test_map.insert(pair<int, Test_t *>(2, t2));
    if (!ret.second) {
        cout << "Failed to insert t2 into 2" << endl;
    }
    /* example: failed to insert */
    ret = g_test_map.insert(pair<int, Test_t *>(1, t2));
    if (!ret.second) {
        cout << "Failed to insert t2 into 1" << endl;
    }
}

void show_map(void)
{
    Test_map_t::iterator iter = g_test_map.begin();
    while (iter != g_test_map.end()) {
        cout << iter->first << ": ";
        iter->second->show();
        ++iter;
    }
}

void remove_map(void)
{
    Test_map_t::iterator iter = g_test_map.begin();
    cout << "size = " << g_test_map.size() << endl;
    while (iter != g_test_map.end()) {
        cout << iter->first << " is removed" << endl;
        delete iter->second;
        g_test_map.erase(iter);
        ++iter;
    }
    cout << "size = " << g_test_map.size() << endl;
}

void erase_map(void)
{
    cout << "size = " << g_test_map.size() << endl;
    while (!g_test_map.empty()) {
        cout << (g_test_map.begin())->first << " is erased" << endl;
        delete (g_test_map.begin())->second;
        g_test_map.erase(g_test_map.begin());
    }
    cout << "size = " << g_test_map.size() << endl;
}

Test_t *find_test_by_index(int index)
{
    auto iter = g_test_map.find(index);
    //Test_map_t::iterator iter = g_test_map.find(index);
    if (iter == g_test_map.end()) {
        return nullptr;
    }
    return iter->second;
}

int main(int argc, char *const argv[])
{
    Test_t *t = nullptr;

    init_map();
    show_map();

    cout << "find index = 2" << endl;
    t = find_test_by_index(2);
    if (nullptr != t) {
        t->show();
    }

    cout << "OK" << endl;
    remove_map();
    return 0;
}


result:

$ g++ -std=c++11 test.cpp
$ ls
a.out  test.cpp
$ ./a.out
Failed to insert t2 into 1
1: a = 1
2: a = 2
find index = 2
a = 2
OK
size = 2
1 is removed
destory Test_t
2 is removed
destory Test_t
size = 0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值