有一些数据
struct Data {
std::size_t some_other_data = 0;
std::size_t id = 0;
};
存储在 std::vector 中我想通过元素
id
创建元素索引并将其附加到更大的索引文件中。
如果我想用
std
算法来实现这个,我应该遵循哪种方式?
这是用“普通”C++ 编写的代码:
#include <cstddef>
#include <vector>
struct Data {
std::size_t some_other_data = 0;
std::size_t id = 0;
};
int main()
{
std::vector<std::size_t> collected_indexes;
std::vector<Data> dict = { { 2, 2 }, { 0, 0 }, { 1, 1 } };
std::vector<std::size_t> index(dict.size());
// The code I want to rewrite shorter with std
for (std::size_t i = 0; i < index.size(); ++i) {
index[dict[i].id] = i;
}
collected_indexes.append_range(index);
// End of code
}
如果所提出的解决方案可以与 execution_policies 一起使用以使其并行,那就太好了。
此处使用标准算法。
std::vector<std::size_t> collected_indexes;
std::vector<Data> dict = { { 2, 2 }, { 0, 0 }, { 1, 1 } };
// Use std::ranges::transform to generate index and append it to collected_indexes
std::ranges::transform(dict, std::back_inserter(collected_indexes), [](const Data& d) { return d.id; });