• STL map类测试


    /*
    STL map类的使用示例
    功能:常用增删改查函数测试
    */
    
    #include <map>
    #include <string>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    // 无参构造对象
    map<char, string> m;
    map<int, int> m1;
    // 1、常用插入数据的方式
    // (1)call insert(ValTy&&) version 
    m.insert(make_pair('a', "apple"));
    // (2)call insert(const value_type&) version
    m1.insert({ { 4, 44 }, { 2, 22 }, { 3, 33 }, { 1, 11 }, { 5, 55 } });
    m.insert({ 'b', "balance" });
    // (3)使用运算符: 对象名[key] = Value
    m['c'] = "clone";
    
    // 2、常用遍历map表方式
    // (1)使用迭代器iterator it->first表示key it->second表示value
    map<char, string>::iterator it = m.begin();
    while (it != m.end())
    {
    cout << it->first << "<--->" << (it->second).c_str() << endl;
    ++it;
    }
    // (2)使用下标遍历
    // map < int, CString > 或者 map < int, 结构体名>的元素遍历
    int nSize = m1.size();
    for(int i = 1; i <= nSize; ++i)
    cout << m1[i] << endl;
    
    // 3、 查询表内是否存在指定的key 
    // (1)使用find方法
    //iterator find(const Key& _Key);
    //const_iterator find(const Key& _Key) const;
    
    map<char, string>::iterator m_RcIter = m.find('a');
    
    if (m_RcIter == m.end())
    cout << "The map m doesn't have an element "
    << "with a key of 'a'." << endl;
    else
    cout << "The element of map m with a key of 'a' is: "
    << m_RcIter->second << "." << endl;
    
    m_RcIter = m.find('g');
    if (m_RcIter == m.end())
    cout << "The map m doesn't have an element "
    << "with a key of 'g'." << endl;
    else
    cout << "The element of map m with a key of 'g' is: "
    << m_RcIter->second << "." << endl;
    
    // (2)使用 Count方法来查询
    //size_type count(const Key& _Key) const;
    bool i = m.count('d');
    cout << "The number of elements in m1 with a sort key of 'd' is: "
    << i << "." << endl;
    
    // (3)使用at()方法,如果没找到,则中断程序,弹出一个断言
    //Type& at(const Key& _Key);
    //const Type& at(const Key& _Key) const;
    string str1 = m.at('a');
    
    // 4、 删除
    //iterator erase(iterator _Where); // 删除指定位置
    //iterator erase(iterator _First,iterator _Last); // 删除指定范围
    //size_type erase(const key_type& _Key); // 删除指定key
    int j = m1.erase(0);
    if (j)
    cout << "删除成功!" << endl;
    else
    cout << "删除失败!" << endl;
    map<int, int>::iterator m1_it;
    m1_it = m1.begin();
    m1.erase(m1_it);
    m1.erase(m1.begin(), m1.begin()++);
    
    return 0;
    }
    

      

  • 相关阅读:
    Swift
    Swift
    Swift
    Swift
    获取项目版本号与设置引导页的判断条件
    [iOS]简单的APP引导页的实现 (Swift)
    iOS
    文顶顶 iOS开发UI篇—UITabBarController简单介绍 iOS开发UI篇—UITabBarController简单介绍
    Swift开源项目精选
    Fuel 5.1安装openstack I版本号环境
  • 原文地址:https://www.cnblogs.com/veis/p/12548810.html
Copyright © 2020-2023  润新知