'C++ Iterators that work for both std::vector and std::map
I need to implement something and it would be much easier if I could create, for example, an iterator that works both for std::vector and std::map. Is that possible? I'm talking about the iterators from the STL, not creating a new custom one.
I have a class which stores some elements in a std::vector. When I return those elements sometimes through different methods, I use std::vector<...>::iterator, and this iterator is later used by other parts of the program.
I want to create a new class which uses std::map<...> instead of std::vector<...>, so I can't return std::vector<...>::iterator, only std::map<...>::iterator. And no, I don't want to create an extra vector in this new class. The other parts of the program require an std::vector<...>::iterator instead of a std::map<...>::iterator.
Solution 1:[1]
You can write a template function that accepts iterators of different types. As long as you use the given iterator as a bidirectional iterator, both vector and map iterators will work.
Could you give me an example on how to do it
The standard library header <algorithm> is full of examples of function templates that accept iterators to different containers. Here is a simple example:
template<class InputIt, class T>
InputIt find(InputIt first, InputIt last, const T& value)
{
for (; first != last; ++first) {
if (*first == value) {
return first;
}
}
return last;
}
But if you are looking for a single iterator type, then there isn't such iterator in the standard library. It can be implemented though.
If the only thing that you do with the iterator is indirecting through it to access the object, then you can use a pointer instead of iterator of the container for that purpose in most cases. Only standard exception is std::vector<bool> which won't work with bool*.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
