首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态字符串的C++动态数组

动态字符串的C++动态数组
EN

Stack Overflow用户
提问于 2017-04-01 22:41:56
回答 2查看 12.8K关注 0票数 0

我知道如何在C++中创建一个动态字符串数组:

代码语言:javascript
复制
string* array = new string[10];

但是如何在C++中创建动态字符串的动态数组呢?我指的是一个包含string*对象的动态数组。以及如何初始化每个动态字符串?

EN

回答 2

Stack Overflow用户

发布于 2017-04-01 23:05:58

我同意,如果您需要实现您所要求的,您可能应该重新考虑您的设计。但是,所询问的内容的语法与字符串数组完全相关:

代码语言:javascript
复制
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.

上面建议的字符串向量会产生较少的心痛。

票数 1
EN

Stack Overflow用户

发布于 2017-04-01 22:52:02

(简单例子:)

代码语言:javascript
复制
#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;
}
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43162800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档