Dear all
I am trying to give a vector as an input for a function and get it back as an out put. I normally send the address of first element in the vector.
as an example:
1 2 3 4 5 6 7 8 9 10 11 12
void my_function(int* my_vect,int sz){
int i;
for (i=0;i<sz;i++)
*(my_vect+i)=i;
}
int main(){
int sz=100;
int my_vect[sz];
my_function(&my_vect[0],sz)
}
I want to use push_back (dynamic memory) since size of the vector is not known in some cases. However I am getting error about using push_back for int*. How can I modify my code?
wrong code:
1 2 3 4 5 6 7 8 9 10 11 12
void my_function(int* my_vect,int sz){
int i;
for (i=0;i<sz;i++)
my_vect.push_back(i);
}
int main(){
int sz=100;
vector<int> my_vect;
my_function(&my_vect[0],sz);
}
Thank you for your Answer
my_vect is vector in main code. What I am doing is assigning the address of first element to the function.
so if I use my_function(my_vect, sz) I need to introduce the my_vet as vector in function.
void my_function(vector<int> my_vect,int sz)
However in that case it doesn't return the vector back to main function. Am I wrong?
I need to get the vector back.
Thanks again.
Also, it's not really a size you're passing in... vectors already have built-in support for size. You're really just passing in a max value "n" so that the vector can be populated from 0..n-1
If you know the approx final size of the vector, you can call a vector's reserve(...) method, e.g. immediately after its creation in main() or w/e. This will reduce allocations from the push_back.
IMO, this operation is fairly simple and doesn't really need a separate function. Perhaps do something more exciting w/ the vector?