我在这里有这个结构和向量
//Record Structure
struct Record {
std::string date;
std::string name;
int dollars = 0;
int cents = 0;
std::string getCost() {
//Dollars First
std::stringstream dollar;
dollar << dollars;
std::string DOLLAR = dollar.str();
//Cents Second
std::stringstream cent;
cent << cents;
std::string CENT = cent.str();
//Display cents as double zeros
DOLLAR = DOLLAR.length() == 1 ? "0" + DOLLAR : DOLLAR;
CENT = CENT.length() == 1 ? "0" + CENT : CENT;
//Result
std::string result = "$" + DOLLAR + "." + CENT;
//Return
return result;
}
void Constructor(std::string NM, std::string DT, int DOLLAS, int PENNY) {
name = NM;
date = DT;
dollars = DOLLAS;
cents = PENNY;
}
};
//Vector that holds instances of the Record structure
std::vector <Record> Records;
假设我已经将一个实例附加到向量中
Record newInstance;
newInstance.Constructor("Name", "Date", 10, 0);
Records.push_back(newInstance);
如果我这样擦除它,整个结构会被解构并释放空间吗?
Records.erase(Records.begin());
如果它没有被解构并释放空间,我将如何做到这一点?
是的,当一个元素从向量中删除时,它会被销毁,它所持有的任何资源都应该被释放。 我说"应该"是因为这取决于元素类型的正确实现 - 我们必须假设元素类型的实现使得销毁它不会泄漏任何资源。
在您的特定情况下,Record
是一个包含整数和 std::string
s 的结构,这将按您的预期工作:从向量(或任何其他 STL 容器(中删除Record
将释放整数和字符串使用的内存。
是的。std::vector::erase
所做的是
通过移除的元素数减小容器大小,这些元素将被销毁。
您可以在此处找到参考资料。