字符串实例化问题
Issues with instantiation of string
我在实例化字符串和将数组传递给另一个函数时遇到问题。昨天,我有以下代码,它运行良好:
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::array
的std::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);
然后,很明显,如果调用者在使用数据之前返回(例如,调用不同线程中的函数来使用数据),则需要分配堆上的所有数据,但我想这对于另一个问题线程来说已经足够了。。。
- 从C++实例化QML
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?
- 显式模板实例化问题
- 实例化函数模板的编译问题
- 模板函数实例化的可移植性问题
- 模板函数实例化 自定义数据类型的问题
- 字符串实例化问题
- 在 C++ 中实例化指向新对象的指针时出现问题
- 何时会隐式实例化导致问题
- Cygwin gcc编译器使用GAlib的模板实例化问题
- 复杂数据类型的模板实例化问题
- 类和函数模板实例化的Visual Studio dll导出问题
- c++中的工厂模式.实例化问题
- Qt继承和实例化问题
- c++中多态性基类和继承类实例化的问题
- 在实例化结构模板时出现问题
- 实例化模板化类的问题
- 实例化子类的多态性问题
- 对以下用户定义类片段中的模板实例化问题表示怀疑
- 继承——实例化问题