正如标题所说,我想删除数组中包含0的元素。
当用户提示一个相同的整数时,程序会拒绝用户输入并自动将0放在那里,但我希望将其删除。
这是我20个数组中的当前输出
25 35 50 23 95 55 9 85 45 0
97 56 0 33 75 0 101 86 100 0
这是我的欲望输出与相同的用户提示
25 35 50 23 95 55 85 45 97
56 33 75 86 100
答案 0 :(得分:1)
我仍然更喜欢使用std::vector
,尽管这个问题提到"没有使用vector"。但是,让我们尝试使用数组。
int int_array[20] = {/*...*/};
int* last_ptr = std::remove(std::begin(int_array), std::end(int_array), 0);
for (int* it = int_array ; it != last_ptr ; ++it)
cout << *it << endl;
按照惯例,生成的last_ptr
指向通过结果数组末尾的位置。
由于它是一个数组,实际的数组大小不会改变。我们所能做的就是忽略数组中未使用的部分。