【问题标题】:`iterator` and `const_iterator` for C arrays in C++?`iterator` 和 `const_iterator` 用于 C++ 中的 C 数组?
【发布时间】:2015-01-16 01:23:45
【问题描述】:

有没有办法从 C 数组和 C++ STL 容器中获取 iteratorconst_iterator

我有这个模板:

template <typename T>
class Another_template {
     // implementation
};

template <typename Container>
Another_template<typename Container::iterator>
fun(Container&) {
   // implementation
}

我希望上述函数也适用于 C 数组。可能吗?还是应该专门针对 C 数组?

我知道C++有std::array,但是我对C数组很好奇。

【问题讨论】:

    标签: c++ arrays stl iterator


    【解决方案1】:

    您可以将标头&lt;iterator&gt; 中声明的标准函数std::beginstd::endstd::cbeginstd::cend 与数组和标准容器一起使用。

    这是一个演示程序

    #include <iostream>
    #include <iterator>
    #include <vector>
    
    template <typename Container>
    auto f( const Container &c ) ->decltype( std::begin( c ) )
    {
        for ( auto it = std::begin( c ); it != std::end( c ); ++it )
        {
            std::cout << *it << ' ';
        }
        std::cout << std::endl;
    
        return std::begin( c );
    }
    
    int main() 
    {
        int a[] = { 1, 2, 3, 4, 5 };
        f( a );
    
        std::vector<int> v = { 1, 2, 3, 4, 5 };
        f( v );
    
        return 0;
    }
    

    输出是

    1 2 3 4 5
    1 2 3 4 5
    

    编辑:您更改了原始代码 sn-p 但是您可以使用相同的方法。这是一个例子

    template <typename Container>
    auto f1( const Container &c ) ->std::vector<decltype( std::begin( c ) )>;
    

    【讨论】:

    • 对。遗憾的是,我把我的例子简化得太多了。我已经修好了。正如您现在所看到的,我需要iterator 来实例化另一个模板,因此auto 将不起作用,AFAIK。很抱歉给您带来不便。
    【解决方案2】:

    如果您需要 C 数组的功能,您可以使用 stl 向量并通过获取对第一个元素的引用来像使用 c 数组一样使用它:

    int *c_array = &my_int_vector[0];
    

    【讨论】:

    • 执行此操作的标准方法是使用 Container.data() 获取指向内部数组的指针,以便基于数组的容器与 C 函数交互。这通常使用字符串来完成。
    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2012-05-10
    • 2020-04-03
    • 1970-01-01
    • 2019-10-30
    • 2014-03-24
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多