C ++中的字符串初始化数组 [英] Array of strings initialization in c++

查看:325
本文介绍了C ++中的字符串初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以这样初始化

i know i can initialize like this

std::string foo [3] = {"T1","T2","T3"};

但是如果在未声明之前声明它,该怎么办呢?
示例

but what if declared it before do i have to initialize each one by its own? example

std::string foo [3];
foo[0] = "T1"
foo[1] = "T2"
foo[2] = "T3"

我的意思是一次给字符串所有值foo = { T1, T2, T3}

i mean giving the string all the values at once foo ={"T1","T2","T3"}

推荐答案

从技术上讲,您不能在声明后对其进行初始化。细微差别很重要,因为在第二个示例中,您将分配给各个字符串。现在,您想分配给整个阵列,这是行不通的。如果使用更智能的数据结构,例如 std :: vector ,则实际上可以在一条指令中分配所有值,因为矢量会丢弃旧的字符串并创建新的字符串,将从您的 T1 ,..字符串构造而成。

Technically, you cannot initialise it after the declaration. The nuance is important, because in your second example you assign to the individual strings. Now, you want to assign to the whole array, which doesn't work. If you used a more intelligent data structure like std::vector you could indeed assign all values in one instruction, because the vector would throw away the old strings and create new ones that would be copy constructed from your "T1",.. strings.

这篇关于C ++中的字符串初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆