我们如何将阵列成员转移到一个位置?
例如,如果我们有 n 大小的数组,其中包含一个空元素,并且我们将所有元素转移到成员 pos 的右侧在一个位置,我们可以将 n-1 成员复制到空元素中,依此类推。
代码:
#include <iostream>
using namespace std;
// we take the position of insertion, then right shift all elements
// then insert the required number
int main() {
int n = 10;
int list[n];
cout << "Enter " << n-1 << " elements:\n";
for( int i = 0; i < n-1; ++i) {
cin >> list[i];
}
int pos, num;
cout << "Position ( start: 1 ): ";
cin >> pos;
if( pos < n && pos >= 0 ) {
cout << "No. to be inserted: ";
cin >> num;
for( int i = n-2; i >= pos-1; --i) {
list[i+1] = list[i];
}
list[pos-1] = num;
for( int i = 0; i < n; ++i) {
cout << list[i] << ' ';
}
return 0;
}
}
但是,通过某些方式,我们不能一次性将整个子阵列移动,将所有成员一个一个地滑动?
我们也可以用向量来实现吗?并且矢量会更有效或更好实现这一目标吗?
答案 0 :(得分:2)
首先,C ++不支持可变长度数组(VLA)。虽然有些编译器有自己的语言扩展支持VLA,但最好使用标准C ++功能。
所以而不是
int main() {
int n = 10;
int list[n];
//...
最好写
int main() {
const int n = 10;
int list[n];
//...
另外一般情况下,最好使用标准算法而不是循环,因为这样可以消除错误。
要在数组pos
中插入值,您可以使用以下方法,如演示程序中所示。对于基本算术类型,您还可以使用标准C函数memmove
。
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
const size_t N = 10;
for ( size_t i = 0; i < N; i++ )
{
int a[N] = { 0 };
auto pos = std::next( std::begin( a ), i );
std::copy_backward( pos, std::prev( std::end( a ) ), std::end( a ) );
*pos = i + 1;
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
它的输出是
1 0 0 0 0 0 0 0 0 0
0 2 0 0 0 0 0 0 0 0
0 0 3 0 0 0 0 0 0 0
0 0 0 4 0 0 0 0 0 0
0 0 0 0 5 0 0 0 0 0
0 0 0 0 0 6 0 0 0 0
0 0 0 0 0 0 7 0 0 0
0 0 0 0 0 0 0 8 0 0
0 0 0 0 0 0 0 0 9 0
0 0 0 0 0 0 0 0 0 10
对于标准容器std::vector
,它具有允许插入新元素的方法。然而,与数组相比,这些方法会扩大向量。
std::vector
有以下允许插入一个元素的方法。
iterator insert(const_iterator position, const T& x);
iterator insert(const_iterator position, T&& x);
在引擎盖下,向量与数组完成相同的工作,除了向量可以动态放大使用的内存。