您的位置:首页 > 编程语言 > C语言/C++

C++中的集合和字典(unordered_set, unordered_map)

2017-07-01 22:07 555 查看
C++中的集合和字典是非常常用的结构,插入/查找都是O(1),代码示例挑选于C++ reference: http://www.cplusplus.com/reference/unordered_set/unordered_set/clear/

unordered_set:

#include <iostream>
#include <string>
#include <array>
#include <unordered_set>
using namespace std;

void SetMain()
{
std::unordered_set<std::string> myset = { "yellow","green","blue" };
std::array<std::string, 2> myarray = { "black","white" };
std::string mystring = "red";

myset.insert(mystring);                        // copy insertion
myset.insert(mystring + "dish");                 // move insertion
myset.insert(myarray.begin(), myarray.end());  // range insertion
myset.insert({ "purple","orange" });           // initializer list insertion

std::cout << "myset contains:";
for (const std::string& x : myset) std::cout << " " << x;
std::cout << std::endl;

// Possible output:
// myset contains : green blue reddish white yellow black red orange purple

// find
std::unordered_set<std::string> myset1 = { "red","green","blue" };

std::string input;
std::cout << "color? ";
getline(std::cin, input);

std::unordered_set<std::string>::const_iterator got = myset1.find(input);

if (got == myset1.end())
std::cout << "not found in myset1";
else
std::cout << *got << " is in myset1";

std::cout << std::endl;

// size(), empty(), clear()

}


unordered_map:

#include <iostream>
#include <string>
#include <unordered_map>

void MapMain()
{
// unordered_map::find
std::unordered_map<std::string, double> mymap = {
{ "mom",5.4 },
{ "dad",6.1 },
{ "bro",5.9 } };

std::string input;
std::cout << "who? ";
getline(std::cin, input);

std::unordered_map<std::string, double>::const_iterator got = mymap.find(input);

if (got == mymap.end())
std::cout << "not found";
else
std::cout << got->first << " is " << got->second;

std::cout << std::endl;

// unordered_map::insert
std::unordered_map<std::string, double>
myrecipe,
mypantry = { { "milk",2.0 },{ "flour",1.5 } };

std::pair<std::string, double> myshopping("baking powder", 0.3);

myrecipe.insert(myshopping);                        // copy insertion
myrecipe.insert(std::make_pair<std::string, double>("eggs", 6.0)); // move insertion
myrecipe.insert(mypantry.begin(), mypantry.end());  // range insertion
myrecipe.insert({ { "sugar",0.8 },{ "salt",0.1 } });    // initializer list insertion

std::cout << "myrecipe contains:" << std::endl;
for (auto& x : myrecipe)
std::cout << x.first << ": " << x.second << std::endl;

std::cout << std::endl;

// Possible output :
// myrecipe contains :
// salt: 0.1
// eggs : 6
// sugar : 0.8
// baking powder : 0.3
// flour : 1.5
// milk : 2

// size(), empty(), clear()
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: