我想传递 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/