简体   繁体   中英

allocate an element vector to vector

This is the segment function I write:

vector<int> v1(const vector<int> &v2, const vector<int> &v3) {

  int v2_index = 0;
  int v3_index = 0;
  int v1_INDEX = 0;

  for(int i=0; i < v3.size(); ++i) {
    if(v2[v2_INDEX] == v3[v3_INDEX]) {
       int  x= v2[v2_INDEX];
       v1[v1_INDEX] = x;
       ++v1_INDEX;
     }
     if (v2[0] != v3[0]) {
       v2_INDEX++;
     }
     v3_INDEX++;
   }
}

I must use vector as a function. If the v2 element equal to v3 element, I want to allocate one element (not duplicate; push_back or v2[0]= v1[0]) to the v1 vector:

I've tried:

v1.push_back(v2.push_back(i));
v1[v1_INDEX] = v2[v2_index];
int x = v2[v2_index]; v1.push_back(x);
v1[v2[v2_index]];

All of them do not compile. Why can I allocate an element v2[i] to -----> v1[i] correctly without using extra library?

I get the error below:

error: request for member ‘push_back’ in ‘v1’, which is of non-class type 

The crux of the matter is that in C++, unlike Pascal , a function returns values by using a return statement. In C++ it is impossible to access the returned object through function name. In your code:

   v1[v1_index] = x;

The v1 refers to the function itself, not the returned object. So, the code tries to access function v1 is if it were an array, or a vector. Which makes no sense, and hence the error:

<source>: In function 'std::vector<int> v1(const std::vector<int>&, const std::vector<int>&)':
<source>:12:19: warning: pointer to a function used in arithmetic [-Wpointer-arith]
        v1[v1_index] = x;
                   ^

To get the functionality you want, it is up to you to define the returned object, and return it at the end:

vector<int> v1(const vector<int> &v2, const vector<int> &v3) {

  int v2_index = 0;
  int v3_index = 0;
  int v1_index = 0;

  vector<int> ret;
  for(int i=0; i < v3.size(); ++i) {
    if(v2[v2_index] == v3[v3_index]) {
       int  x= v2[v2_index];

       // Bug: out of bounds
       ret[v1_index] = x;
       ++v1_index;
     }
     if (v2[0] != v3[0]) {
       v2_index++;
     }
     v3_index++;
   }
   return ret;
}

This compiles, but you still have a critical bug. The bug is accessing ret out of bounds. A better solution is to ditch v1_index and simply call push_back() instead:

   int  x= v2[v2_index];
   ret.push_back(x);

Even better, use a range-for loop instead of all the mess with v3_index variables. It is as simple as:

for (auto v3_element: v3) {
  ... your code goes here...
}

No need to maintain indexes, and no need to access v3[...] . This is all done for you by for . Unfortunately, you can't get rid of v2_index due to the way it is incremented, but other index variables are not needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM