我有std :: string变量。我需要从无符号字符数组中加入一些字节。我知道第一个字节和第一个字节。
我可以使用std :: string :: assign函数。我已经完成了。
但我想使用memcpy函数以正确的方式解决该问题。
std::string newString;
memcpy(&newString, &bytes[startIndex], length);
我知道这是错的。我已经研究并使用std :: vector找到了一些想法。
请帮助我找到解决此问题的最佳解决方案。
答案 0 :(得分:18)
由于我们只是构造字符串,因此有一个std::string
构造函数需要两个迭代器:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
我们可以提供:
std::string newString(&bytes[startIndex], &bytes[startIndex] + length);
如果我们没有构建字符串而是分配给现有字符串,您仍然应该使用assign()
。这正是该功能的用途:
oldString.assign(&bytes[startIndex], &bytes[startIndex] + length);
但如果您因某种原因确实坚持memcpy()
,那么您需要确保该字符串实际上有足够的数据可以复制到其中。然后使用&str[0]
作为目标地址†复制到其中:
oldString.resize(length); // make sure we have enough space!
memcpy(&oldString[0], &bytes[startIndex], length);
† Pre-C ++ 11从技术上讲,并不能保证字符串是连续存储在内存中的,但实际上无论如何都要这样做。
答案 1 :(得分:-1)
您需要设置字符串的大小,以便有一个适当大小的缓冲区来接收数据,并将常量从data()
std::string newString;
newString.resize(length);
memcpy((char*)newString.data(), &bytes[startIndex], length);
当然所有这些都是未定义行为的领域,但非常标准而不是。
答案 2 :(得分:-3)
这是一个黑客,因为你说的方式不对,但是因为STL保证std::string
具有连续的存储空间是可能的:
std::string str(32, '\0');
std::strcpy(const_cast<char*>(str.data()), "REALLY DUDE, IT'S ILLEGAL WAY");
当然,您可以以相同的方式使用std::memcpy
(我只使用strcpy
复制以空字符结尾的字符串)...
在你的情况下:
str.resize(length);
memcpy(const_cast<char*>(str.data()), bytes + startIndex, length);