如何在 C++ 中使用删除运算符删除单个数据



如何在c ++中使用动态内存分配删除数组的单个元素?我只想从单个位置删除数组的元素。我使用了删除运算符,但没有帮助。

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++中看到裸newdelete调用实际上是非常不寻常的,您几乎总是应该更喜欢智能指针或标准库中的集合(例如vector(。

最新更新