Eleno
Eleno

Reputation: 3016

`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.

Upvotes: 3

Views: 4159

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

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 ) )>;

Upvotes: 4

pinkboi
pinkboi

Reputation: 259

If you need the functionality of a C array, you can use an stl vector and use it like a c array by getting a reference to the first element:

int *c_array = &my_int_vector[0];

Upvotes: 0

Related Questions