将char*复制到指定pos处的std :: string,而不是分配新对象

jav*_*red 1 c++ string

让我用代码问我的问题:

char* apples = "apples";
std::string str("I like .....");
// need to copy apples to str to have "I like apples", without creating new objects
Run Code Online (Sandbox Code Playgroud)

有分配功能,但遗憾的是似乎无法提供std::string offset.

我不想分配新对象,因为这是低延迟并且经常是代码的一部分.

UPD错,我已经把上述5点,但我的意思是6点,以适应"苹果"完美:)当然,如果串能力没有足够多的某些对象被创建.在我的问题中,我认为字符串容量就足够了.

kas*_*sak 5

您可以使用std::copy算法http://www.cplusplus.com/reference/algorithm/copy/

std::copy(apples, apples + sz, str.begin() + offset);

  • 如果他的愿望是使用`std :: back_inserter(str)`来附加而不是覆盖,因为第三个参数也可以做到.还有许多成员函数:`append`,`insert`等; 在这种情况下,"最安全"的解决方案可能就像`str.replace(offset,std :: string :: npos,apples)`; 这将用`apples`中的字符替换`offset`之后的任何字符,根据需要扩展或减小`str`的​​大小. (2认同)