我有一个结构定义如下
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/