【发布时间】:2016-11-24 07:42:24
【问题描述】:
(我来自 C 背景,是 C++ 及其 STL 的新手)
我正在编写一个 C++ 向量数组,它将通过函数传递(作为向量数组的引用)并在其中进行处理。
在这种情况下,[在 C 中] 我会传递一个指向我的自定义数据类型的指针(在后台按值调用。)
我的代码在尝试这样做时在编译时出错:
#include <cstdio>
#include <vector>
using namespace std;
/*
the problem is I can't get the syntax. vector<type> &var is
a reference to a single dimension array of vectors.
*/
void pass_arrayOf_vect(vector<int> &array, int lmt);
int main() {
int lmt = 10;
vector<int> lst[lmt];
pass_arrayOf_vect(lst, lmt);
return 0;
}
/*
and the traditional ambiguity of whether using "." or "->" for
accessing or modifying indexes and their members.
*/
void pass_arrayOf_vect(vector<int> &lst, int lmt) {
for (int i = 0; i < lmt; i++) {
lst[i].push_back(i*i);
}
for (int i = 0; i < lmt; i++) {
printf("array[%d]: ", i);
for (int j = 0; j < lst[i].size(); j++) {
printf("%d ",lst[i][j]);
}
printf("\n");
}
printf("\n");
return;
}
【问题讨论】:
-
要使用向量数组,请写
vector<vector<int>>。 -
小心
vector<int> lst[lmt];因为lmt不是编译时常量,所以这就是所谓的可变长度数组。它们不是标准 C++ 的一部分,只有少数编译器支持它们。如果您在 GCC 中构建程序并将程序提交给使用 Visual Studio 的人,这会让生活变得一团糟。 -
既然你来自 C,你可能应该马上知道 C++ 标准不支持你在这里的可变长度数组(VLA)(甚至通过扩展支持它的流氓编译器也可能会在元素基础的非 POD 类型的位置呕吐),所以我首先要避开那些。其次,只要您对本网站上报告的编译器错误有任何疑问(如您所说,“...在编译时给出错误”总是在您的帖子中包含错误逐字 .
-
@WhozCraig 明白了这一点。那么标准做法是什么?在 main() 或其他函数中修改向量数组?
标签: c++ pointers vector reference stl