java vector push_关于vector在堆上还是在栈上的思考与vector.push_back()究竟放入的是什么...

vector如果不new是在栈上的,这是众人皆知的。

如下面的代码:

class Solution {

public:

vector> generate(int numRows) {

vector> result;

for (int i=0; i

vector temp(i+1,1);

cout<

result.push_back(temp);

}

for (int i=0; i

cout<

}

return result;

}

};

得到的结果如下:

0x7fff5fbff5f0

0x7fff5fbff5f0

0x7fff5fbff5f0

0x100105540

0x100105558

0x100105570

Program ended with exit code: 0

那么如果使用了new了呢?众所周知,使用new之后所得到的结果是在堆上的。

但是我们来看下面的代码:

class Solution {

public:

vector> generate(int numRows) {

vector> result;

for (int i=0; i

vector *temp =new vector();

cout<

result.push_back(*temp);

}

for (int i=0; i

cout<

}

return result;

}

};

得到的结果如下:

0x1001054a0

0x1001054e0

0x1001054c0

0x100105560

0x100105578

0x100105590

Program ended with exit code: 0

依旧不相同,是为什么呢?

因为vector的push_back()机理是这样的,

它并不是一种深度拷贝,而是一种浅拷贝,

即,将要push_back元素所对应的所有值拷贝到vector name所分配的那块空间去,

而不是借用别人已经存在的那块地址。

有点绕,我们来看一道Leetcode:leetcode 118 Pascal's Triangle

——————————————

这是我原来的解法,是wrong answer,

调试了一下,发现无论numRows是多少,result数组依然全部是1。

class Solution {

public:

vector> generate(int numRows) {

vector> result;

for (int i=0; i

vector temp(i+1,1);

result.push_back(temp);

for (int j=1; j

temp[j]=result[i-1][j-1]+result[i-1][j];

}

}

return result;

}

};

原因就是上面说的,push_back到result的并不是temp本身,而是temp所对应的值们。

所以对temp[j]造成的改动并不影响result找个vector。

所以正解如下:

class Solution {

public:

vector> generate(int numRows) {

vector> result;

for (int i=0; i

vector temp(i+1,1);

result.push_back(temp);

for (int j=1; j

result[i][j]=result[i-1][j-1]+result[i-1][j];

}

}

return result;

}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值