获取基于字符串的结构元素的向量值
Get value of vector of struct element based on string
我有一个结构体定义如下
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';
}
}
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?