使用擦除删除 std 向量的元素对象:a)内存处理和 b)更好的方法?
我有一个 vec_A
将 class A
的实例存储为: vec_A.push_back(A());
我想删除向量在稍后阶段,有两个问题:a)元素被删除为:vec_A.erase(iterator)
我需要添加任何其他代码以确保没有内存泄漏吗? 。
b) 假设条件if(num <5)
是num是否在特定的numberList中。鉴于此,是否有比我下面说明的更好的方法来删除向量的元素?
#include<vector>
#include<stdio.h>
#include<iostream>
class A {
public:
int getNumber();
A(int val);
~A(){};
private:
int num;
};
A::A(int val){
num = val;
};
int A::getNumber(){
return num;
};
int main(){
int i =0;
int num;
std::vector<A> vec_A;
std::vector<A>::iterator iter;
for ( i = 0; i < 10; i++){
vec_A.push_back(A(i));
}
iter = vec_A.begin();
while(iter != vec_A.end()){
std::cout << "\n --------------------------";
std::cout << "\n Size before erase =" << vec_A.size();
num = iter->getNumber() ;
std::cout << "\n num = "<<num;
if (num < 5){
vec_A.erase(iter);
}
else{
iter++;
}
std::cout << "\n size after erase =" << vec_A.size();
}
std::cout << "\nPress RETURN to continue...";
std::cin.get();
return 0;
}
I have a vec_A
that stores instances of class A
as: vec_A.push_back(A());
I want to remove some elements in the vector at a later stage and have two questions: a) The element is deleted as: vec_A.erase(iterator)
Is there any additional code I need to add to make sure that there is no memory leak? .
b) Assume that condition if(num <5)
is if num is among a specific numberList. Given this, is there a better way to delete the elements of a vector than what I am illustrating below?
#include<vector>
#include<stdio.h>
#include<iostream>
class A {
public:
int getNumber();
A(int val);
~A(){};
private:
int num;
};
A::A(int val){
num = val;
};
int A::getNumber(){
return num;
};
int main(){
int i =0;
int num;
std::vector<A> vec_A;
std::vector<A>::iterator iter;
for ( i = 0; i < 10; i++){
vec_A.push_back(A(i));
}
iter = vec_A.begin();
while(iter != vec_A.end()){
std::cout << "\n --------------------------";
std::cout << "\n Size before erase =" << vec_A.size();
num = iter->getNumber() ;
std::cout << "\n num = "<<num;
if (num < 5){
vec_A.erase(iter);
}
else{
iter++;
}
std::cout << "\n size after erase =" << vec_A.size();
}
std::cout << "\nPress RETURN to continue...";
std::cin.get();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这就是您需要做的全部。不会出现内存泄漏。由于您没有在堆上分配对象,因此当您执行 vec_A.push_back(A()) 时,一个新对象将复制到向量中。当你擦除时,向量将负责删除元素。
是的,您可以删除/擦除习惯用法。这是一个例子:
Yes, that's all you need to do. There will be no memory leak. Since you didn't allocate yoour object on heap, when you did vec_A.push_back(A()) a new object is copied into the vector. When you do erase, vector will take care of deleting the elements.
Yes, you can remove/erase idiom. This is an example:
1)资源处理由类本身完成。类的析构函数负责确保不存在内存泄漏。
2) 从向量中删除元素最好从后到前进行:
1) Resource handling is done by the class itself. The destructor of a class is responsible to ensure that there is no memory leak.
2) Removing elements from a vector is best done back-to-front: