我想调用一个库函数,它的签名是:
bool WriteBinary(const std::vector<uint8_t> & DataToWrite);
我有一个 std::string
变量,我想将这个函数作为参数发送给它。
void WriteString(const std::string & TextData)
{
// ...
WriteBinary(TextData); // <-- How to make this line work?
// ...
}
有没有一种方法可以直接发送 std::string
变量而不复制它?
最佳答案
没有办法做到这一点,因为不能保证这两种类型的布局在任何方面都相似。
最好的方法是修复 WriteBinary
以使用“迭代器”代替:
bool WriteBinary(const unsigned char* first, const unsigned char* last);
或者模板化它:
template <typename Iter>
bool WriteBinary(Iter first, Iter last);
然后您可以将它用于字符串、 vector 或您喜欢的任何其他容器!
否则,您可以使用迭代器构造函数尽可能高效地进行复制:
WriteBinary(std::vector<uint8_t>(TextData.begin(), TextData.end()));
关于c++ - 如何在不制作拷贝的情况下将 `std::string` 转换为 `std::vector<unsigned char>`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16595713/