简体   繁体   English

返回子列表c ++的迭代器

[英]Return iterator of a sublist c++

We have a list 我们有一个清单

std::list<int> list;

// fill part of the list with 5
list.push_back(5);
list.push_back(5);
list.push_back(5);

// fill part of the list with 10
list.push_back(10);
list.push_back(10);
list.push_back(10);

// iterator that starts with 5
std::list<int>::iterator iterFiveBegin = list.begin();


//
std::list<int>::iterator iterEnd = list.end();

How can I get the iterator std::list<int>::iterator iterTenBegin of the list where it starts with "10"? 如何获取std::list<int>::iterator iterTenBegin的iterator std::list<int>::iterator iterTenBegin以“10”开头?

Firstly, don't use variable name list , try intList instead. 首先,不要使用变量名list ,而是尝试使用intList

You may use std::find 你可以使用std::find

std::list<int>::iterator it = std::find (intList.begin(), intList.end(), 10);

Per std::find documentation : Per std::find文档

std::find 的std ::发现
Return value 返回值
Iterator to the first element satisfying the condition or last if no such element is found. Iterator到满足条件的第一个元素,如果没有找到这样的元素则为last。

Just use std::find , from the <algorithm> header: 只需使用<algorithm>标头中的std :: find

std::list<int>::const_iterator ten = std::find(list.begin(), list.end(), 10);

Make sure to check that it is valid: 确保检查它是否有效:

if (ten == list.end())
{
  // no 10 found in list
}

Also, don't name your std::list instance "list". 另外,不要将std::list实例命名为“list”。

如果您的列表已排序,我想您可以使用std :: lower_bound和std :: upper_bound

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM