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 thebegin()
andend()
functions to obtain the iterator range:
#includeint main() { std::vector v = {1, 2, 3, 4, 5}; // 使用基于范围的 for 循环 for (int num : v) { std::cout << num << " "; } std::cout << std::endl; // 使用迭代器 for (std::vector ::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 thefront()
and# of the linked list ##back()function and the
next()member function of the linked list:
#includeint main() { std::list
l = {1, 2, 3, 4, 5}; // 使用基于范围的 for 循环 for (int num : l) { std::cout << num << " "; } std::cout << std::endl; // 使用迭代器 std::list ::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
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!