c++ vector一维字符串数组
时间: 2024-04-17 12:21:50 浏览: 16
C++中的vector是一个动态数组容器,可以存储不同类型的数据,包括字符串。一维字符串数组可以通过vector<string>来实现。
下面是使用vector创建一维字符串数组的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <string>
int main() {
std::vector<std::string> strArray; // 创建一个空的字符串数组
// 向数组中添加元素
strArray.push_back("Hello");
strArray.push_back("World");
strArray.push_back("C++");
// 遍历数组并输出每个字符串
for (const auto& str : strArray) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
```
运行以上代码,输出结果为:
```
Hello World C++
```
相关问题
c++ 二维字符串数组
C++中的二维字符串数组是一个包含多个字符串的数组,每个字符串又是一个字符数组。可以使用二维数组或者使用vector<vector<string>>来表示二维字符串数组。
使用二维数组表示二维字符串数组的示例代码如下:
```cpp
#include <iostream>
using namespace std;
int main() {
const int rows = 3;
const int cols = 4;
// 声明并初始化二维字符串数组
string arr[rows][cols] = {
{"Hello", "World", "C++", "Programming"},
{"CSDN", "AI", "Assistant", "Chatbot"},
{"Array", "of", "Strings", "Example"}
};
// 遍历输出二维字符串数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
使用vector<vector<string>>表示二维字符串数组的示例代码如下:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<string>> arr = {
{"Hello", "World", "C++", "Programming"},
{"CSDN", "AI", "Assistant", "Chatbot"},
{"Array", "of", "Strings", "Example"}
};
// 遍历输出二维字符串数组
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
c++字符串二维数组
在C++中,可以使用二维字符数组来表示字符串的二维数组。二维字符数组是一个由字符组成的矩阵,每个元素是一个字符。
以下是创建和使用二维字符数组的示例:
```cpp
#include <iostream>
int main() {
const int rows = 3;
const int cols = 5;
char strArray[rows][cols] = {
{'H', 'e', 'l', 'l', 'o'},
{'W', 'o', 'r', 'l', 'd'},
{'C', '+', '+', ' ', '\0'}
};
// 输出二维字符数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << strArray[i][j];
}
std::cout << std::endl;
}
return 0;
}
```
上述代码创建了一个3行5列的二维字符数组`strArray`,并用字符串初始化了每个元素。注意,字符串最后一个字符可以是空字符(`'\0'`),表示字符串的结束。
输出结果为:
```
Hello
World
C++
```
需要注意的是,二维字符数组的大小在编译时必须是已知的常量,无法在运行时动态改变大小。如果需要动态修改大小,请考虑使用动态分配内存或者使用`std::vector<std::string>`等C++标准库容器来代替二维字符数组。