Junior — Middle
Can you explain what is meant by a bidirectional iterator in the context of C++?
sobes.tech AI
Answer from AI
A bidirectional iterator in C++ is an iterator that supports moving both forward and backward through a container. Unlike unidirectional (input or forward) iterators, bidirectional iterators allow the use of ++ and -- operators to move to the next and previous elements, respectively.
Example of using a bidirectional iterator with std::list:
#include <iostream>
#include <list>
int main() {
std::list<int> lst = {1, 2, 3, 4};
auto it = lst.begin();
++it; // move to the second element (2)
std::cout << *it << "\n";
--it; // move back to the first element (1)
std::cout << *it << "\n";
return 0;
}
Bidirectional iterators are typically supported in containers where bidirectional navigation is possible, such as std::list, std::set, std::map.