移动指定索引处的数组元素

Shifting array elements at specified indexes

本文关键字:数组元素 索引 移动      更新时间:2023-10-16

什么是最有效的算法移动数组元素在指定的索引左和右一个位置?

例如,将[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] );
}