list基础用法

list基础用法

1.list的访问就不能用下标+[]了,用迭代器

cpp 复制代码
void test1()
{
	list<int>lt;//list要带头文件,同理,vector,string也是
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);

	//list的访问就不能用下标+[]了
	//用迭代器
	list<int>::iterator it = lt.begin();
	while (it != lt.end())
	{
		cout << *it;
		it++;
	}
	cout << endl;

	for (auto e : lt)
	{
		cout << e;
	} 
	cout << endl;

}

2.emplace_back()几乎是与push_back()用法一致,但也有差别

cpp 复制代码
void test2()
{
	list<A>lt;
	A a1(1, 2);
	lt.push_back(a1);//又名
	lt.push_back(A(1, 1));//匿名
	lt.emplace_back(a1);
	lt.emplace_back(A(1, 1));

	//差别:
	//push_back()只能传一个参数,emplace_back()支持直接传构造A的对象参数
	lt.emplace_back(3, 4);


}

3.insert(),erase()的用法

cpp 复制代码
void test_list3()
{
	list<int> lt;
	lt.push_back(1);
	lt.push_back(2);
	lt.push_back(3);
	lt.push_back(4);
	lt.push_back(5);
	lt.push_back(6);

	//insert()
	auto it = lt.begin();
	int k = 3;
	while (k--)
	{
		++it;
	}

	lt.insert(it, 30);

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;

	//erase()
	int x = 0;
	cin >> x;
	it = find(lt.begin(), lt.end(), x);
	if (it != lt.end())
	{
		lt.erase(it);
	}

	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}

4.reverse()

cpp 复制代码
     lt.reverse();//or
	reverse(lt.begin(), lt.end());

5.排序

cpp 复制代码
    // 升序
	lt.sort();
	//or
	less<int> ls;
    lt.sort(ls);
    //降序
     greater<int> gt;
	 lt.sort(ls);
	 //or
	 lt.sort(greater<int>());

	

关于链表排序:链表排序效率非常的低。

6.合并

cpp 复制代码
std::list<double> first, second;

	first.push_back(3.1);
	first.push_back(2.2);
	first.push_back(2.9);

	second.push_back(3.7);
	second.push_back(7.1);
	second.push_back(1.4);

	first.sort();
	second.sort();

	first.merge(second);//second就为空了

7.unique()(去重)

前提:必须保证有序

cpp 复制代码
void test5()
{
	list<int> lt;
	lt.push_back(1);
	lt.push_back(20);
	lt.push_back(3);
	lt.push_back(5);
	lt.push_back(5);
	lt.push_back(4);
	lt.push_back(5);
	lt.push_back(6);

	lt.sort();
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;

	lt.unique();
	for (auto e : lt)
	{
		cout << e << " ";
	}
	cout << endl;
}

8.splice剪切再粘贴

cpp 复制代码
void test6()
{
	// 一个链表节点转移给另一个链表
	std::list<int> mylist1, mylist2;
	std::list<int>::iterator it;

	// set some initial values:
	for (int i = 1; i <= 4; ++i)
		mylist1.push_back(i);      // mylist1: 1 2 3 4

	for (int i = 1; i <= 3; ++i)
		mylist2.push_back(i * 10);   // mylist2: 10 20 30

	it = mylist1.begin();
	++it;                         // points to 2

	mylist1.splice(it, mylist2); // mylist1: 1 10 20 30 2 3 4
								  // mylist2 (empty)
								  // "it" still points to 2 (the 5th element
}
相关推荐
naturerun43 分钟前
从数组中删除元素的算法
数据结构·c++·算法
Andy1 小时前
C++ list容器基本逻辑结构详解
c++·windows·list
酿情师4 小时前
区块链原理与技术02:区块链的数据结构04(区块结构)
数据结构·区块链
夏日听雨眠4 小时前
数据结构(循环队列)
数据结构·算法·链表
平行侠4 小时前
30MacLaren-Marsaglia算法故事文件
数据结构·算法
平行侠6 小时前
33水库抽样 - 从未知大小的流中等概率采样
数据结构·算法
Controller-Inversion6 小时前
42. 接雨水
数据结构·算法·leetcode
Controller-Inversion6 小时前
33. 搜索旋转排序数组
数据结构·算法·leetcode
宵时待雨6 小时前
优选算法专题6:模拟
数据结构·c++·算法·leetcode·职场和发展