push.back

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);
}


Thanks in advance for your help.
1
2
3
4
5
6
void my_function(int* my_vect,int sz)
{
  int i;
  for (i=0;i<sz;i++)
    my_vect.push_back(i);
}


Look at the first line there. What kind of object is my_vect? Is it a vector?
also, &my_vect[0] is redundant in this case. It can just be my_function(my_vect, 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.

1
2
3
4
5
void Func(vector<int>& v, int n)
{
    for(int i=0; i<n; ++i)
      v.push_back(i);
}


Use a reference.

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?

Thanks for response,
Yes my code is pretty large one, I have some 3-D and 4-D vectors. This was only for showing what problem I have.
Topic archived. No new replies allowed.