#include #include

using namespace std;

void display(list &L) { for(list::iterator it=L.begin(); it!=L.end(); it++) cout << *it << " "; cout << endl; }

bool mycompare(int a,int b) { return a>b; //左边大于右边为真,是从大到小排序 }

int main() { list L;

for(int i=1;i<5;i++)
	L.push_back(i*10); //尾部添加元素

display(L);

for(int i=9;i>=5;i--)
	L.push_front(i*10); //头部添加元素

display(L);

L.pop_back(); //尾部删除元素
display(L);

L.pop_front(); //头部删除元素
display(L);

cout << "=========" << endl;
list<int>::iterator it = L.begin();
it++;
it++;

L.insert(it,20);//20插入到迭代器it的前一个位置
display(L);

cout << "容器中元素个数:" << L.size() << endl;

L.erase(it);//删除迭代器指向的元素
			//参数是迭代器
display(L);

L.remove(20);//删除链表中所有值为20的元素
display(L);

L.reverse();//链表逆序
display(L);

L.sort();//默认从小到大排序
display(L);

L.sort(mycompare);
display(L);


L.clear();
if( L.empty() )
	cout << "容器为空" << endl;
else
	cout << "容器不为空" << endl;

cout << L.size() << endl;

}

mycompare 函数调用方法:

在代码中,mycompare 函数是作为参数传递给 list 的 sort 函数的。sort 函数会根据 mycompare 函数的返回值来确定元素的排序顺序。

具体调用过程如下:

  1. 首先,在 main 函数中调用 L.sort() 函数,默认从小到大排序。

  2. 在 sort 函数内部,会根据传入的比较函数来进行排序,即根据 mycompare 函数的返回值。如果 mycompare 函数返回 true,表示左边的元素大于右边的元素,需要交换位置,否则不交换位置。

  3. sort 函数会遍历链表中的每个元素,并调用 mycompare 函数来比较元素的大小,并根据比较结果进行排序。

  4. 最终,链表中的元素会按照 mycompare 函数的规则进行排序。在代码中,mycompare 函数返回 a>b,表示从大到小排序,所以最终链表中的元素会按照从大到小的顺序排列。

C++ STL list 容器详解:常用操作及排序方法

原文地址: https://www.cveoy.top/t/topic/pcCu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录