从数组中删除并移位
Deleting from an array and shifting
对于大小为5的数组,我试图在0和数组的当前最后一个元素之间找到一个随机位置。
(最后一个位置第一次是4,第二次是3,依此类推。)
删除该数组位置中的任何元素,将其上方的所有元素下移,使数组中没有空位。
我试图尽可能节省时间,所以我想避免将所述随机位置设置为0或类似的值。
所以,如果我的数组看起来像int n[] = {1,3,5,7,9};
,而我的随机位置查找器选择了位置2,我如何将5(位置2)移到最后,并将所有内容下移,使我得到的数组看起来就像{1,3,7,9,5}
?
到目前为止,我有:
for (int j = 0; j < 5; j++)
{
printf ("before removal:n");
printarray (array, 5);
int randompos = ( rand() % (5-j) ); //selects random number from 0 to active last pos.
/* ?????? */ = array[randompos]; // What position will hold my random position?
//Also, what goes in place of the 'deleted' element?
insertion_sort (array, 5-j); //sort only the active elements
printf ("after removal:n");
printarray (array, 5);
}
期望输出:
before removal:
1,3,5,7,9
(假设随机位置为阵列位置2,存储编号5)
after removal:
1,3,7,9,5
给定数组{1,3,5,7,9}
和pos = 2
,可以执行以下操作:
int main()
{
int pos = 2;
int arr[] = {1, 3, 5, 7,9};
int length =sizeof(arr)/sizeof(arr[0]);
int val = arr[pos];
for (int i = pos; i < length; i++){
int j = i + 1;
arr[i] = arr[j];
}
arr[length - 1] = val;
return 0;
}
#include <iostream>
#include <algorithm>
#include <random>
int main() {
int n[] = {1, 3, 5, 7, 9};
std::size_t n_size = sizeof(n) / sizeof(int);
std::default_random_engine generator;
for(std::size_t i(0), sz(n_size); i < sz; ++i) {
std::cout << "before removal:" << std::endl;
std::cout << " ";
for(std::size_t j(0); j < n_size; ++j) std::cout << n[j] << " ";
std::cout << std::endl;
--n_size;
std::uniform_int_distribution<int> distribution(0, n_size);
std::size_t idx = distribution(generator);
std::cout << " Removing index: " << idx << std::endl;
std::swap(n[idx], n[n_size]);
std::sort(std::begin(n), std::begin(n) + n_size); // use your sorting here
std::cout << "after removal:" << std::endl;
std::cout << " ";
for(std::size_t j(0); j < n_size; ++j) std::cout << n[j] << " ";
std::cout << "n" << std::endl;
}
}
现场演示
相关文章:
- 你能帮我解决删除数组 c++ 中重复值的挑战吗?
- 删除[i] 数组和删除数组 [i] 之间的区别
- 如何实现删除数组的功能?
- 删除数组 c++ 崩溃问题
- 如何删除数组列表中的元素
- C++删除数组只会解除分配第一项
- 删除数组成员的更好方法是什么?
- 如何使用 deleteEntry 函数 c++ 删除数组中的单个字符串
- 删除数组中所有出现的数字 C++
- C++ 删除数组时检测到堆损坏
- 不允许删除数组的一部分,为什么
- 如何删除数组中第一次出现的值
- 当我删除数组时,指针在哪里?指向数组的指针与数组中的元素之间的区别
- 尝试用C 中的空地址(而非null)删除数组指针
- 为什么 std::remove 不删除数组的最后一个元素
- 如何使用c++删除数组中的一些值
- 仅删除数组的第一个元素
- 删除数组时断言失败
- 如何并行删除数组中的零值
- 访问指针数组/通过另一个指针并删除数组中的单个元素而不删除第一个指针或整个数组