std::forward_list 是 C++11 中引入的一个单向链表容器,它可以在常数时间内插入和删除元素,但不能随机访问元素。std::forward_list 的用法与其他 STL 容器类似,可以使用迭代器来遍历和操作容器中的元素。
push_front:在链表的头部插入一个元素。pop_front:删除链表的头部元素。insert_after:在指定位置之后插入一个元素。erase_after:删除指定位置之后的元素。remove:删除链表中所有等于指定值的元素。reverse:反转链表中的元素顺序。sort:对链表中的元素进行排序。
以下是一个使用 std::forward_list 的示例代码:
#include <iostream>
#include <forward_list>
int main() {
std::forward_list<int> flist = {1, 2, 3, 4, 5};
// 在头部插入一个元素
flist.push_front(0);
// 删除头部元素
flist.pop_front();
// 在第二个位置之后插入一个元素
auto it = flist.begin();
std::advance(it, 1);
flist.insert_after(it, 6);
// 删除第三个位置之后的元素
auto it2 = flist.begin();
std::advance(it2, 2);
flist.erase_after(it2);
// 删除所有等于 4 的元素
flist.remove(4);
// 反转链表中的元素顺序
flist.reverse();
// 对链表中的元素进行排序
flist.sort();
// 遍历链表中的元素并输出
for (auto n : flist) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
这里注意一下advance的用法:
std::advance 是 C++ STL 中的一个算法函数,它可以将迭代器向前或向后移动指定的距离。std::advance 的用法非常简单,它接受两个参数:一个迭代器和一个整数值,表示要移动的距离。
以下是 std::advance 的函数原型:
template<class InputIt, class Distance>
void advance(InputIt& it, Distance n);
其中,InputIt 表示迭代器类型,Distance 表示距离类型。it 表示要移动的迭代器,n 表示要移动的距离。
std::advance 的作用是将迭代器 it 向前或向后移动 n 个位置。如果 n 是正数,那么迭代器将向前移动 n 个位置;如果 n 是负数,那么迭代器将向后移动 n 个位置。如果 n 的绝对值大于迭代器中剩余的元素个数,那么行为是未定义的。
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
// 将迭代器向前移动两个位置
auto it = v.begin();
std::advance(it, 2);
// 输出移动后的迭代器指向的元素
std::cout << *it << std::endl;
// 将迭代器向后移动一个位置
std::advance(it, -1);
// 输出移动后的迭代器指向的元素
std::cout << *it << std::endl;
return 0;
}
总之,std::advance 是一个非常实用的算法函数,它可以帮助我们在迭代器中快速移动指定的距离,非常适合于需要在迭代器中进行随机访问的场景。但是,由于它可能会导致迭代器越界,因此在使用时需要格外小心,避免出现不必要的错误。
No comments yet.