list基础用法
- 1.list的访问就不能用下标+[]了,用迭代器
- 2.emplace_back()几乎是与push_back()用法一致,但也有差别
- 3.insert(),erase()的用法
- 4.reverse()
- 5.排序
- 6.合并
- 7.unique()(去重)
- 8.splice剪切再粘贴
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
}