C++链表 在forward_list首尾处添加元素

#include<iostream>
#include<forward_list>
using namespace std;
int main() {
	forward_list<int> a{ 1,2,3,4,5,6,7,8 };
	a.insert_after(a.before_begin(), 0);
	auto prec = a.before_begin();
	auto curr = a.begin();

	//遍历到最后一项,添加新元素在末尾
	while (1) {
		prec = curr;
		curr++;
		if (curr == a.end())
			break;
	}
	a.insert_after(prec, 9);
	for (auto it = a.begin(); it != a.end(); it++)
		cout << *it << endl;
}

输出:

0
1
2
3
4
5
6
7
8
9

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`forward_list`是C++ STL的一个单向链表容器。单向链表是一种数据结构,它具有一些优点,如在链表中添加或删除元素更加高效。在使用`forward_list`时,必须使用迭代器来访问元素,而不是像在`vector`或`array`中那样使用下标。以下是`forward_list`的一些基本操作: 1.创建`forward_list`: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f1; // 空的forward_list forward_list<int> f2(3); // 3个元素forward_list元素默认值为0 forward_list<int> f3(2, 1); // 2个元素forward_list元素默认值为1 forward_list<int> f4{ 1, 2, 3 }; // 3个元素forward_list,初始化列表为1、2、3 forward_list<int> f5(f4.begin(), f4.end()); // 从迭代器初始化forward_list return 0; } ``` 2.在`forward_list`中插入元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; f.push_front(0); // 在前面插入0 f.insert_after(f.begin(), 4); // 在第一个元素之后插入4 f.insert_after(f.begin(), 2, 5); // 在第一个元素之后插入两个5 f.insert_after(f.begin(), {6, 7, 8}); // 在第一个元素之后插入3个元素 return 0; } ``` 3.在`forward_list`中删除元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; f.pop_front(); // 删除第一个元素 f.erase_after(f.begin()); // 删除第二个元素 f.remove(3); // 删除所有等于3的元素 return 0; } ``` 4.在`forward_list`中查找元素: ```c++ #include <forward_list> #include <iostream> using namespace std; int main() { forward_list<int> f{ 1, 2, 3 }; auto it = find(f.begin(), f.end(), 3); if (it != f.end()) cout << "3 is in the forward_list." << endl; else cout << "3 is not in the forward_list." << endl; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值