c++ - 根据字符串获取结构元素 vector 的值

标签 c++ vector struct

我有一个结构定义如下

struct a_t
{
    std::string ID;
    std::string Description;
};

结构a_t 上的 vector 定义如下:

std::vector<a_t> aList

aList的内容如下:

ID    Description
=================
one_1  Device 1
two_2  Device 2
three_3 Device 3
....

给定一个字符串 one,我应该搜索 aList 以找到该特定元素的描述。在这种情况下,我必须将 Device 1 作为输出。

我应该怎么做?

最佳答案

您可以使用 std::find_if<algorithm>

a_t item;
auto pred = [](const a_t & item) {
    int p = -1;
    p= item.ID.find("one");
    return p >= 0;
};
std::vector<a_t>::iterator pos=std::find_if(std::begin(aList), std::end(aList), pred);
std::cout <<"\nResult:" <<pos->Description;

关于c++ - 根据字符串获取结构元素 vector 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39032232/

相关文章:

c++ - 如何从 vector 中提取n个样本?

c++ - 删除 vector 中的元素需要永远完成

c++ - 线程间同一个socket的recv/send/close代码需要加锁吗

c++ - C++ 中的 RTTI 和虚函数。 gcc的实现方式是必须的吗?

c++ - OpenCV标志识别

c - 结构体的初始化

html - 如何将 html 数据移动到 Golang 中的结构

C++ 向后正则表达式搜索

c++ - 如何定义一个包含可变维度 vector 的类以及如何使用这个类?

c - 通过指针访问结构成员