Posts C++primer-p10 泛型
Post
Cancel

C++primer-p10 泛型

1. set 与 map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void test1101(){
    map<string,size_t> map;
    set<string> set = {"a","and","so","unh.."};
    string word;
    while (cin>>word){
        if (set.find(word) == set.end())
            ++map[word];
    }
    for (const auto &item : map)
        cout << item.second << endl;
}

void test1102(){
    set<int> set {4,1,3,6,9};
    for (const auto &item : set)
        cout << item << endl;
}
  1. 不允许重复
  2. 有序,红黑树

2. multiset 与 multimap

1
2
3
4
5
6
7
8
9
void test1103(){
    vector<int> vec(10,1);

    set<int> set(vec.begin(),vec.end());
    cout << set.size() << endl;

    multiset<int> multiset(vec.begin(), vec.end());
    cout << multiset.size() << endl;
}
  1. 允许重复
  2. 有序,红黑树

2.1自定义比较函数

1
2
3
4
5
6
7
8
9
10
11
12
 bool compaer(const int &i,const int &j){
    return i<j;
}
void test1104(){

    multiset<int, decltype(compaer)*> set(compaer);
    for (int i = 0; i < 10; ++i) {
        set.insert(i);
    }
    for (const auto &item : set)
        cout << item << endl;
}

2.2 不可以改变set 与 map 的key 值

2.3 插入

1
2
3
4
5
6
7
void test1106(){
    vector<int> vec(10,1);
    set<int> set(vec.begin(), vec.end());

    auto p = set.insert(1);
    cout << p.second << endl;
}

不管是map还是set,插入时返回一个pair<iterator,bool>,前者返回插入时的位置迭代器,后者返回插入是否成功。

2.4 删除

erase,返回删除个数,size_t;

3. 无序unordered_map()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class User{
public:
    string name;
    int pwd;
};

size_t hasher(const User &user){
    return hash<string>() (user.name);
}

bool eqOp(const User &u1,const User &u2){
    return u1.name == u2.name;
}

void test1107(){
        unordered_multiset<User, decltype(hasher)*, decltype(eqOp)*> bookSet(42,  hasher, eqOp);//  42 为桶的大小
}
This post is licensed under CC BY 4.0 by the author.

Contents

Trending Tags