gpt4 book ai didi

C++迭代器需要删除吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:35:37 26 4
gpt4 key购买 nike

我有一个关于内存释放的问题

我正在我的一个程序中迭代一个 vector 。像这样:

// init vector
vector<int>* v = new vector<int>();
// iterate
for (vector<Column>::iterator it = v->begin(); it != v->end(); ++it) {
// do something with it
}
// delete vector
delete v;

但是我不确定是否应该这样写:

// init vector
vector<int>* v = new vector<int>();
// iterate
vector<Column>::iterator it = v->begin()
for (; it != v->end(); ++it) {
// do something with it
}
delete it;
// delete vector
delete v;

或者因为释放了迭代器而没有必要释放迭代器?

最佳答案

您只能对迭代器持有的对象调用 delete,而不是迭代器本身;以您的代码为例(但稍作修改):

std::vector<int*> *v = new std::vector<int*>();
for (int i = 0; i < 10; ++i) {
v->push_back(new int(i));
}
std::vector<int*>::iterator it = v->begin();
for (; it != v->end(); ++it) {
// do something with it
delete *it; // <- notice the deference to delete the underlying int
//delete it; // causes compiler error (expected pointer)
}
// delete vector
delete v;

在迭代器类型上调用 delete 会产生编译器错误(取决于编译器/实现等)。

关于C++迭代器需要删除吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23578455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com