我知道如何在C++中创建一个动态字符串数组:
string* array = new string[10];但是如何在C++中创建动态字符串的动态数组呢?我指的是一个包含string*对象的动态数组。以及如何初始化每个动态字符串?
发布于 2017-04-01 23:05:58
我同意,如果您需要实现您所要求的,您可能应该重新考虑您的设计。但是,所询问的内容的语法与字符串数组完全相关:
string** sillyIdea = new string*[10];
//some access examples
sillyIdea[0]= new string;
*(sillyIdea[0]) = "hello";
(*(sillyIdea[0]))[0] = 'H';
sillyIdea[1]= new string;
//statement below looks like a 2d array construct but it is not,
//just shorthand for
// *((sillyIdea[1]) + 0)
sillyIdea[1][0] = "world";
//an array of pointers can usually be treated programtcally as a
//jaggedarray(asymtrical multi-dimensional array). In other words,
// your array of string pointers can be treated like an array of one
//element string arrays, making for a cleaner syntax, but worse code.
//in int main(int argc, char** argv), argv is one such example of a jagged array.上面建议的字符串向量会产生较少的心痛。
发布于 2017-04-01 22:52:02
(简单例子:)
#include <iostream>
using namespace std;
int main() {
int n, m;
cin>>n;
cin>>m;
string** array = new string*[n];
for(int i = 0; i<n; i++)
{
array[i] = new string[m];
}
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
cin>>array[i][j];
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
cout<<array[i][j]<<endl;
return 0;
}https://stackoverflow.com/questions/43162800
复制相似问题