获取基于字符串的结构元素的向量值

Get value of vector of struct element based on string

本文关键字:元素 向量 结构 获取 字符串      更新时间:2023-10-16

我有一个结构体定义如下

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

和结构体a_t上的向量,定义如下:

std::vector<a_t> aList

aList的内容如下:

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

给定字符串one,我应该通过aList搜索以找到该特定元素的描述。在本例中,我必须得到Device 1作为输出。

我该怎么做呢?

可以使用<algorithm>std::find_if

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;

试试这个:

for(std::vector<a_t>::iterator it = aList.begin(); it != aList.end(); ++it) {
    if ((*it).ID.find("one") != std::string::npos) {
        std::cout << (*it).Description<< 'n';
    }
}