开发者

Passing a vector<vector<int> > pointer to a argument?

开发者 https://www.devze.com 2023-02-22 15:05 出处:网络
Okay, so I\'m trying to pass a pointer to a argument like this. void function(vector<vector<int> > *i){

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)

But when I do it says i[0][0] is 0 and not 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

Or alternatively, you can also pass by reference as illustrated here : 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. Your code in main is wrong. You should declare test as 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.


At least on my machine, this gives me 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. By doing this you can avoid having to test for a NULL pointer condition and it helps clean up the syntax.

0

精彩评论

暂无评论...
验证码 换一张
取 消