Search code examples
c++vectorstdstring

Initialization of std::string from std::vector<unsigned char> causes error


In C++ we can create a vector from another vector via
std::vector<unsigned char> tmp_1 { &some_vector[i] , &some_vector[j] };

Question : Is there any way to do the same for std::string?
Something like:

std::string tmp2 { &some_vector[i] , &some_vector[j] };

Attempts to use constructor from documentation always return error;

Note: *some_vector is the vector of unsigned chars

UPD: Found answer: had typo so tried to access [-1] element.


Solution

  • std::string has several constructors, some of which can be used to construct the string from a std::vector, eg:

    // using a char* pointer and a size...
    std::string tmp2( reinterpret_cast<char*>(&some_vector[i]), j-i );
    

    // using char* pointers as iterators...
    std::string tmp2( &some_vector[i], &some_vector[j] );
    

    // using vector iterators...
    std::string tmp2( some_vector.begin()+i, some_vector.begin()+j );
    

    Live Demo