c++ - 是否可以使用迭代器创建成员字段的值列表?

标签 c++ algorithm data-structures iterator c++-standard-library

考虑以下结构

struct Pair 
{
   int a;
   std::string b;
};

我有一个 std::vector<Pair> pairs但我想要一个 std::vector<std::string> listOfBFromPairs其中包含对列表中 b 的所有值。

我想在一行中完成此操作。

我以前用过OpenGL,我之前创建了一个结构体,指定了一个起点

pairs.begin() + offsetof(Pair, b)

并给定一个步长(内存中 pair 对象的大小)和我想要解析的东西的数量,它已经完成了我在这里的任务。

这里也可以使用 C++ 迭代器吗?

我的具体用例是我想创建一个 Vulkan 扩展名称的无序集,但 Vulkan 返回包含扩展名称作为成员的结构。然后,我将使用无序集来检查我的应用程序想要使用的扩展。

最佳答案

I want a std::vector<std::string> listOfBFromPairs which contains all the values of b from the list of pairs.

I would like to do this in a one-liner?

当然可以。您可以使用 std::transform 来自 <algorithm> 像这样的标题

#include <algorithm> // std::transform
#include <iterator>  // std::back_inserter

std::vector<Pair> pairs;
std::vector<std::string> listOfBFromPairs;
listOfBFromPairs.reserve(pairs.size()); // reserve the memory for unwanted reallocations

std::transform(pairs.begin(), pairs.end(),
   std::back_inserter(listOfBFromPairs), [](const Pair& pair) { return pair.b; }
);

但是如果您需要 listOfBFromPairs没有重复使用 unordered_set , 你需要创建一个 std::unordered_set<std::string> listOfBFromPairs;不是字符串 vector 。在这种情况下,您需要使用 std::inserter 将字符串插入到 unordered_set 中。 .

#include <unordered_set>
#include <algorithm> // std::transform
#include <iterator>  // std::inserter

std::vector<Pair> pairs;
std::unordered_set<std::string> listOfBFromPairs;

std::transform(pairs.begin(), pairs.end(),
   std::inserter(listOfBFromPairs, listOfBFromPairs.end()), [](const auto& pair) { return pair.b; }
);

关于c++ - 是否可以使用迭代器创建成员字段的值列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63425296/

相关文章:

string - 两个词有多相似

java - 链表中的节点可以有动态数组吗?

c - 使用中序遍历删除二叉树

c - 在数组 : Segmentation fault (core dumped) 中插入一个元素

C++ 意外标识符

c++ - 上交所注册管理

c++ - 哪些工具可以报告此类未初始化变量的使用情况?

c++ - 如何在C++中调用cmath库中的特殊函数?

python - 从列表列表中生成所有可能的组合

arrays - 获取最长连续的 1 序列