简体   繁体   中英

Reaching nth element of a std::list in C++

I need to reach nth element of a list somehow. I tried the code below but it didn't work. Is there a way to get the content of nth element of a list? I can't use vectors or queues, I only can use lists. Here is my attempt :

#include <list>
#include <iostream>
#include <iterator> 

using namespace std;

int main()
{
    int x = 5;
    list <int> mylist;
    list<int>::iterator it;
    for (int i=0; i<10; i++) 
    mylist.push_back (i);

    it = mylist.begin();

    for(int i = 0 ; i < 10; i++)
    {
        if(it == x)
        {
        cout<<"x found"<<endl;
        break;
        }
        advance(it,1);


    }
}

Here, it is of iterator type (iterator to given list element), you need to further de-reference to get its value.

Change

if (it == x)

to

if (*it == x)
    ^^^

The function std::advance() can be used for this as follows:

it = mylist.begin();
std::advance(it, x);

To get the n th element, you can use std::advance :

std::list<int>::iterator it = myList.begin();
std::advance( it, n );

Just be sure that there are enough elements. If you have C++11, you can use:

std::list<int>::iterator it = std::next( myList.begin(), n );

directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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