C++学习笔记 —— STL之set和map

文章目录


这里把set和map放到一块因为两者都是关联性容器,也就是说他们的存储顺序与放入元素顺序不同,他们会自动维护一个容器中元素的顺序。而且他们的api有很多相似之处。

set 集合

https://blog.csdn.net/sevenjoin/article/details/81908754
https://blog.csdn.net/ktigerhero3/article/details/78273497
set容器 不允许重复值 set是只读,他会自己排序,所以不能修改set里的元素比如不能set[3] = 4
multiSet 与set完全相同,唯一不同就是他允许重复元素. set和multiset底层都是红黑树实现的.

#include <iostream>
#include <string>
#include <set>
#include <vector>

using namespace std;

int main()
{
    set<int> arraySet;
    // 插入元素,set是有序的会自动对插入的数据进行排序,不能指定位置插,因为他会自己维护顺序
    // 关联式容器
    arraySet.insert(7);//返回的是一个bool值,若插入重复元素返回false
    arraySet.insert(4);
    arraySet.insert(5);
    arraySet.insert(6);
    arraySet.insert(5);
    //遍历
    set<int>::iterator it;  // it是迭代器,前面是他的类型
    // 遍历set集合,使用auto代替迭代器类型
    for (it = arraySet.begin(); it != arraySet.end(); it++) {
        cout << *it << ",";
    }  // 4, 5, 6, 7
    cout << endl;
    //大小
    cout << arraySet.size() << endl;  // 4

    //查找元素
    cout << *arraySet.find(5) << endl;  // 5 返回找到元素的迭代器,如果找不到则返回end()迭代器。
    if (arraySet.find(5) != arraySet.end()) {
        cout << "find num in set" << endl;
    } else {
        cout << "do not find num in set" << endl;
    }
    //删除元素
    arraySet.erase(7);
    //返回元素个数
    cout << arraySet.count(5) << endl;  // 1 返回某个值元素的个数,因为set是非重复的,结果为0或1,而Multiset就可以是多个
    cout << arraySet.count(3) << endl;  // 0

    cout << *arraySet.end() << endl;  // 4 指向最后一个元素的后面一个位置所以值不确定

    // 使用set给vector去重
    vector<int> vec;
    vec = {1, 2, 3, 4, 8, 9, 3, 2, 1, 0, 4, 8};  //初始化vector
    set<int> st(vec.begin(), vec.end());         // 初始化Set,把vector放到set中,set自动去重
    vec.assign(st.begin(), st.end());            // 再把set元素放回到vector中。
}

map

map会根据key自动排序,第一元素为key值,第二元素为value,不允许有两个相同的key值
MultiMap与map唯一区别是key值是可以重复的.


#include <iostream>
#include <map>

using namespace std;

void printMap(map<int, int> mapT)
{
    for (auto iter = mapT.begin(); iter != mapT.end(); iter++) {
        cout << "<" << iter->first << "," << iter->second << ">" << endl;
    }
    cout << endl;
}

int main()
{
    //使用数组方式初始化map
    map<int, int> mapT;
    mapT[1];    //会初始化key=1,value=0
    mapT[2]++;  //会初始化key=2,value=1
    printMap(mapT);

    // map插入数据三种方式
    map<int, int> m;
    m.insert(pair<int, int>(1, 10));  //插入key为1 value为10
    m.insert(make_pair(2, 20));       //插入<2,20>
    m[4] = 40;                        //插入<4,40>
    printMap(m);

    m.size();
    //删除
    m.erase(1); //删除key值为1的键值对
    //查找  返回的是一个迭代器
    map<int,int>:: iterator it = m.find(2);
    if (it != m.end())
    {
        cout<< "find key: " << it->first << " value: " << it->second << endl;
    }
    
    
}

https://juejin.im/entry/5b38f3b6e51d4558de5c0139

发布了103 篇原创文章 · 获赞 94 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/chongbin007/article/details/105646761