在std :: list中找到所有匹配的元素 [英] Find all matching elements in std::list

查看:1406
本文介绍了在std :: list中找到所有匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何内置或完善的方式(即通过lambda)来遍历std :: list的元素并查找与给定值匹配的所有元素?我知道我可以遍历所有这些对象,但是我想问一问是否有办法让迭代器仅对符合给定条件的元素进行迭代?下面的示例仅向我提供了第一个匹配元素的迭代器.

I was wondering if there's any built-in or well-established way (i.e. via lambda) to go through the elements of an std::list and find all the ones that match a given value? I know I can iterate through all of them, but I thought I'd ask if there's a way to get an iterator that iterates through just the elements that match a given criteria? My sample below only gives me the iterator to the first matching element.

#include <list>
#include <algorithm>
#include <stdio.h>

int main()
{
    std::list<int> List;
    List.push_back(100);
    List.push_back(200);
    List.push_back(300);
    List.push_back(100);
    int findValue = 100;

    auto it = std::find_if(List.begin(), List.end(), [findValue](const int value)
    {
        return (value == findValue);
    });

    if (it != List.end())
    {
        for (; it != List.end(); ++it)
        {
            printf("%d\n", * it);
        }
    }
    return 0;
}

谢谢您的反馈.

推荐答案

std::find_ifstd::find的泛化,用于当您需要一个函数来检查所需的元素时,而不是简单的相等性测试.如果只想对相等性做一个简单的测试,则不需要通用形式,而lambda只会增加复杂性和冗长性.只需使用std::find(begin, end, findValue)代替:

std::find_if is a generalisation of std::find for when you need a function to check for the elements you want, rather than a simple test for equality. If you just want to do a simple test for equality then there's no need for the generalised form, and the lambda just adds complexity and verbosity. Just use std::find(begin, end, findValue) instead:

std::vector<std::list<int>::const_iterator> matches;
auto i = list.begin(), end = list.end();
while (i != end)
{
  i = std::find(i, end, findValue);
  if (i != end)
    matches.push_back(i++);
}

但是,与其在循环中调用find,不如说是手动编写循环:

But rather than calling find in a loop I'd just write the loop manually:

std::vector<std::list<int>::const_iterator> matches;
for (auto i = list.begin(), toofar = l.end(); i != toofar; ++i)
  if (*i == findValue)
    matches.push_back(i);

这篇关于在std :: list中找到所有匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆