20

I have a pointer to a vector of type uint8.

How would I take this pointer and convert the data in the vector into a full string representative of its content?

deddebme
  • 445
  • 1
  • 5
  • 10
Mr S
  • 458
  • 3
  • 7
  • 15

3 Answers3

40

You could just initialize the std::string with the sequence obtained from the std::vector<uint8_t>:

std::string str(v->begin(), v->end());

There is no need to play any tricks checking whether the std::vector<uint8_t> is empty: if it is, the range will be empty. However, you might want to check if the pointer is v is null. The above requires that it points to a valid object.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Is it okay if I ask why you were gone for so long? – David G Jul 31 '13 at 23:47
  • 3
    @0x499602D2: You mean, why I didn't answer questions for a while? It's simple: I was busy trying to get work done besides work. Right now I'm to busy at work to work besides work. – Dietmar Kühl Jul 31 '13 at 23:53
  • I'm surprised this answer is accepted because it does not produce something "representative of its content". If you vector is "{1,2,3,4,5,6,7,8,9}" then your output will be a string of non-displayable characters! – Jérémy Pouyet Nov 12 '16 at 09:45
  • 1
    @JérémyPouyet: it seems we interpreted the question differently: I read as asking to convert a sequence of bytes in a `std::vector` to the same sequence of bytes in a `std::string`. The answer matches that interpretation. You interpretation seems to be _formatting_ the content of a `std::vector<...>` and storing the result in a `std::string`. That question is often asked/answered although possibly in two parts: How to format a vector? How to direct the output of a stream to a string? – Dietmar Kühl Nov 12 '16 at 10:15
9

For those who wants the conversion be done after a string is declared, you may use std::string::assign(), e.g.:

std::string str;
std::vector<uint8_t> v;
str.assign(v.begin(), v.end());
deddebme
  • 445
  • 1
  • 5
  • 10
0
vector<uint8_t> *p;
string str(
    p && !p->empty() ? &*p->begin()             : NULL,
    p && !p->empty() ? &*p->begin() + p->size() : NULL);
user541686
  • 205,094
  • 128
  • 528
  • 886
  • There is no need to play any tricks with `empty()` vectors: they'll return a valid range and `std::string` has a constructor taking a pair of input iterators. – Dietmar Kühl Jul 31 '13 at 23:40
  • @DietmarKühl: Oh yeah you're right, I have a habit of doing this because I sometimes compile with an old STL implementation that doesn't have that templated overload, totally forgot. – user541686 Jul 31 '13 at 23:51
  • yes, the old RogueWave implementation still shipping as the default standard C++ library for Sun Studio, I guess. If I had to use that I would actually use `std::copy(v->begin(), v->end(), std::back_inserter(str));`. – Dietmar Kühl Jul 31 '13 at 23:56