如何从现有的 std::list 取前 n-5 个元素创建新的 std::list ?
n 是现有列表(列表)的大小

最佳答案

std::list<T> newlist(oldlist.begin(), std::prev(oldlist.end(), 5));

其中 T 是旧列表的值类型。
std::prev 在 C++11 中是新的,但如果你没有它,你可以使用 std::advance 代替:
std::list<T>::const_iterator end = oldlist.end();
std::advance(end, -5);
std::list<T> newlist(oldlist.begin(), end);

无论哪种方式,您都有责任确保 oldlist.size() >= 5std::prevstd::advance 都不适合你。

关于c++ - 如何从采用前 n-5 个元素的现有列表创建新列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14735927/

10-11 22:49
查看更多