C ++ Vector元素'指数

时间:2016-07-04 13:16:37

标签: c++ algorithm vector rotation

#include <iostream>
#include <vector>

int main()
{

std::vector<int> v = {1, 2, 3, 4};

 }

是否有一种有效的推动方式&#34; 4&#34;到1的位置并将每个其他元素推送到下一个索引。因此,向量的元素顺序为{4,1,2,3}。我想过几个方法,但我想知道是否有一种优雅而有效的方法来做到这一点。

提前致谢!

2 个答案:

答案 0 :(得分:6)

这看起来是为std :: rotate:

量身定制的
std::rotate(v.begin(), v.begin()+3, v.end());

答案 1 :(得分:1)

您可以使用标准算法std::rotate作为示例

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

int main() 
{
    std::vector<int> v = {1, 2, 3, 4};

    for ( int val : v ) std::cout << val << ' ';
    std::cout << std::endl;

    std::rotate( std::begin( v ), std::prev( std::end( v ) ), std::end( v ) );

    for ( int val : v ) std::cout << val << ' ';
    std::cout << std::endl;

    return 0;
}

然而,对于这样的整数数向量,更有效的方法是使用手动标准C函数std::memmove,例如

#include <iostream>
#include <vector>
#include <cstring>

int main() 
{
    std::vector<int> v = {1, 2, 3, 4};

    for ( int val : v ) std::cout << val << ' ';
    std::cout << std::endl;

    int value = v.back();
    std::memmove( v.data() + 1, v.data(), ( v.size() - 1 ) * sizeof( int ) );
    v[0] = value;

    for ( int val : v ) std::cout << val << ' ';
    std::cout << std::endl;

    return 0;
}

在这两种情况下,输出都是

1 2 3 4 
4 1 2 3