c++ - 如何遍历 std::vector<char> 并找到以 null 结尾的 c 字符串

标签 c++ stdvector

我根据以下代码片段提出三个问题
我有一个字符串列表。它恰好是一个 vector ,但可能是任何来源

vector<string> v1_names = boost::assign::list_of("Antigua and Barbuda")( "Brasil")( "Papua New Guinea")( "Togo");

下面是存储每个名字的长度

vector<int> name_len;

下面是我要存放字符串的地方

std::vector<char> v2_names;

估计从 v1_names 复制名称所需的内存

v2_names.reserve( v1_names.size()*20 + 4 );

问题:这是估算存储量的最佳方法吗?我将最大长度固定为 20 就可以了,然后为 null tr​​eminator 添加空间
现在复制名称

for( std::vector<std::string>::size_type i = 0; i < v1_names.size(); ++i)
{
    std::string val( v1_names[i] );
    name_len.push_back(val.length());
    for(std::string::iterator it = val.begin(); it != val.end(); ++it)
    {
        v2_names.push_back( *it );
    }
    v2_names.push_back('\0');
}

问题:这是将元素从 v1_name 复制到 v2_names 的最有效方法吗?
主要问题:如何遍历 v2_names 并打印 v2_names 中包含的国家名称

最佳答案

使用简单的连接,利润!

#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>

int main(int, char **)
{
    vector<string> v1_names = boost::assign::list_of("Antigua and Barbuda")( "Brasil")( "Papua New Guinea")( "Togo");

    std::string joined = boost::algorithm::join(v1_names, "\0");
}

关于c++ - 如何遍历 std::vector<char> 并找到以 null 结尾的 c 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7446172/

相关文章:

c++ - 指针模板清除函数的 vector 无法编译并显示 "undefined reference"消息

c++ - 我应该使用 std::vector 而不是数组吗

c++ - 如何从字符串中获取词 vector ?

c++ - 异常:内存位置 0x00e4df90 处的 std::bad_alloc

c++ - 在 C++ 宏 "int val = rand()"中创建新值

c++ - 通过应用程序确定 Windows 版本

c# - 制作 C++/MFC 应用程序以从其他应用程序中提取 AssemblyInfo?

c++ - std::unordered_map operator[] 是否对不存在的键进行零初始化?

c++ - 什么是 std::vector::_emplace_back_slow_path/std::vector::_push_back_slow_path?

c++ - 使用 vector 中的对象排序