C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?

C++ STD functional operators: is there a method to map one vector onto another vector through a function?

本文关键字:向量 函数 一个 映射 另一个 一种 运算符 STD 有没有 方法 C++      更新时间:2023-10-16

>假设我有两个向量,我想通过标准过程vector<string>从向量 1 创建向量 2,vector<double>向量 1

// pseudo code
std::map_onto(v1.begin(),v1.end(),v2.begin(),v2.end(),[](string x) -> double {return stod(x);});

有没有办法在C++做到这一点?

你总是可以简单地编写一些代码:

for (auto x : v1) {
v2.push_back(std::stod(x));
}

或者,如果v2已经存在并且您希望覆盖它:

for (size_t i = 0; i < v1.size(); ++i) {
v2[i] = std::stod(v1[i]);
}

或者你可以使用 std::transform:

std::transform(std::begin(v1), std::end(v1), std::begin(v2), 
[](const std::string& s) -> double { return std::stod(s); });