在C++中,set和unordered_set都是用来存储唯一元素的容器,但它们之间有一些不同之处。在遍历方面,两者的性能也有所不同。
std::set<int> s = {1, 2, 3, 4, 5};
// 使用迭代器遍历set
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it << " ";
}
// 使用范围for循环遍历set
for (int val : s) {
std::cout << val << " ";
}
std::unordered_set<int> us = {1, 2, 3, 4, 5};
// 使用迭代器遍历unordered_set
for (auto it = us.begin(); it != us.end(); ++it) {
std::cout << *it << " ";
}
// 使用范围for循环遍历unordered_set
for (int val : us) {
std::cout << val << " ";
}
总的来说,set在遍历时有序性更好,而unordered_set在查找元素时更快。根据实际需求选择合适的容器来存储和遍历数据。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++ std::set与std::unordered_set区别