简体   繁体   中英

vector of vector push back

I initialized a vector of vector of int. The sizes of inner vectors are arbitrary. I read related questions but still cannot solve my problem.

vector<vector<int> > vec;
vector<int> get(int i) {
  return vec[i];
}

int main() {
  vec.resize(5);  // Only the first dimension has the fixed size
  get(2).push_back(2);  // If I do vec[2].push_back(2), it will work
  get(1).push_back(34);
  for (int i = 0; i < 5; ++i) {
    cout << vec[i].size() << endl;  // output: 0
    for (int j = 0; j < vec[i].size(); ++j) {
       cout << vec[i][j] << endl;
    }
  }
}

I think things go wrong when I use get() method. But I cannot see where the problem is.

You want to return a reference to the vector, not a copy.

Change

vector<int> get(int i) {
  return vec[i];
}

to

vector<int>& get(int i) {
  return vec[i];
}

In order to return a reference.

The problem is, that you return a copy from get, not the actual instance you want to address.

Change your code to

vector<int>& get(int i) {
        // ^
    return vec[i];
}

The problem you are having is that get function is returning a copy of your vector, not the actual vector. You can do several things:

  1. Get a pointer to the internal with this vector<int> * get(.. and derefernce it ( This is very bad do not do this
  2. Return a reference to your vector vector<int> &get(.. ( Better but still )
  3. Just use your vector straight up, the function get adds no benefit, and vector already has an at command (as well as operator [] ).

Here is a live example.

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