std::vector<char*> 如何打印
时间: 2024-05-14 12:19:19 浏览: 17
可以使用循环遍历 vector 中的每个 char* 指针,然后使用 printf 或 cout 打印指针所指向的字符串,例如:
```c++
#include <iostream>
#include <vector>
#include <cstdio>
int main() {
std::vector<char*> vec{"hello", "world", "!"};
for (const auto& str : vec) {
printf("%s ", str);
}
std::cout << std::endl;
return 0;
}
```
输出结果为:
```
hello world !
```
相关问题
std::vector<char*> 拼接成string
可以使用`std::string`的构造函数或者`operator+=`操作符将`std::vector<char*>`拼接成一个字符串。
方法1:使用`std::string`的构造函数
```cpp
#include <vector>
#include <string>
std::vector<char*> vec = { "hello", ",", "world", "!" };
std::string str(vec[0]);
for (int i = 1; i < vec.size(); ++i) {
str += std::string(vec[i]);
}
```
方法2:使用`operator+=`操作符
```cpp
#include <vector>
#include <string>
std::vector<char*> vec = { "hello", ",", "world", "!" };
std::string str;
for (auto s : vec) {
str += std::string(s);
}
```
需要注意的是,`std::vector<char*>`存储的是C风格字符串,需要将其转换为`std::string`类型才能进行字符串拼接。
std::vector<unsigned char>如何转std::string
引用中提供了一个示例函数`Vec2Str`,可以将`std::vector<unsigned char>`转换为`std::string`。该函数首先使用`reserve`函数来为目标字符串`StrChar`分配足够的内存空间,然后使用`push_back`函数将每个字符逐个添加到`StrChar`中。
下面是使用`Vec2Str`函数将`std::vector<unsigned char>`转换为`std::string`的示例代码:
```cpp
void Vec2Str(std::vector<unsigned char>& VecChar, std::string& StrChar) {
StrChar.reserve(VecChar.size());
for (int iIndex = 0; iIndex < VecChar.size(); iIndex++) {
StrChar.push_back(static_cast<char>(VecChar[iIndex]));
}
}
// 示例用法
std::vector<unsigned char> VecChar;
// 添加元素到VecChar
std::string StrChar;
Vec2Str(VecChar, StrChar);
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)