简体   繁体   English

"标准::字符串到标准::数组?"

[英]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. C ++ 11中没有这种东西,Boost中也没有。 If you don't want to paste this all over the place, you can just put it in a header and #include that. 如果您不想将其粘贴到整个位置,则可以将其放在标题中并#include

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. 很好,也许在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. 这样,如果删除断言,即使v是原始数组,此函数也将起作用。

If you really only want convert string to an array, just use .c_str() (and work on char* ). 如果您真的只想将字符串转换为数组,则只需使用.c_str() (并在char*上工作)。 It isn't exactly array<> but may suit your needs. 它不完全是array<>但可以满足您的需求。

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::string,但如果您使用 C 字符串文字 (char const *),C++20 仅针对此类事情引入std::to_array<\/code> :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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