字符串实例化问题

Issues with instantiation of string

本文关键字:问题 实例化 字符串      更新时间:2023-10-16

我在实例化字符串和将数组传递给另一个函数时遇到问题。昨天,我有以下代码,它运行良好:

string sources[8][3] = {
    {"ab", "cd","ef"},
    {"gh", "ij","kl"},
            (...)
}

我想将sources数组作为参数传递给另一个函数,该函数必须具有以下原型:

size_t parse_data(char *ptr, size_t size, size_t nmemb, char *userdata){

因此,变量将是userdata,我会将其转换为字符串数组的数组。我决定使用指针,但我不能做得更好:

string** sources;
sources = new string*[8];
sources[0] = new string[3];
sources[0][0] = new string("ab");

有更优雅的方法吗?感谢

我不知道你为什么要用现在的方式来做。但是,由于您列出了C++11,静态array可以用以下内容实例化:

#include <array>
...
array<array<string, 3>, 8> sources;

这都在堆栈上,所以不需要动态分配字符串。

可以使用sources[0][0] = string("foo"); 填充条目

您可以使用initializer_list:一次填充所有内容

 array<array<string, 3>, 8> sources { "ab", "cd","ef", "gh", "ij","kl",
                                      (...)};

当将c样式字符串指针传递给parse_data时,您将对数组项调用c_str()

例如:sources[0][0].c_str()


完整示例代码:

#include <array>
#include <iostream>
using namespace std;
int main(int, char **)
{
  array<array<string, 2>, 3> sources { "ab", "cd", "ef", "gh", "ij", "kl"};
  for (size_t i = 0 ; i < sources.size() ; ++i) {
    for (size_t j = 0 ; j < sources[0].size() ; ++j) {
      std::cout << i << "," << j << ": " << sources[i][j] << std::endl;
    }
  }
  return 0;
}

输出:

0,0: ab
0,1: cd
1,0: ef
1,1: gh
2,0: ij
2,1: kl

根据swalog之前的回答,您也可以执行此

std::array<std::array<std::string, 3U>, 8U> strings
{{
    {{"ab", "cd", "ef"}},
    {{"gh", "ij", "kl"}}
}};

以便完全模仿您的原始(并且非常整洁)语法。

为什么你可能会问双背带?std::array基本上是一个数组包装器,所以第一个大括号表示"初始化std::array结构",第二个大括号则表示"用这些值初始化内部数组"。然后你有一个std::arraystd::arrays,所以你需要把这个逻辑乘以2。。。

这个想法的缺点是,自动格式化IDE不太喜欢这样,但除非你正在制作一些高数量的维度,否则你应该没事

编辑:
为了将这些值作为char*传递,您需要重新解释向数组投射指针:

char* userData = reinterpret_cast<char*>(&strings);  

然后重新解释回std::array<std::array<...>>*:

auto array = *reinterpret_cast<std::array<std::array<std::string, 3U>, 8U>*>(userData);

然后,很明显,如果调用者在使用数据之前返回(例如,调用不同线程中的函数来使用数据),则需要分配堆上的所有数据,但我想这对于另一个问题线程来说已经足够了。。。