移动指定索引处的数组元素
Shifting array elements at specified indexes
什么是最有效的算法移动数组元素在指定的索引左和右一个位置?
例如,将[a,b,c,d,e,f]的索引[1,3,5]左移得到[b,a,d,c,f,e]
我不希望它在新索引越界时旋转,如果这有意义的话。
我使用c++ std::vector存储数组
我将您的问题解释为根据索引交换数组的两个相邻条目。如果这是错误的,那么请用一个不正确的例子来澄清你的问题。
void swapElements(const std::vector<int>& indexes, std::vector<int>& array){
for(auto i : indexes){
if (i < 1 || i >= array.size()){
continue;
}
std::swap(array[i-1], array[i]):
}
}
我认为最简单的方法是使用具有给定索引的元素和它前面的元素的std::swap
。
第一个元素可以使用
std::swap( v.front(), v.back() );
下面是一个例子
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<char> v = { 'a', 'b', 'c', 'd', 'e', 'f' };
for ( char c : v ) std::cout << c << ' ';
std::cout << std::endl;
for ( size_t i : { 1, 3, 5 } )
{
if ( i == 0 ) std::swap( v.front(), v.back() );
else if ( i < v.size() ) std::swap( v[i], v[i-1] );
}
for ( char c : v ) std::cout << c << ' ';
std::cout << std::endl;
return 0;
}
输出为
a b c d e f
b a d c f e
如果不希望旋转向量,则可以为下面的
构造If语句。for ( size_t i : { 1, 3, 5 } )
{
if ( 0 < i && i < v.size() ) std::swap( v[i], v[i-1] );
}
相关文章:
- 数组元素打印的递归方法
- 在 C++ 中访问数组负索引处的内存不会返回垃圾
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 当该数组的索引中没有元素时,指针指向什么?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 根据字符获取数组的索引
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 从 C++ 数组元素的指针获取索引的最快方法是什么
- 在VS中的Watch中按索引查看数组元素
- 如何使用索引交换预定义的数组元素
- 移动指定索引处的数组元素
- 数组索引与数组元素
- 如何使用静态数组元素作为不同模板实例化对象的静态数组的索引