在C++中,使用std::map
作為關(guān)聯(lián)容器時(shí),有多種方法可以進(jìn)行拷貝
#include<iostream>
#include <map>
int main() {
std::map<int, std::string> map1 = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用拷貝構(gòu)造函數(shù)創(chuàng)建一個(gè)新的map
std::map<int, std::string> map2(map1);
// 輸出拷貝后的map
for (const auto& pair : map2) {
std::cout<< pair.first << ": "<< pair.second<< std::endl;
}
return 0;
}
#include<iostream>
#include <map>
int main() {
std::map<int, std::string> map1 = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用賦值操作符創(chuàng)建一個(gè)新的map
std::map<int, std::string> map2;
map2 = map1;
// 輸出拷貝后的map
for (const auto& pair : map2) {
std::cout<< pair.first << ": "<< pair.second<< std::endl;
}
return 0;
}
std::copy
(不推薦):注意:這種方法并不會(huì)復(fù)制原始map
的內(nèi)部結(jié)構(gòu),而是將相同的鍵值對(duì)插入到新的map
中。因此,在大多數(shù)情況下,不推薦使用這種方法。
#include<iostream>
#include <map>
#include<algorithm>
int main() {
std::map<int, std::string> map1 = {{1, "one"}, {2, "two"}, {3, "three"}};
// 使用std::copy創(chuàng)建一個(gè)新的map
std::map<int, std::string> map2;
std::copy(map1.begin(), map1.end(), std::inserter(map2, map2.end()));
// 輸出拷貝后的map
for (const auto& pair : map2) {
std::cout<< pair.first << ": "<< pair.second<< std::endl;
}
return 0;
}
總之,使用拷貝構(gòu)造函數(shù)或賦值操作符是在C++中拷貝std::map
的最佳實(shí)踐。這些方法簡單、高效,并且能夠保留原始map
的內(nèi)部結(jié)構(gòu)。