📜  在C ++中使用向量向左旋转数组

📅  最后修改于: 2021-05-31 18:12:10             🧑  作者: Mango

给定一个整数数组arr []和另一个整数D ,任务是对数组执行D左旋转并打印修改后的数组。

例子:

Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 2
Output: 3 4 5 6 1 2

Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 12
Output: 1 2 3 4 5 6

方法:使用C++中的向量,可以通过从向量中删除第一个元素然后将其插入相同向量的末尾来执行旋转。同样,可以执行所有所需的旋转,然后打印修改后的矢量的内容以获得所需的旋转数组。

下面是上述方法的实现:

CPP
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to left rotate the array by d elements
// here we are passing vector by reference to avoid copying
// that just make our program slow
void rotate(vector& vec, int d)
{
    // Base case
    if (d == 0)
        return;
 
    // Push first d elements from the beginning
    // to the end and remove those elements
    // from the beginning
    for (int i = 0; i < d; i++)
    {
        // adding first element at
        // the end of vector
        vec.push_back(vec[0]);
       
        // removing first element
        vec.erase(vec.begin());
    }
 
    // Print the rotated array
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }
}
 
// Driver code
int main()
{
    vector vec = { 1, 2, 3, 4, 5, 6 };
    int n = vec.size();
    int d = 2;
 
    // Function call
    rotate(vec, d % n);
 
    return 0;
}


输出
3 4 5 6 1 2 
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”