C++ 中的字符串数组(5 种不同的创建方式3-5)


theme: channing-cyan highlight: a11y-dark


小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

3. 使用字符串类:

STL字符串类可用于创建可变字符串数组。在这种方法中,字符串的大小不固定,可以更改字符串。 

这仅在 C++ 中受支持,因为 C 没有类。

#include <iostream>
#include <string>

int main()
{
    std::string colour[4] = { "Blue", "Red",
                            "Orange", "Yellow" };

    for (int i = 0; i < 4; i++)
        std::cout << colour[i] << "\n";
}

输出

Blue
Red
Orange
Yellow

  • 数组的大小是固定的,但不是必须的。同样,这里的 4 可以省略,编译器会确定数组的合适大小。字符串也是可变的,允许更改它们。

4. 使用向量类:

STL 容器Vector可用于动态分配大小可变的数组。

这仅在 C++ 中可用,因为 C 没有类。请注意,此处的初始化列表语法需要支持 2011 C++ 标准的编译器,尽管您的编译器很可能会支持,但需要注意这一点。

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> colour {"Blue", "Red", "Orange"};
    colour.push_back("Yellow");
    for (int i = 0; i < colour.size(); i++)
        std::cout << colour[i] << "\n";
}

输出

Blue
Red
Orange
Yellow

  • 向量是动态数组,允许您随时添加和删除项目。
  • 向量中可以使用任何类型或类,但给定的向量只能包含一种类型。

5.使用数组类:

STL 容器数组可用于分配固定大小的数组。它的使用方式可能与矢量非常相似,但大小始终是固定的。

这仅在 C++ 中受支持。

#include <iostream>
#include <array>
#include <string>
int main()
{
    std::array<std::string, 4> colour { "Blue", "Red", "Orange",
                                    "Yellow" };

    for (int i = 0; i < 4; i++)
        std::cout << colour[i] << "\n";
    return 0;
}

输出

Blue
Red
Orange
Yellow

笔记:

这些绝不是制作字符串集合的唯一方法。C++ 提供了多个容器类,每个类都有不同的权衡和特性,它们的存在都是为了满足您在项目中的需求。

未经允许不得转载:木盒主机 » C++ 中的字符串数组(5 种不同的创建方式3-5)

赞 (0)

相关推荐

    暂无内容!