Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a vector of auto (unknown) type inside a template function in C++

I have a template function inside which I want to generate a vector which is of an unknown type. I tried to make it auto, but compiler says it is not allowed.

The template function gets either iterators or pointers as seen in the test program inside the followed main function. How can the problem be fixed?

template<class Iter>
auto my_func(Iter beg, Iter end)
{
    if (beg == end)
        throw domain_error("empty vector");

    auto size = distance(beg, end);

    vector<auto> temp(size); // <--HERE COMPILER SAYS CANNOT BE AUTO TYPE
    copy(beg, end, temp->begin);
    .
    .
    return ....

}


int main()
{
    int bips[] = {3, 7, 0, 60, 17}; // Passing pointers of array
    auto g = my_func(bips, bips + sizeof(bips) / sizeof(*bips));

    vector<int> v = {10, 5, 4, 14}; // Passing iterators of a vector
    auto h = my_func(v.begin(), v.end());

    return 0;
}
like image 328
axcelenator Avatar asked Jul 20 '17 14:07

axcelenator


People also ask

What does Vector begin () do?

vector::begin() begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container.

Is vector a class template or object template?

vector is a template class, which can be instantiated with a type, in the format: vector<int> , vector<double> , vector<string> . The same template class can be used to handle many types, instead of repeatably writing codes for each of the type.

What is a vector in C __?

Vector. Vectors are sequence containers representing arrays that can change in size. Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays.


1 Answers

You cannot use a std::vector of auto. You might use std::iterator_traits instead:

std::vector<typename std::iterator_traits<Iter>::value_type> temp(size);
like image 185
Edgar Rokjān Avatar answered Sep 18 '22 12:09

Edgar Rokjān