To traverse an STL container, you can use the container's begin() and end() functions to obtain the iterator range: Vector: Use a for loop to traverse the iterator range. Linked list: Use the next() member function to traverse the elements of the linked list. Mapping: Get an iterator of key-value pairs and use a for loop to traverse.
How to traverse C++ STL containers
Traversing C++ Standard Template Library (STL) containers is essential in programmers’ daily work a task. STL provides a series of predefined data structures such as vectors, linked lists, and maps, each with its own traversal methods.
To traverse a vector, we can use the begin()
and end()
functions to obtain the iterator range:
#include <vector> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; // 使用基于范围的 for 循环 for (int num : v) { std::cout << num << " "; } std::cout << std::endl; // 使用迭代器 for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }
Output:
1 2 3 4 5 1 2 3 4 5
To traverse a linked list, we can use the front()
and# of the linked list ##back() function and the
next() member function of the linked list:
#include <list> int main() { std::list<int> l = {1, 2, 3, 4, 5}; // 使用基于范围的 for 循环 for (int num : l) { std::cout << num << " "; } std::cout << std::endl; // 使用迭代器 std::list<int>::iterator it = l.begin(); while (it != l.end()) { std::cout << *it << " "; it = it->next(); } std::cout << std::endl; return 0; }
Output:
1 2 3 4 5 1 2 3 4 5
begin() and
end() functions to get an iterator of key-value pairs:
#include <map> int main() { std::map<std::string, int> m = {{"Apple", 1}, {"Banana", 2}, {"Cherry", 3}}; // 使用基于范围的 for 循环 for (auto const& [key, value] : m) { std::cout << key << ": " << value << std::endl; } std::cout << std::endl; // 使用迭代器 for (std::map<std::string, int>::iterator it = m.begin(); it != m.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } return 0; }
Output:
Apple: 1 Banana: 2 Cherry: 3 Apple: 1 Banana: 2 Cherry: 3
The above is the detailed content of How to iterate over a C++ STL container?. For more information, please follow other related articles on the PHP Chinese website!