如何在c ++中使用动态内存分配删除数组的单个元素?我只想从单个位置删除数组的元素。我使用了delete运算符,但没用。< / p>
答案 0 :(得分:5)
delete
功能仅适用于您使用new
分配的整个内容。换句话说,如果您使用new
分配了整个数组,则不能delete
其中的一部分。所以,这没关系:
auto x = new int[10]; // An array of ten things.
delete[] x; // Delete the *entire* array.
但这不会:
delete &(x[7]); // Try to delete the eight item.
C ++中可调整大小的数组通常应该使用std::vector
,如以下示例程序所示:
#include <iostream>
#include <vector>
int main() {
// Create a vector: 11, 22, ... 99.
std::vector<int> vec;
for (auto i = 11; i <= 99; i += 11)
vec.push_back(i);
// Remove the fifth thru sixth, and third elements (55, 66, 33).
vec.erase(vec.begin() + 4, vec.begin() + 6);
vec.erase(vec.begin() + 2);
// Output modified vector.
for (auto val: vec)
std::cout << val << ' ';
std::cout << '\n';
}
所述程序的输出正如预期的那样:
11 22 44 77 88 99
(我以相反的顺序删除了组,否则,删除33
会更改后续人员的位置,从而模糊代码的意图。“
在现代C ++中看到裸new
和delete
调用实际上非常,你应该总是更喜欢智能指针或者标准库中的集合(例如vector
)。