简体   繁体   English

适用于 std::vector 和 std::map 的 C++ 迭代器

[英]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 .我需要实现一些东西,例如,如果我可以创建一个同时适用于std::vectorstd::map的迭代器,它会容易得多。 Is that possible?那可能吗? I'm talking about the iterators from the STL, not creating a new custom one.我说的是来自 STL 的迭代器,而不是创建新的自定义迭代器。

I have a class which stores some elements in a std::vector .我有一个类,它将一些元素存储在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.当我有时通过不同的方法返回这些元素时,我使用std::vector<...>::iterator ,这个迭代器稍后会被程序的其他部分使用。

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 .我想创建一个使用std::map<...>而不是std::vector<...>的新类,所以我不能返回std::vector<...>::iterator ,只有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 .该程序的其他部分需要std::vector<...>::iterator而不是std::map<...>::iterator

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.标准库头文件<algorithm>充满了函数模板的示例,这些模板接受不同容器的迭代器。 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* .唯一的标准例外是std::vector<bool> ,它不适用于bool*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM