C++:map.insert插入重複鍵(已存在鍵)將忽略,而非值覆蓋

C++:map.insert插入重複鍵(已存在鍵)將忽略,而非值覆蓋

測試代碼:

#include <iostream>
#include <map>

using namespace std;

int main() {
    map<int, int> mymap;
    int i = 0;
    for (; i < 10; i++) {
        mymap.insert(pair<int, int>(1280, i));
    }   

    map<int, int>::iterator it = mymap.begin();
    while (it != mymap.end()) {
        cout << it->first << endl;
        cout << it->second << endl;
        it++;
    }   

    return 0;
}

編譯 & 運行:

$ g++ -o main main.C
$ ./main
1280
0

輸出的值是0,而非9,說明每次map.insert,相同鍵的值將被忽略,而不是覆蓋。


#include <iostream>
#include <map>

using namespace std;

int main() {
	map<int, int> mymap;
	int i = 0;
	for (; i < 10; i++) {
		mymap.insert(make_pair(1280, i));
	}

	map<int, int>::iterator it = mymap.begin();
	while (it != mymap.end()) {
		cout << it->first << endl;
		cout << it->second << endl;
		it++;
	}

	return 0;
}

同上。

map.insert(pair(…))
map.insert(make_pair(…))


參考:

1.https://blog.csdn.net/qc530167365/article/details/91371603
2.https://www.cnblogs.com/tianzeng/p/9017148.html

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