如何删除数组中的单个元素,使用c++?I中的动态内存分配,只想从单个位置删除数组中的元素,我使用了delete操作符,但没有帮助。
发布于 2018-06-04 19:04:51
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
就会改变后面那些人的位置,从而模糊代码的意图)。
实际上,在现代new
中看到裸的C++和delete
调用是非常不寻常的,您应该总是更喜欢智能指针或标准库中的集合(如vector
)。
https://stackoverflow.com/questions/50691172
复制