vector 存储指针
当 vector 存储指针时,释放内存应该对每个元素进行 delete,然后 clear(),将容器元素清空#include <stdio.h>#include <stdlib.h>#include <iostream>#include <str
·
当 vector 存储指针时,释放内存应该对每个元素进行 delete,然后 clear(),将容器元素清空
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <set>
#include <memory>
#include <vector>
#include <assert.h>
using namespace std;
int main()
{
vector<int> number{1,3,5,7};
vector<int *> integer;
transform(number.begin(), number.end(), back_inserter(integer),
[](const int &x){
int *y = new int(x);
(*y)++;
return y;
});
cout << "Value :\n";
for (auto x : integer) {
cout << *x << "\n";
}
cout << "Pointer :\n";
for (auto x : integer) {
cout << x << "\n";
}
for (auto x : integer) {
delete x;
}
integer.clear();
cout << "size, capacity is:\n";
//size become 0, but capacity still not change
cout << integer.size() << " " << integer.capacity() << "\n";
//if want release capacity, should shrink_to_fit
integer.shrink_to_fit();//vector<int*>(integer).swap(integer);
cout << integer.size() << " " << integer.capacity() << "\n";
int *a = new int(1);
cout << a << "\n";
delete a;
return 0;
}
输出:
Value :
2
4
6
8
Pointer :
0x7fae4e4026e0
0x7fae4e402700
0x7fae4e4026f0
0x7fae4e402710
size, capacity is:
0 4
0 0
0x7fae4e4026e0
更多推荐
已为社区贡献1条内容
所有评论(0)