c++11新增的容器1:array
array最早是在boost中出現:http://www.boost.org/doc/libs/1_61_0/doc/html/array.html
當時的初衷是希望提供一個在棧上分配的,定長數組,而且可以使用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
同樣是來至boost的組件:http://www.boost.org/doc/libs/1_61_0/doc/html/unordered.html
在早期的標准庫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,歡迎大家交流技術