Short of (the obvious) building a C style string first then using that to create a std::string, is there a quicker/alternative/"better" way to initialize a string from a vector of chars?
7 Answers
Well, the best way is to use the following constructor:
template<class InputIterator> string (InputIterator begin, InputIterator end);
which would lead to something like:
std::vector<char> v;
std::string str(v.begin(), v.end());
I think you can just do
std::string s( MyVector.begin(), MyVector.end() );
where MyVector is your std::vector.
-
2Except in VS2013 which asserts at runtime about invalid iterators, unless you set
_ITERATOR_DEBUG_LEVEL=1
(in which case it seems to work fine).– CameronSep 23, 2014 at 22:39
With C++11, you can do std::string(v.data())
or, if your vector does not contain a '\0'
at the end, std::string(v.data(), v.size())
.
-
Even with C++98, I believe you can do std::string(&v[0]). This, of course, is if the vector is null-terminated.– JamieApr 16, 2016 at 0:48
-
1@Jamie: By the way, in C++98,
string(&v[0], v.size())
should work also, but only afterassert(not v.empty());
, since if the vector is empty, bothv[0]
andv.front()
would invoke undefined behavior. That, aside from the syntactic simplicity of not having to use the address-of operator, is the real benefit of C++11'sdata()
function, which works even on an empty vector. Apr 25, 2016 at 19:46 -
Very true. Unfortunately, my project is stuck on Visual Studio 2008 for the foreseeable future. Right about checking vector length first.– JamieMay 2, 2016 at 17:51
-
1If vector does not contain a '\0',
std::string(v.data())
might lead a longer string. So do not use this way.– heLomaNNov 20, 2018 at 12:53 -
@heLomaN: What's wrong with
std::string(v.data(), v.size())
, which was explicitly mentioned in the answer for that exact reason?– Sz.Aug 13, 2019 at 11:50
std::string s(v.begin(), v.end());
Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)
I like Stefan’s answer (Sep 11 ’13) but would like to make it a bit stronger:
If the vector ends with a null terminator, you should not use (v.begin(), v.end()): you should use v.data() (or &v[0] for those prior to C++17).
If v does not have a null terminator, you should use (v.begin(), v.end()).
If you use begin() and end() and the vector does have a terminating zero, you’ll end up with a string "abc\0" for example, that is of length 4, but should really be only "abc".
-
-
Is there a performance difference between
(v.begin(), v.end())
and(v.data())
? Will the latter beO(n)
?– 김선달Nov 30, 2020 at 4:34
Just for completeness, another way is std::string(&v[0])
(although you need to ensure your string is null-terminated and std::string(v.data())
is generally to be preferred.
The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().
-
Why can't you use
data()
to modify the buffer? It looks to me like if you calldata()
on a non-const vector, it will return aT *
(and if your vector is const, 'v[0]` would return aT const &
anyway). Apr 25, 2016 at 19:42 -
@AdamH.Peterson it seems to be an oversight in the standard. Std::vector's data has both const and non-const functions, whereas in the current standard, std::string has only a const function: en.cppreference.com/w/cpp/string/basic_string/data Note that C++17 adds a non-const version, so this may not be the case indefinitely - however, the current standard states "Modifying the character array accessed through data has undefined behavior."– RiotApr 26, 2016 at 16:48
-
That would be true if
v
were a string, but the target type is a string andv
is a vector. (But it is nice to see that C++17 will give strings parity with vector.) Apr 26, 2016 at 16:51 -
@AdamH.Peterson you're right of course. The question was answered a while ago, I'd assumed the whole question was about strings exclusively without checking.– RiotApr 26, 2016 at 17:44
vector<char> vec;
//fill the vector;
std::string s(vec.begin(), vec.end());
-
-
1C++11 string library template goes as follows default (1) string(); copy (2) string (const string& str); substring (3) string (const string& str, size_t pos, size_t len = npos); from c-string (4) string (const char* s); from buffer (5) string (const char* s, size_t n); fill (6) string (size_t n, char c); range (7) template <class InputIterator> string (InputIterator first, InputIterator last); initializer list (8) string (initializer_list<char> il); move (9) string (string&& str) noexcept; we are following 7th template.– TechCatMay 13, 2020 at 15:27
-
Hi @TechCat! Please read up on writing a good answer before answering your next question. Enjoy your stay at SO!– Diggy.May 13, 2020 at 15:49
-
-
Not sure why this was down voted, this is a perfectly acceptable answer. Jan 4 at 0:57
std::vector<char> v2(std::move(v))
but with astd::string
as the new object.