简体   繁体   中英

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

Is there a way to get either an iterator and a const_iterator from both C arrays and C++ STL containers?

I have this template:

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

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

I would like the above function to work for C arrays, too. Is it possible? Or should I specialize it for C arrays?

I know that C++ has std::array , but I am curious about C arrays.

You may use standard functions std::begin , std::end , std::cbegin , std::cend declared in header <iterator> with arrays and standard containers.

Here is a demonstrative program

#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;
}

The output is

1 2 3 4 5
1 2 3 4 5

EDIT: You changed your original code snippet nevertheless you may use the same approach. Here is an example

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

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

int *c_array = &my_int_vector[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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