C++ 字符串数组
在本节,我们将了解如何在 C++ 中定义字符串数组。众所周知,C 中没有字符串。我们必须使用字符数组创建字符串。因此,要制作一些字符串数组,我们必须制作一个双维字符数组。每个行都在该矩阵中保存不同的字符串。
C++ 中有一个名为 string 的类。使用此类对象,我们可以存储字符串类型的数据,并非常高效地使用它们。我们可以创建对象数组,因此我们可以轻松地创建字符串数组。
之后,我们还将了解如何创建字符串类型的向量对象并将它们用作数组。
示例
#include<iostream>
using namespace std;
int main() {
string animals[4] = {"Elephant", "Lion", "Deer", "Tiger"}; //The
string type array
for (int i = 0; i < 4; i++)
cout << animals[i] << endl;
}输出
Elephant Lion Deer Tiger
现在让我们看看如何使用向量创建字符串数组。向量可在 C++ 标准库中使用。它使用动态分配的数组。
示例
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<string> animal_vec;
animal_vec.push_back("Elephant");
animal_vec.push_back("Lion");
animal_vec.push_back("Deer");
animal_vec.push_back("Tiger");
for(int i = 0; i<animal_vec.size(); i++) {
cout << animal_vec[i] << endl;
}
}输出
Elephant Lion Deer Tiger
广告
数据结构
网络连接
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP