简体   繁体   中英

Std::string to std::array?

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;
}

That seems fine. There isn't such a thing in C++11, and I don't think there is one in Boost either. If you don't want to paste this all over the place, you can just put it in a header and #include that.

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.

That's fine, maybe with a minor modification in C++11.

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;
    using std::begin; using std::end; 
    std::copy( begin(v), end(v), begin(d) ); // this is the recommended way
    return d;
}

That way, if you remove the assertion, this function would work even if v is a raw array.

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.

It doesn't work with std::string, but if you're using a C string literal (char const *), C++20 introduces std::to_array<\/code> for just this sort of thing:

std::array arr {"Hello, world!"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM