Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Std::string to std::array?

Tags:

c++

c++11

What's the recommended way to convert a string to an array? I'm looking for something like:

template<class T, size_t N, class V>
std::array<T, N> to_array(const V& v)
{
    assert(v.size() == N);
    std::array<T, N> d;
    std::copy(v.begin(), v.end(), d.data());
    return d;
}

Does C++11 or Boost provide something like this? How do others do this? Seems silly having to copy/paste this function myself every time I need it in a project.

like image 696
XTF Avatar asked Apr 17 '12 11:04

XTF


People also ask

How do you copy a string into an array?

Using c_str() with strcpy() A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring.

How do I convert a string to an array of characters C++?

The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.

Is std::string an array?

Now, you know that std::string is the basic_string for char -typed characters. Referring to Does std::string need to store its character in a contiguous piece of memory?, if you are mentioning std::string then for C++ 11 and later versions, it is essentially AN array (not TWO or MORE arrays) of char -typed characters.

Can you treat a string like an array in C++?

In C++, the string can be represented as an array of characters or using string class that is supported by C++. Each string or array element is terminated by a null character. Representing strings using a character array is directly taken from the 'C' language as there is no string type in C.


2 Answers

If you really only want convert string to an array, just use .c_str() (and work on char*). It isn't exactly array<> but may suit your needs.

like image 193
Bartek Banachewicz Avatar answered Oct 06 '22 11:10

Bartek Banachewicz


Simply calling:

std::copy(v.begin(), v.end(), d.data());

is The way to convert a string to the array. I don't see any advantage of wrapping this into a dedicated "utility" function.

In addition, unless the compiler optimizes it, the performance may degrade with your function: the data will be copied second time when returning the array.

like image 43
David L. Avatar answered Oct 06 '22 09:10

David L.