Reputation: 7
what is the easiest way to copy a two-dimensional array of chars into a one-dimensional array of strings in c++?
something like that:
char inCharArray[3][255];
string outStringArray[3];
for (int i = 0; i < sizeof(inCharArray) / sizeof(inCharArray[i]); i++)
{
outStringArray[i] = inCharArray[i];
}
Regards Tillman
Upvotes: 0
Views: 268
Reputation: 4449
This alternative to std::transform
is more readable to me:
std::copy(std::begin(inCharArray),
std::end(inCharArray),
std::begin(outStringArray));
// only safe if input strings are null-terminated and arrays have equal size
static_assert(std::size(inCharArray) == std::size(outStringArray),
"arrays are not equal size");
Also consider using std::array
instead of C-style arrays while you're writing C++ code.
Upvotes: 0
Reputation: 41760
Using STL algorithm is one of the best way to do it.
char inCharArray[3][255];
string outStringArray[3];
std::transform(
std::begin(inCharrArray),
std::end(inCharArray),
std::begin(outStringArray),
[](char const* c_str) -> std::string {
return std::string{c_str};
}
);
This is assuming the strings are ending sooner than 255.
Upvotes: 1