【问题标题】:Is there a C++ equivalent to Java's Collection interface for STL container classes?是否有与 Java 的 STL 容器类的 Collection 接口等效的 C++?
【发布时间】:2010-06-21 23:51:31
【问题描述】:

我想将任意容器作为函数的参数传递并对其进行迭代(不擦除也不推送元素)。不幸的是,看起来没有标准的方法来做到这一点。

我想到的第一个解决方案是由封装 STL 容器的类实现的接口(我们称之为CollectionInterface)。所以函数声明看起来像:

f(const CollectionInterface * collection);

或者,我在考虑方法模板,它的优点是它在编译时保持绑定:

template <class CONTAINER> void f(const CONTAINER & collection);

你认为哪种方式更好?

【问题讨论】:

    标签: c++ stl collections containers function-templates


    【解决方案1】:

    ForwardIterator?这是InputIterator(或OutputIterator)的一种类型,它还允许多遍算法(递增它不会使先前的值无效)。

    迭代器(与 Java 迭代器完全不同)是统一 C++ 集合的中心线程。有关处理它们的算法示例(以及相关的迭代器类型要求),您可以从 &lt;algorithm&gt; 开始。特别是,search 提供了使用 ForwardIterator 的示例。它在由范围[first2, last2) 定义的序列的范围[first1, last1] 内找到第一个匹配项。这些都是符合ForwardIterator要求的对象。

    【讨论】:

    • 作为方法模板的参数?
    • @doc:对于模板函数,如果不必是成员函数,则 C++ 中通常首选成员函数或独立函数。
    【解决方案2】:

    如果您想以这种方式处理事情,您还可以编写接受整个容器而不是引用的方法。标准库容器的迭代器都通过成员函数begin()end() 提供,或者在某些情况下rbegin()rend() 用于向后迭代。模板的工作方式,您不必创建对象派生自的实际接口类型;需求是由使用的对象推断出来的。

    template<typename Container> void Function(const Container& c) {
        for(typename Container::const_iterator i = c.begin(), end = c.end(); i != end; ++i)
           //do something
    }
    

    传递迭代器在使用函数时提供了更大的灵活性,特别是并非所有迭代器都来自具有显式 begin()end() 函数的容器,您可以提供任何您想要的显式子范围。但有时这种方法是合适的。

    【讨论】:

    • 我喜欢这种方式,但我发现了一些问题。我无法指定容器内的内容类型,当我访问const_iteratorbegin()end() 时,我收到警告“无法解析标识符”。
    【解决方案3】:

    我想将任意容器作为函数的参数传递并对其进行迭代(不擦除也不推送元素)。

    传递迭代器。下面是一个实现和使用的例子:

    template <typename Iter>
    void function(Iter begin, Iter end)
    {
        for (Iter it = begin; it != end; ++it)
        {
            std::cout << *it << std::endl;
        }
    }
    
    int main()
    {
        std::string array[] = {"hello", "array", "world"};
        function(array, array + 3);
    
        std::vector<std::string> vec = {"hello", "vector", "world"};
        function(vec.begin(), vec.end());
    }
    

    请注意,在许多情况下,您实际上并不需要编写函数,但您可以使用库工具来组合它,然后简单地对其应用std::for_each。或者更好的是,使用预先存在的算法,例如 std::accumulatestd::find_if

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 2012-01-21
      • 2013-07-25
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      相关资源
      最近更新 更多