如何将数组成员向右移动一个位置?
例如,如果我们有一个大小为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;
}
}
我们能不能通过某种方式,一次性将整个子数组向右平移一个位置,将所有元素都右移一位?
另外,我们可以使用向量来实现这个操作吗?向量是更有效或者说更好的方式吗?
std::rotate
。 - NathanOlivervector::insert
会有帮助。 - SCaffreystd::vector<>
的性能仍然优于std::list<>
。请参阅 https://www.youtube.com/watch?v=YQs6IC-vgmo。@StillLearning - cdonat