c++map的用法

begin() 返回指向map头部的迭代器

clear() 删除所有元素

count() 返回指定元素出现的次数

empty() 如果map为空则返回true

end() 返回指向map末尾的迭代器

equal_range() 返回特殊条目的迭代器对

erase() 删除一个元素 find() 查找一个元素

get_allocator() 返回map的配置器

insert() 插入元素 key_comp() 返回比较元素key的函数

lower_bound() 返回键值>=给定元素的第一个位置

max_size() 返回可以容纳的最大元素个数

rbegin() 返回一个指向map尾部的逆向迭代器

rend() 返回一个指向map头部的逆向迭代器

size() 返回map中元素的个数

swap() 交换两个map upper_bound() 返回键值>给定元素的第一个位置

value_comp() 返回比较元素value的函数

    map<string, int> m;
    //键值对插入
    m.insert(pair<string,int>("one",1));
    m.insert(pair<string, int>("two", 2));
    m.insert(pair<string, int>("three", 3));
    //类型插入
    m.insert(map<string, int>::value_type("four", 4));
    //数组插入
    m["five"] = 5;

    cout <<"one的值是:"<< m["one"] << endl;
    cout << "m中元素的个数:" << m.size() << endl;

    //迭代器迭代
    map<string, int>::iterator itor;
    for (itor=m.begin(); itor!=m.end(); itor++){
        cout << itor->first<<":"<<itor->second << endl;
    }

    //查找键
    itor = m.find("one");
    if (itor!=m.end())
    {
        cout << "找到键为one的元素,值为:" << itor->second<< endl;
    }

    //查找符合条件的个数
    int x=m.count("two");
    cout << "键为one的元素的出现次数为:" << x<< endl;

    //清除迭代器指定的
    m.erase(itor);

    //清除所有,等效于m.clear();
    m.erase(m.begin(),m.end());

    //map中没有sort,因为是默认升序排列的

    std::getchar();
    return 0;
原文地址:https://www.cnblogs.com/xietianjiao/p/12876488.html