Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting std::array to std::vector

In the code below, the size of the function (foo) argument (std::vector) can be anything to make the function a generic one. However, sometimes the size container is known so std::array can be used. The problem is to convert the std::array to std::vector. What is the best way to solve this problem? Is it better to just use std::vector always in this case?

#include <iostream>
#include <array>
#include <vector>

using namespace std;

// generic function: size of the container can be anything
void foo (vector<int>& vec)
{
    // do something
}

int main()
{
   array<int,3> arr; // size is known. why use std::vector?
   foo (arr); // cannot convert std::array to std::vector

   return 0;
}
like image 506
Shibli Avatar asked Jul 22 '14 17:07

Shibli


People also ask

How do you turn an array into a vector?

To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.

What is the difference between std :: array and std::vector?

Difference between std::vector and std::array in C++Vector is a sequential container to store elements and not index based. Array stores a fixed-size sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so, size increases with insertion of elements.

Is std::vector slower than array?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.


Video Answer


1 Answers

Given that you pass in an array, foo does not seem to resize the container it gets passed in (however, it does seem to modify the elements since vec is passed non-const). It therefore does not need to know anything about the underlying container other than how to access elements.

Then, you can pass a pair of iterators (and make the iterator type a template argument), as many STL algorithms do.

like image 119
Alexander Gessler Avatar answered Nov 14 '22 12:11

Alexander Gessler