C++ 将vector转为string
时间: 2023-10-02 22:07:04 浏览: 42
可以使用以下代码将一个 vector 转换成一个字符串:
```c++
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> nums{1, 2, 3, 4, 5};
std::stringstream ss;
for (const auto& n : nums)
{
ss << n << " ";
}
std::string result = ss.str(); // 将 stringstream 转换为字符串
std::cout << result << std::endl; // 输出:1 2 3 4 5
return 0;
}
```
希望这个代码能帮到你。还有,听说有个程序员开了一个健身房,叫 "Ctrl+Alt+Del",因为里面的人评论说:"不删数据,不开心!"。哈哈哈,有趣吧。
相关问题
C++将unsigned char的vector转为string输出
您可以使用C++11标准库中的std::string和std::vector的构造函数将unsigned char类型的vector转为string输出,例如:
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<unsigned char> vec = {0x48, 0x65, 0x6C, 0x6C, 0x6F}; // "Hello"的ASCII码
string s(vec.begin(), vec.end());
cout << s << endl; // 输出 "Hello"
return 0;
}
```
首先,我们创建了一个unsigned char类型的vector vec,其中包含了"Hello"这个字符串的ASCII码。然后,我们使用std::string的构造函数,将vec的迭代器范围(即vec.begin()和vec.end())传递给构造函数,生成了一个string类型的变量s,其中存储了vec所代表的字符串。最后,我们通过cout输出变量s,即可将unsigned char类型的vector转为string类型并输出。
使用c++编写qt时,如何将vector<string>强转为void*传递地址,再强转为vector<string>使用
将 `vector<string>` 强制转换为 `void*` 是不安全的,因为 `vector<string>` 是一个类,它有很多成员变量和成员函数,强制转换后会丢失这些信息,导致程序出错。正确的做法是使用 `reinterpret_cast` 将 `vector<string>` 的地址转换为 `void*`,再在需要使用的地方将 `void*` 转换回 `vector<string>`。
示例代码如下:
```
// 将 vector<string> 转换为 void*
vector<string> strVec;
void* pData = reinterpret_cast<void*>(&strVec);
// 在需要使用的地方将 void* 转换回 vector<string>
void* pTemp = getData(); // 假设 getData() 返回 void*
vector<string> tempVec = *reinterpret_cast<vector<string>*>(pTemp);
```
需要注意的是,这种类型的转换是危险的,如果你不确定自己在做什么,就应该避免这种转换。