【C++從入門到放棄】集合list,map的curd操作示例


#include <iostream>
#include <vector>
#include <map>

void func(int &b) {
    b = b * b;
}


int main() {
    using namespace std;

    {
        vector <string> vec2;
        vec2.push_back("11");
        vec2.push_back("22");
        vec2.push_back("33");

        for (auto o:vec2) {
            cout << "for o2:" << o << endl;
        }
        cout << endl;

        for (int i = 0; i < vec2.size(); i++) {
            cout << "fori o2:" << vec2[i] << endl;
        }
        cout << endl;

        vector<string>::iterator it;
        for (it = vec2.begin(); it != vec2.end(); it++) {
            cout << "iteraror o2:" << *it << endl;
        }
        cout << endl;
    }

    {
        map<int, string> mp;
        mp.insert(pair<int, string>(2, "b")); // 第一種 用insert函數插入pair
        mp.insert(map<int, string>::value_type(3, "student_one")); // 第二種 用insert函數插入value_type數據
        mp[1] = "a"; // 第三種 用"array"方式插入

        for (auto m:mp) {
            cout << "iteraror m:" << m.first << ":" << m.second.c_str() << endl;
        }
        cout << endl;

        map<int, string>::iterator it;
        for (it = mp.begin(); it != mp.end(); it++) {
            //printf("%d-->%s\n", it->first, it->second.c_str());
            cout << "iteraror m:" << it->first << ":" << it->second.c_str() << endl;
        }
        cout << endl;

        // find 返回迭代器指向當前查找元素的位置否則返回map::end()位置
        it = mp.find(2);
        if (it != mp.end())
            cout << "Find, the value is:" << it->second << endl;
        else
            cout << "Do not Find" << endl;
    }
}

運行結果如下:

g++ listmap.cpp -o listmap.out ; ./listmap.out
for o2:11
for o2:22
for o2:33

fori o2:11
fori o2:22
fori o2:33

iteraror o2:11
iteraror o2:22
iteraror o2:33

iteraror m:1:a
iteraror m:2:b
iteraror m:3:student_one

iteraror m:1:a
iteraror m:2:b
iteraror m:3:student_one

Find, the value is:b

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章