c++ - 如何将 vector<string> 转换为 null 终止的 char **?

标签 c++

我正在尝试转换 std::vector<std::string>到以 NULL 结尾的 C 风格字符串数组 ( char * )。是否可以不使用 new 进行复制/malloc

基本上,我想在没有 new/malloc 的情况下将 vec 转换回与 arr 完全相同的东西。

#include <string>
#include <vector>
#include <stdio.h>
using namespace std;

void print(const char **strs)
{
   const char **ptr = strs;
   while(*ptr) {
      printf("%s ", *ptr);
      ++ptr;
   }
}

void print(std::vector<std::string> &strs) {
   for(auto iter = strs.begin(); iter != strs.end(); ++iter) {
      printf("%s ", iter->c_str());
   }
}

void main()
{
   const char *arr[] = { "a", "b", "c", "d", "e", "f", NULL };

   vector<string> vec;

   const char **str = arr;
   while(*str) {
      vec.push_back(*str);
      ++str;
   }
   vec.push_back((char *) NULL); //Doesn't work

   //print(vec);
   print((const char **) &vec[0]);
}

最佳答案

仅仅通过设置指向该 vector 开头的指针是不可能的,因为vector<string>不是您期望的连续字符。

                   addr1   addr2    addr3
                    ^        ^        ^
                    |        |        |
                +--------+--------+--------+----
                |   |    |   |    |   |    |
                |  std:: |  std:: |  std:: |
       +---->   | string | string | string | ...
       |        |        |        |        |
       |        +--------+--------+--------+----
       |
       |
       |
 vector<string> 

addr1 , addr2addr3是内存中的随机地址。

因此,解决方案是遍历项目,读取字符串和字符并将它们放入您的 continues 数组中。

关于c++ - 如何将 vector<string> 转换为 null 终止的 char **?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108062/

相关文章:

c++ - 从 C++ 中的 std::string 获取字节

C++ & Qt : Random string from an array area

c++ - 性能方面,按位运算符与普通模数相比有多快?

c++ - 即使库排序正确,命令行也缺少 DSO

c++ - QT Creator C++ MSVC15 : Missing type specifier

c++ - 在非限定 id 之后的静态数据成员定义中使用的名称

c++ - SQLite3 对象不理解?

c++ - 如何缩放到 SDL 中的分辨率?

c++ - 将 nullptr 转换为 std::span

c++ - 什么是STL?