[英]Passing a vector<vector<int> > pointer to a argument?
Okay, so I'm trying to pass a pointer to a argument like this. 好的,所以我试图将指针传递给这样的参数。
void function(vector<vector<int> > *i){
vector<int> j;
j.push_back(5);
i->push_back(j);
}
And call it with function(&i)
并使用function(&i)
调用
But when I do it says i[0][0] is 0 and not 5. 但是当我这样做时,它说i [0] [0]是0而不是5。
Why is this happening? 为什么会这样呢?
Edit: 编辑:
int main(){
vector<vector<int> > test;
function(&test);
cout << test[0][0];
}
You can try this code: 你可以试试这段代码:
void f(vector<vector<int> > *i)
{
vector<int> j;
j.push_back(5);
i->push_back(j);
}
vector<vector<int> > i;
f(&i);
cout << i[0][0];
Output: 输出:
5
Demo: http://ideone.com/hzCtV 演示: http : //ideone.com/hzCtV
Or alternatively, you can also pass by reference as illustrated here : http://ideone.com/wA2tc 或者,您也可以按如下所示通过引用传递: http : //ideone.com/wA2tc
I assume you are calling your function as function(test)
and not function(&test)
as the second one will not compile. 我假设您将函数称为function(test)
而不是function(&test)
因为第二个function(&test)
无法编译。 Your code in main
is wrong. 您的main
代码是错误的。 You should declare test as vector<vector<int> > test;
您应该将test声明为vector<vector<int> > test;
(without *
). (不带*
)。 At its current form, you have just defined pointer to a vector without actually allocating the vector itself. 在当前形式下,您刚刚定义了指向向量的指针 ,而没有实际分配向量本身。 If you try to dereference this pointer (you are trying to do i->push_back()
you will invoke undefined behavior. 如果尝试取消引用该指针(尝试执行i->push_back()
,则将调用未定义的行为。
At least on my machine, this gives me 5! 至少在我的机器上,这给了我5分!
#include <vector>
#include <stdio.h>
using std::vector;
void vf(vector<vector<int> > * i) {
vector<int> j;
j.push_back(5);
i->push_back(j);
}
int main() {
vector<vector<int> > j;
vf(&j);
printf("c: %d\n",j[0][0]);
}
You should use references instead of pointers unless NULL is an acceptable value for the pointer. 您应该使用引用而不是指针,除非NULL是指针可接受的值。 By doing this you can avoid having to test for a NULL pointer condition and it helps clean up the syntax. 通过这样做,您可以避免必须测试NULL指针条件,并且有助于清理语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.