简体   繁体   中英

C++ Vector elements' index

#include <iostream>
#include <vector>

int main()
{

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

 }

Is there an efficient way to push "4" to 1's place and push every other element to the next index. So that the vector's element order is {4, 1, 2, 3} instead. I have thought of a few ways, but i was wondering if there is an elegant and more efficient way to do it.

Thanks in advance!

这看起来是为std :: rotate量身定制的:

std::rotate(v.begin(), v.begin()+3, v.end());

You could use standard algorithm std::rotate as for example

#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;
}

However a more efficient approach for such a vector of integer numbers is to use manually standard C function std::memmove as for example

#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;
}

In the both cases the output is

1 2 3 4 
4 1 2 3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM