C++ 删除 vector 中的元素

标签 c++ vector

int main(){     

vector<Customer*> newcustomer;

newcustomer.push_back(new Customer("III", 123333, 555));
newcustomer.push_back(new Customer("LOL", 122222, 444));
newcustomer.push_back(new Customer("PPL", 121111, 333));

for (int i = 0; i < 3; i++){
    cout << newcustomer[i]->getName() << endl;
    cout << newcustomer[i]->getPhone() << endl;
    cout << newcustomer[i]->getID() << endl;
    cout << endl;
}






system("pause");
return 0;

}

所以我创建了一个名为 customer 的类,您可以插入新客户,getName 返回姓名,getPhone 返回电话号码,GetID 返回 ID,现在我想从该 vector 中提取所有内容,但不确定该怎么做。

最佳答案

要删除 vector 中的所有元素,您可以简单地使用 myvector.erase (myvector.begin(),myvector.end());myvector.clear()。 但这里的问题不仅仅是从 vector 中删除元素,还在于删除堆上分配的内存。以下是我的解决方案。

int main(){     

vector<Customer*> newcustomer;

newcustomer.push_back(new Customer("III", 123333, 555));
newcustomer.push_back(new Customer("LOL", 122222, 444));
newcustomer.push_back(new Customer("PPL", 121111, 333));

for (int i = 0; i < 3; i++){
    cout << newcustomer[i]->getName() << endl;
    cout << newcustomer[i]->getPhone() << endl;
    cout << newcustomer[i]->getID() << endl;
    cout << endl;
}


while(!newcustomer.empty())
{
    Customer *cust = newcustomer.front();
    newcustomer.erase(newcustomer.begin());
    delete cust;
}

system("pause");
return 0;

}

关于C++ 删除 vector 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30960920/

相关文章:

c++ - 是什么导致双重释放或损坏(out)错误?

c++ - 如何编写处理信号的跨平台 C++?

android - OpenCV - RTSP 流损坏的宏 block

c++ - 改变类对象数量的 vector

c++ - 我需要我的 vector 的最大大小(我给的值)C++

c++ - 处理删除命令期间出现段错误

r - R 中是否有 as.numeric(as.character(my.factor)) 的简短替代方案?

c++ - 这个语法 (0 < x < 10) 在 C++ 中有什么作用?

C++ 映射值作为列表,从列表中添加和删除元素

c++ - 3D vector C++ 的循环帮助