【问题标题】:How to pass static vector of vectors by reference?如何通过引用传递向量的静态向量?
【发布时间】:2019-11-17 02:32:08
【问题描述】:

我想传递v 向量,这样每次调用函数one(..) 时它就不会被复制。但我做不到。

谁能帮我摆脱困境?

int n; // global variable
void one(vector <int >(&v)[n]) 
{
    v[0][0] = 1;
}

int main()
{
    cin >> n;//n=1
    vector <int > v[n];
    v[0].push_back(9);
    one(v);
    cout << v[0][0];
}

错误信息:

prog.cpp:5:32: error: variable or field ‘one’ declared void
  void one(vector <int > (&v)[n]){
                                ^
prog.cpp:5:27: error: ‘v’ was not declared in this scope
  void one(vector <int > (&v)[n]){
                           ^
prog.cpp: In function ‘int main()’:
prog.cpp:17:6: error: ‘one’ was not declared in this scope
 one(v);
      ^

【问题讨论】:

  • 你并没有真正的向量向量。那将拼写为std::vector&lt;std::vector&lt;int&gt;&gt;。
  • 你拥有的是一个向量数组(但要注意variable-length arrays 并不是真正的 C++ 的一部分)。为什么不像通常传递数组一样传递它,使用指针(如vector&lt;int&gt;* v)以及数组的长度?或者确实是一个实际的向量向量?

标签: c++ function c++11 pass-by-reference stdvector


【解决方案1】:

首先,你没有 vector 的vector,它看起来像std::vector&lt;std::vector&lt;Type&gt;&gt;。你所拥有的是一个 variable-length array 的向量。

VLA 不是 C++ 标准的一部分,而是编译器扩展。有关更多信息,请参阅此帖子: Why aren't variable-length arrays part of the C++ standard?

话虽如此,如果n 是编译时知道的,您可以通过提供n 作为非类型模板参数来解决问题。

template<std::size_t n>
void one(std::vector<int> (&v)[n])
{
    v[0][0]=1;
}

在vector of vectors的情况下,不需要模板,而是通过引用传递它。

void one(std::vector<std::vector<int>> &v)
//                               ^^^^^^^^^^
{
    v[0][0]=1;
}

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多