简体   繁体   中英

Push into vector in reverse order

How can I push the byes in a char[] array into a std::vector<char> in reverse order? eg I want to push

char c[] = "a string";

into

std::vector<char> v;

so that in the end v will contain

{'g','n','i','r','t','s',' ','a'}

?

std::string cString(c);
std::vector<char> v(cString.rbegin(), cString.rend());

or

v.insert(v.end(), cString.rbegin(), cString.rend());

for existing vector.

With reverse iterators:

typedef std::reverse_iterator<const char*> r_it;
std::vector<char> v ( r_it(std::end(c)), r_it(std::begin(c)) );

In C++14, we'll be able to do

std::vector<char> v( std::crbegin(c), std::crend(c) );

To append to an existing vector, use

v.insert( v.end(), rbegin, rend );

If don't feel like using std::string (avoiding allocation etc.) you can use reverse_iterator explicitly. I use helper function cause I hate specifying template parameters explicitly:

template <class It>
std::reverse_iterator<It> make_reverse(It it)
{
    return std::reverse_iterator<It>(it);
}

...

char c[] = "a string";
std::vector<char> v( make_reverse(std::end(c)) + 1, make_reverse(std::begin(c)) );

The +1 is there because you want to skip the trailing \\0 from c .

#include <algorithm>
#include <iterator>
[...]

char c[] = "a string";
std::vector<char> v;

std::reverse_copy(c, c + sizeof(c)/sizeof(c[0]), std::back_inserter(v));

Thanks to chris for originally suggesting reverse_copy in the comments.

Note that with this approach you will get a '\\0' in the first element of your vector.

If you'd like to use reverse_copy :

char c[] = ...;
std::vector<char> vec;
// Avoid to copy the terminating '\0': Don't add +1 to strlen(c)
std::reverse_copy(c, c+strlen(c), std::back_inserter(vec));

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