Convert std :: array to std :: vector

In the code below, the size of the function argument (foo) ( std::vector ) can be anything to make the function generic. However, sometimes the size of the container is known, so you can use std :: array. The problem is converting 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; } 
+8
c ++ vector c ++ 11 stdvector stdarray
source share
2 answers

Given that you are passing an array , foo does not seem to resize the container to which it is passed (however, it does seem to change the elements since vec is not const passed). Therefore, he does not need to know anything about the base container, except how to access the elements.

You can then pass a couple of iterators (and make the iterator type an argument to the template), as many STL algorithms do.

+16
source share

The function takes a vector by reference. Therefore, it makes no sense to pass an object of type std :: array to a function. This may make sense if the function parameter is defined as the constant of the vector reference.

0
source share

All Articles