【问题标题】:C++ function that returns an iterator to first record with the given value [duplicate]C ++函数返回迭代器以使用给定值的第一条记录[重复]
【发布时间】:2017-10-15 16:20:58
【问题描述】:

我正在尝试创建一个简单的函数,它返回一个迭代器以使用给定值记录第一个记录。

【问题讨论】:

标签: c++ c++11 lambda listiterator const-iterator


【解决方案1】:

试试下面的

std::list<records>::const_iterator findrecords(const std::list<records>& registry, 
                                               const std::string& student_id) 
{
    return std::find_if(registry.begin(),
                        registry.end(), 
                        [&]( const records &r ) { return r.student_id == student_id; } );
}

这是一个演示程序

#include <iostream>
#include <list>
#include <string>
#include <algorithm>

struct records
{
    std::string student_id;
};    

std::list<records>::const_iterator findrecords(const std::list<records>& registry,
    const std::string& student_id)
{
    return std::find_if(registry.begin(),
        registry.end(),
        [&](const records &r) { return r.student_id == student_id; });
}

int main()
{
    std::list<records> registry = { { "A" }, { "B" }, { "C" } };

    std::string student_id( "B" );

    auto it = findrecords(registry, student_id);

    if (it != registry.end())
    {
        std::cout << it->student_id << std::endl;
    }

    return 0;
}

它的输出是

B

【讨论】:

  • 错误 C2064 术语不计算为采用 1 个参数的函数记录 c:\visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\list 1556
  • @JasonW 试试演示程序。考虑到我自己定义了班级记录。它可能与您的班级不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2013-03-28
相关资源
最近更新 更多