c++11新增的容器1:array
当时的初衷是希望提供一个在栈上分配的,定长数组,而且可以使用stl中的模板算法。
array的用法如下:
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
int main
{
// construction uses aggregate initialization
std::array<int, 3> a1{ {1, 2, 3} }; // double-braces required in C++11 (not in C++14)
std::array<int, 3> a2 = {1, 2, 3}; // never required after =
std::array<std::string, 2> a3 = { std::string("a"), "b" };
// container operations are supported
std::sort(a1.begin, a1.end);
std::reverse_copy(a2.begin, a2.end,
std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// ranged for loop is supported
for(const auto& s: a3)
std::cout << s << ' ';
}c++11中新增的容器:unordered_map unordered_set
在早期的标准库stl中是只有红黑树map,而没有hash map的。
所以boost提供了unordered这个组件,并且在c++11中进入了标准库。
unordered_map提供了和map类似的接口,只是map是有序,而unordered_map因为采用hash map的数据结构,所以是无序的。
另外,因为map采用的是红黑树,所以查找性能是O(log(n))。而unordered_map采用hash map,所以查找性能是O(1)。
所以一般来说小规模的数据适合采用map(百W以下),而大规模的数据适合unordered_map(百W以上)
unordered_map使用如下:
#include <iostream>
#include <string>
#include <unordered_map>
int main
{
// Create an unordered_map of three strings (that map to strings)
std::unordered_map<std::string, std::string> u = {
{"RED","#FF0000"},
{"GREEN","#00FF00"},
{"BLUE","#0000FF"}
};
// Iterate and print keys and values of unordered_map
for( const auto& n : u ) {
std::cout << "Key:[" << n.first << "] Value:[" << n.second << "]\n";
}
// Add two new entries to the unordered_map
u["BLACK"] = "#000000";
u["WHITE"] = "#FFFFFF";
// Output values by key
std::cout << "The HEX of color RED is:[" << u["RED"] << "]\n";
std::cout << "The HEX of color BLACK is:[" << u["BLACK"] << "]\n";
return 0;
}c++11中新增的容器:非成员begin\end
std::begin/std::end并不是容器,但是因为设计std::begin/std::end的目的应该是为了让传统的C风格数组可以使用stl中的模板算法,所以也放在这里介绍。
std::begin/std::end使用如下:
#include <iostream>
#include <vector>
#include <iterator>
int main
{
std::vector<int> v = { 3, 1, 4 };
auto vi = std::begin(v);
std::cout << *vi << '\n';
int a = { -5, 10, 15 };
auto ai = std::begin(a);
std::cout << *ai << '\n';
}abelkhan技术论坛:
http://abelkhan.com/forum.php,欢迎大家交流技术
