gpt4 book ai didi

c++ - 在 C++ 中到达 std::list 的第 n 个元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:19 25 4
gpt4 key购买 nike

我需要以某种方式到达列表的第 n 个元素。我尝试了下面的代码,但没有用。有没有办法获取列表的第 n 个元素的内容?我不能使用 vector 或队列,我只能使用列表。这是我的尝试:

#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);


}
}

最佳答案

函数std::advance()可用于此目的如下:

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

关于c++ - 在 C++ 中到达 std::list 的第 n 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23569451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com