Vyacheslav
Vyacheslav

Reputation: 113

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"?

Upvotes: 3

Views: 1372

Answers (3)

Julien Lopez
Julien Lopez

Reputation: 1021

if your list is sorted, I guess you can use std::lower_bound and std::upper_bound

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227508

Just use std::find, from the <algorithm> header:

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".

Upvotes: 4

taocp
taocp

Reputation: 23654

Firstly, don't use variable name list, try intList instead.

You may use std::find

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

Per std::find documentation:

std::find
Return value
Iterator to the first element satisfying the condition or last if no such element is found.

Upvotes: 9

Related Questions