如何从std :: list中获取特定元素?

时间:2018-01-19 16:52:28

标签: c++ list

我已经使用Java很长时间了,决定改用C ++。我已经列出了这样一个列表:

std::list <Player*> players;

我想做的就是从这个列表中获取一个特定的元素。我记得在Java中调用了一个&#34; .get(index)&#34;方法,但我无法在C ++中找到类似的东西。 谁能帮我? 谢谢。

1 个答案:

答案 0 :(得分:5)

std::list类不提供随机访问。你可以把它想象成一个链表。

对于随机访问,请改用std::vectorstd::deque。然后,您可以阅读players[index]

如果您致力于std::list,那么您可以通过将迭代器推进到您需要的位置来获得线性时间随机访问。例如:

std::list<Player*>::const_iterator it = players.begin();
std::advance(it, index);

现在*it指的是您想要的元素。如果您使用的是C ++ 11或更高版本,则可以将上述内容缩短为单个语句:

auto it = std::next(players.begin(), index);