c++ - 如何通过引用传递 vector 的静态 vector ?

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

我想传递 v vector ,这样它就不会在我每次调用函数 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);
      ^

最佳答案

首先,您没有 vector 的 vector ,它看起来像std::vector<std::vector<Type>> .你有一个 variable-length array vector

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

关于c++ - 如何通过引用传递 vector 的静态 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56920298/

相关文章:

c++ - 从 ‘arma::umat’ 到 ‘arma::mat’ 的转换

c++ - std::filesystem 根路径如何将自身作为父路径?

function - 多个参数列表和返回函数有什么区别?

javascript - 单击按钮后如何清除 VueJS 中的输入文本?

c++ - 在使用迭代器和 pop_back 循环时出现单一迭代器错误

c++ - 将 MPI 结果写入文件

c++ - std::find 它是如何工作的?运算符==

string - 未知长度的字符返回函数

xcode - 在 Visual Studio 2013 上使用 std::function<void>

c++ - 将 C++ decltype 与重载运算符++(预增量)一起使用