Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine corresponding items from several vectors into a single vector of structs?

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.

like image 355
RocketSearcher Avatar asked Nov 17 '25 22:11

RocketSearcher


1 Answers

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>();
like image 137
康桓瑋 Avatar answered Nov 20 '25 13:11

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!