玩命加载中 . . .

STL-map


映射map

map可以存储键-值对,不能重复的键,可以按键的大小排序,或者自定义
multimap可以重复的键
unordered_map查找时间复杂度为常数

初始化

map<int, string, Compare<int>> mapIntToString;
int --> string
Compare<int> 是排序结构

构造键值对

mapIntToString.insert(make_pair(23, "kavin"));
mapIntToString.insert(pair<int, string>(10, "jack"));
mapIntToString[100] = "lisa";
#include <iostream>
#include <map>
using namespace std;

// 自定义的排序结构
template<typename T>
struct Compare
{
    bool operator () (const T& key1, const T& key2) const {
        return key1 > key2;
    }
};

template<typename T>
void info(const T& se) {
    cout << "INFO: ";
    for (auto it = se.begin(); it != se.end(); it++) {
        cout << "(" << it->first << "->" << it->second << ")" << " ";
    }
    cout << endl;
}

int main(int argc, char const *argv[])
{
    map<int, string, Compare<int>> mapIntToString;
    mapIntToString.insert(make_pair(23, "kavin"));
    mapIntToString.insert(pair<int, string>(10, "jack"));
    mapIntToString[100] = "lisa";
    info(mapIntToString);
    auto it = mapIntToString.find(100);
    if (it != mapIntToString.end()) {
        cout << "Found: " << it->first << "->" << it->second << endl;
    }
    // mapIntToString.erase(it);
    mapIntToString.erase(10);
    info(mapIntToString);

    return 0;
}
INFO: (100->lisa) (23->kavin) (10->jack) 
Found: 100->lisa
INFO: (100->lisa) (23->kavin) 

multimap

int main(int argc, char const *argv[])
{
    multimap<int, string> multimapIntToString(mapIntToString.begin(), mapIntToString.end());
    multimapIntToString.insert(make_pair(100, "lili"));
    info(multimapIntToString);
    cout << multimapIntToString.count(100) << endl;
    it = multimapIntToString.find(100);
    if (it != multimapIntToString.end()) {
        size_t numOfKey = multimapIntToString.count(100);
        for (size_t i = 0; i < numOfKey; i++) {
            cout << "Found: " << it->first << "->" << it->second << endl;
            ++it;
        }
    }
    return 0;
}

INFO: (100->lisa) (23->kavin) 
INFO: (23->kavin) (100->lisa) (100->lili) 
2
Found: 100->lisa
Found: 100->lili

用循环的方式遍历找到的值


文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录