Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::move between std::string and std::vector<unsigned char>

I am working with 2 libraries. One takes in and returns std::strings while the other uses std::vector<unsigned char>s.

It would be good if I could steal the underlying arrays from std::string and std::vector<unsigned char> and be able to move them into each other without the excessive copying.

ATM I use something like:

const unsigned char* raw_memory =
    reinterpret_cast<const unsigned char*>(string_value.c_str()),
std::vector<unsigned char>(raw_memory, raw_memory + string_value.size();

And the other way:

std::string(
    reinterpret_cast<const char*>(&vector_value[0]),
    vector_value.size());

It'd be far better to be able to define a:

std::string move_into(std::vector<unsigned char>&&);
std::vector<unsigned char> move_into(std::string&&);
like image 314
genjix Avatar asked May 04 '12 08:05

genjix


People also ask

What is the difference between std :: string and std :: vector?

std::string offers a very different and much expanded interface compared to std::vector<> . While the latter is just a boring old sequence of elements, the former is actually designed to represent a string and therefore offers an assortment of string-related convenience functions.

Is std :: string a char *?

h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.


1 Answers

You can use the initialization using iterators. Have a look here

EDIT: pasting the code so that you don't have to go to ideone. Still leaving the link so that you can play arround with the code

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
        string a = "Hello world";
        vector<unsigned char> v(a.begin(), a.end());
        for (int i= 0 ;i<  v.size(); ++i) {
           cout << v[i] << endl;
        }
        string s(v.begin(), v.end());
        cout << s << endl;
        return 0;
}
like image 171
Ivaylo Strandjev Avatar answered Sep 20 '22 14:09

Ivaylo Strandjev