使用std::find_if提取序列容器的子串
一个需求是这样的,一个vector容器中,我需要提取满足一定条件的元素的序列。就比如,一个树形结构,我把该接口拍扁成vector容器,每个节点都有一个惟一ID。
以下就是根据特定的ID查找节点下的子节点:
1 NodeList OrgTreeParser::findChildsById(const std::string &id) 2 { 3 NodeList list; 4 5 auto iter = std::find_if(std::begin(m_list), std::end(m_list), 6 [&](const OrgTreeNode & item) -> bool { 7 return item.parent_id.compare(id) == 0; 8 } 9 ); 10 while (iter != m_list.end()) 11 { 12 OrgTreeNode node; 13 node.id = iter->id; 14 node.parent_id = iter->parent_id; 15 node.level_id = iter->level_id; 16 node.name = iter->name; 17 node.addr = iter->addr; 18 node.description = iter->description; 19 list.push_back(node); 20 21 iter = std::find_if(std::next(iter), std::end(m_list), 22 [&](const OrgTreeNode & item) -> bool { 23 return item.parent_id.compare(id) == 0; 24 } 25 ); 26 } 27 28 return list; 29 }
references:
https://stackoverflow.com/questions/33226202/what-is-the-best-way-to-convert-a-stdfind-if-on-a-vector-to-a-loop