简体   繁体   English

向量推回向量

[英]vector of vector push back

I initialized a vector of vector of int. 我初始化了一个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. 我认为使用get()方法时会出错。 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. 问题是,您从get返回了一个副本,而不是您要解决的实际实例。

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. 您遇到的问题是get函数返回的是向量的副本,而不是实际的向量。 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 使用此vector<int> * get(..获取指向内部的指针vector<int> * get(..并取消引用它( 这很糟糕,不要这样做
  2. Return a reference to your vector vector<int> &get(.. ( Better but still ) 返回对向量vector<int> &get(..的引用( 更好,但仍然
  3. Just use your vector straight up, the function get adds no benefit, and vector already has an at command (as well as operator [] ). 只需直接使用vector ,函数get不会增加任何好处,向量已经具有一个at命令(以及operator [] )。

Here is a live example. 这是一个实时示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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