“迭代器”和“const_iterator”表示 C++ 中的 C 数组

`iterator` and `const_iterator` for C arrays in C++?

本文关键字:迭代器 中的 数组 C++ const iterator 表示      更新时间:2023-10-16

有没有办法从 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数组很好奇。

您可以使用标准函数std::beginstd::endstd::cbeginstd::cend在带有数组和标准容器的标头<iterator>中声明。

这是一个演示程序

#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

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

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

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

int *c_array = &my_int_vector[0];