Let's imagine that there is some data stored into an array that needs to go through a function that accepts vector. In this situation, clearly the array data needs to be converted into the respective vector type. One general approach would be
std::vector<int> vec(arr, arr+n);
function(vec);
where arr is the mentioned array variable. I know that we added just one line, but its looks somehow as an unnecessary code pollution. So I tried this
function(std::vector<int>(arr, arr+n))
what worked. Bellow there is a detailed code this.
#include <vector>
#include <iostream>
void print(std::vector<int> vec){
for(unsigned int i=0; i!=vec.size(); ++i){
std::cout << vec[i] << std::endl;
}
}
int main(){
int a[] = {2,1,4,5,6};
print(std::vector<int>(a,a+5));
}
From this, my first question is: This approach is ok, or it has some undesired behavior?
After that, I decided to change the function argument to accept a vector reference like
void print(std::vector<int> &vec){
for(unsigned int i=0; i!=vec.size(); ++i){
std::cout << vec[i] << std::endl;
}
}
what did not work. Here is the error that I got
test.cpp: In function ‘int main()’:
test.cpp:13:34: error: invalid initialization of non-const reference of type ‘std::vector<int>&’ from an rvalue of type ‘std::vector<int>’
print(std::vector<int>(a,a+5));
^
test.cpp:4:6: error: in passing argument 1 of ‘void print(std::vector<int>&)’
void print(std::vector<int> &vec){
Here is the second question: Why, when the function argument as chanced to a vector reference this approach did not work. There is someway to get around this compiler error keeping the approach of creating the vector object in the argument function or not?