Home >Backend Development >C++ >Tips on using iterators in C++
C is a powerful programming language with many advanced features, such as iterators, which allow programmers to use data structures in the standard library more efficiently. This article will introduce the use of iterators so that you can better utilize the C standard library.
What is an iterator?
Iterator (iterator) is an important concept in C. It is a data access tool used to traverse elements in a container. It provides a universal way to access various containers, including vector , list, map, etc.
Iterators have the following types:
How to use iterator?
The following will introduce how to use iterators.
You can use iterators to traverse the elements in the container. The code is as follows:
std::vector<int> v{1, 2, 3, 4, 5}; for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; }
In the above code, the vector container is used The begin() and end() methods in get the start and end positions of the iterator, and then use a for loop to traverse the entire container.
Use iterators to insert or delete elements in the container. The code is as follows:
std::vector<int> v{1, 2, 3, 4, 5}; for (auto it = v.begin(); it != v.end(); ++it) { if (*it == 3) { // 插入元素 v.insert(it, 6); break; } } for (auto it = v.begin(); it != v.end(); ++it) { if (*it == 4) { // 删除元素 v.erase(it); break; } } for (auto i : v) { std::cout << i << " "; }
In the above code, use The insert() and erase() methods in the vector container are used to specify the position of the element to be inserted or deleted through the iterator.
Using iterators can also traverse multiple containers and operate on them. The code is as follows:
std::vector<int> v1{1, 2, 3}; std::vector<int> v2{4, 5, 6}; std::vector<int> v3{7, 8, 9}; // 构造多容器迭代器 auto it1 = v1.begin(); auto it2 = v2.begin(); auto it3 = v3.begin(); for (; it1 != v1.end() && it2 != v2.end() && it3 != v3.end(); ++it1, ++it2, ++it3) { std::cout << *it1 << " " << *it2 << " " << *it3 << std::endl; }
The above In the code, multiple vector containers are used, traversing them through iterators, and printing their element values.
Summary
Iterator is a powerful data access tool in C. It can be used to traverse elements in a container, insert/delete elements, and access multiple containers and operate on them. Mastering the use of iterators can make programmers more proficient in using the C standard library and improve code execution and coding efficiency.
The above is the detailed content of Tips on using iterators in C++. For more information, please follow other related articles on the PHP Chinese website!