有没有办法将 cstring 文字(或变量)直接写入现有的 std::array?
也就是说,我想做这样的事情:
std::array<unsigned char, 100> test;
// std::copy("testing", test);
// test="testing";
我希望行为是“复制直到复制空终止符或目标缓冲区已满。”
我试图避免执行 strlcpy(test.data()... 因为我正在寻找一种可以处理缓冲区溢出的方法,而不必显式地将缓冲区长度作为参数包含在内。
谢谢。
编辑:
这是迄今为止我从建议中找到的最佳解决方案。这只适用于文字。 MSVC 没有统一初始化,所以需要在 then { 之前加上 =。它还需要缓冲区大小,但如果缓冲区大小不匹配或出现溢出,编译将失败:
#include <array>
#include <algorithm>
#include <iostream>
int main() {
std::array<char, 100> arr1={"testing"};
std::array<char, 100> arr2;
arr2=arr1;
std::cout << arr2.data();
}
这通常适用于字符串,但要小心,因为嵌入的 null 不会被复制,并且要包含 null,您必须按数组构造,即 string mystring("junk\0", 5)。
#include <string>
#include <array>
#include <algorithm>
#include <iostream>
int main()
{
const std::string str("testing");
std::array<char, 100> arr;
std::copy(str.begin(), str.end(), arr.begin());
// Note that the null terminator does not get copied.
}
最佳答案
应该这样做:
std::array<unsigned char, 100> test = { "testing" };
如果您使用过大的字符串文字,std::array
构造将在编译时失败。但是,这不适用于非文字。
对于非文字,您需要自己检查空终止符。您可以执行类似 std::copy(my_non_literal, my_non_literal + length_literal, test.begin());
之类的操作,但我认为您已经遇到过这种情况。
关于c++ - 是否有将 cstring(可能是文字)复制到 std::array 的标准函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12335580/