在C++中,动态数组vector怎么转换string类型
时间: 2023-03-26 11:01:48 浏览: 85
可以使用vector的成员函数data()获取vector的底层数组指针,然后使用string的构造函数将其转换为string类型,示例代码如下:
vector<char> vec = {'h', 'e', 'l', 'l', 'o'};
string str(vec.data(), vec.size());
注意:vector中存储的元素类型必须与string中的元素类型相同,否则需要进行类型转换。
相关问题
C++ 查找vector<string>中的数组
如果你想在 `vector<string>` 中查找一个特定的字符串,可以使用 `std::find` 算法。以下是一个示例代码,它在 `vector<string>` 中查找字符串 `"hello"`:
```C++
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> vec = { "hello", "world", "foo", "bar" };
auto it = std::find(vec.begin(), vec.end(), "hello");
if (it != vec.end())
{
std::cout << "Found string: " << *it << std::endl;
}
else
{
std::cout << "String not found" << std::endl;
}
return 0;
}
```
如果你想查找多个字符串,可以使用循环来反复调用 `std::find`。如果你想查找符合某些特定条件的字符串,可以使用 `std::find_if` 算法。
string类型的数组如何转换成Double类型
将 string 类型的数组转换成 Double 类型的数组,需要使用循环遍历数组中每个元素,并对每个元素进行类型转换。
下面是使用 C++ 的示例代码:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
// 定义 string 类型的数组
string strArray[] = {"1.23", "4.56", "7.89"};
// 定义 Double 类型的数组
vector<double> doubleArray;
// 遍历 string 类型的数组,将每个元素转换为 Double 类型,并添加到 Double 类型的数组中
for (int i = 0; i < sizeof(strArray) / sizeof(strArray[0]); i++) {
doubleArray.push_back(stod(strArray[i]));
}
// 输出 Double 类型的数组
for (int i = 0; i < doubleArray.size(); i++) {
cout << doubleArray[i] << " ";
}
return 0;
}
```
输出结果为:
```
1.23 4.56 7.89
```
在上面的示例代码中,使用了 stod() 函数将 string 类型的元素转换成 Double 类型,然后将转换后的 Double 类型元素添加到 vector 容器中。最后遍历 vector 容器输出 Double 类型的数组。