C++ Cookbook 是一本关于 C++ 编程的实用教程,其中包含了许多关于 STL(Standard Template Library)容器的用法示例
- 向量(Vector):
#include#include int main() { std::vector vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); for (int i = 0; i < vec.size(); ++i) { std::cout<< vec[i] << " "; } return 0; }
- 列表(List):
#include#include int main() { std::list
lst; lst.push_back(1); lst.push_back(2); lst.push_back(3); for (std::list ::iterator it = lst.begin(); it != lst.end(); ++it) { std::cout << *it << " "; } return 0; }
- 双端队列(Deque):
#include#include int main() { std::deque deq; deq.push_back(1); deq.push_front(0); deq.push_back(2); for (int i = 0; i < deq.size(); ++i) { std::cout << deq[i] << " "; } return 0; }
- 集合(Set):
#include#include int main() { std::set s; s.insert(3); s.insert(1); s.insert(2); for (std::set ::iterator it = s.begin(); it != s.end(); ++it) { std::cout << *it << " "; } return 0; }
- 多重集合(Multiset):
#include#include int main() { std::multiset ms; ms.insert(3); ms.insert(1); ms.insert(2); ms.insert(3); for (std::multiset ::iterator it = ms.begin(); it != ms.end(); ++it) { std::cout << *it << " "; } return 0; }
- 映射(Map):
#include#include
- 多重映射(Multimap):
#include#include
- 无序集合(Unordered Set):
#include#include int main() { std::unordered_set us; us.insert(3); us.insert(1); us.insert(2); for (std::unordered_set ::iterator it = us.begin(); it != us.end(); ++it) { std::cout << *it << " "; } return 0; }
- 无序多重集合(Unordered Multiset):
#include#include int main() { std::unordered_multiset ums; ums.insert(3); ums.insert(1); ums.insert(2); ums.insert(3); for (std::unordered_multiset ::iterator it = ums.begin(); it != ums.end(); ++it) { std::cout << *it << " "; } return 0; }
- 无序映射(Unordered Map):
#include#include int main() { std::unordered_map um; um['a'] = 1; um['b'] = 2; um['c'] = 3; for (std::unordered_map ::iterator it = um.begin(); it != um.end(); ++it) { std::cout << it->first << ": " << it->second << " "; } return 0; }
- 无序多重映射(Unordered Multimap):
#include#include int main() { std::unordered_multimap umm; umm.insert(std::make_pair('a', 1)); umm.insert(std::make_pair('b', 2)); umm.insert(std::make_pair('c', 3)); umm.insert(std::make_pair('a', 4)); for (std::unordered_multimap ::iterator it = umm.begin(); it != umm.end(); ++it) { std::cout << it->first << ": " << it->second << " "; } return 0; }
这些示例展示了如何使用 C++ STL 容器。你可以根据需要选择合适的容器类型,并学习如何使用它们的成员函数来操作数据。在实际项目中,你可能需要根据特定需求和性能要求选择合适的容器。