-1

I have a vector of chars:

std::vector<char> V = {'A', 'B', 'C', 'D'};

How can I extract a substring from this vector? For example, I want to get an "ABC" value of type std::string. What is the most efficient way?

I also would like to avoid copying data as I'm not going to modify the string.

Kaiyakha
  • 1,463
  • 1
  • 6
  • 19

2 Answers2

3

std::string owns the data it holds, so it's not possible to create one without copying the characters. C++17 offers a non-owning std::string_view, which would not create a copy (but due to that you need to ensure lifetime of vector is long enough for the string_view uses).

std::string s1 (V.data(), V.data() + 3); //iterator constructor
std::string s2 (V.data(), 3); //pointer + count constructor

std::string_view sv1 (V.data(), V.data() + 3); //iterator constructor
std::string_view sv2 (V.data(), 3); //pointer + count constructor
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
0

std::vector<char> has a member function called data() that can return the character buffer (which would be a c-string, had it ended with '\0' - not sure if that change is ok for you). This you don't need to copy.

If you wanted a std::string, then a copy is necessary:

std::string s(v.begin(), v.end());

If all you need is a string-like variable, you can go with c-string or std::string_view, latter being a non-owning string.

lorro
  • 10,687
  • 23
  • 36