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;
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With