I have three std::vectors,
std::vector<std::string> vec1{ "one", "two", "three" };
std::vector<std::string> vec2{ "1", "2", "3" };
std::vector<std::string> vec3{ "i", "ii", "iii" };
and a struct,
struct MyData {
std::string str1;
std::string str2;
std::string str3;
};
I need to obtain a std::vector<MyData>, which is filled from the data of the three vectors:
std::vector<MyData> myData;
myData.reserve(vec1.size());
for (int i = 0; i < vec1.size(); ++i) {
myData.emplace_back(vec1[i], vec2[i], vec3[i]);
}
Is there a more elegant way instead of using this for loop (like using views or similar) for C++20? It is guaranteed that the three vectors are of the same length.
You can use views::zip_transform (C++23) like:
auto to_MyData = [](auto... elems) { return MyData(elems...); };
auto myData = std::views::zip_transform(to_MyData, vec1, vec2, vec3)
| std::ranges::to<std::vector>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With