c++ - 将字符串列表转换为 C 样式数组

标签 c++ arrays list winsock

我有一个 std::list<std::wstring>

[0] = "abc"
[1] = "wds"
[2] = "rew"
[n] = ...

(不要在意列表中的索引,它只是为了示例)

有什么简单的方法可以将它转换成经典的 C 字节数组,以便我可以使用 winsocks 发送它 send()功能?

最佳答案

警告:我没有编译这个。但它应该给你这个想法。基本上,您只需创建 C 样式数组并将每个字符串中的数据附加到其中:

std::vector<wchar_t> cArray;

// Optional: Calculate the length of the desired byte array in advance
std::size_t actualSize = 1 + strings.size(); // stringLengths + number of strings + 1
for (std::wstring const& source : strings)
{
    actualSize += source.size();
}
cArray.reserve(actualSize);
// End optional bits

for (std::wstring const& source : strings)
{
    cArray.insert(cArray.end(), source.begin(), source.end());
    cArray.push_back(L'\0'); // null terminate
}

// double null terminate?
cArray.push_back(L'\0');

char const* cByteArray = reinterpret_cast<char const*>(cArray.data());

关于c++ - 将字符串列表转换为 C 样式数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26681870/

相关文章:

c++ - 常量成员函数

c++ - 使用数组在C++中创建卡片组数据结构

list - 返回普通lisp中没有最后一个元素的列表

list - Prolog:找出所有列表元素的总和是否等于 N

通过 C 中的数组自定义迭代打印每个第 n 个值

python-3.x - Python 列表创建差异

c++ - (C++ 和 OpenGL)我试图在批处理渲染器中旋转一组顶点(它将模拟一个正方形),但它不是 100% 工作 :(

c++ - Node 插件 (OSX) 中的 GraphicsMagick 代码卡住

c++ - 从源代码构建 pcl-1.7.1 时链接到 boost 库

ruby - 如何替换 block 中的字符串