C++ STL list 容器:详解常用操作及回调函数
这串代码中 mycompare 如何调用的,是回调函数吗
在这段代码中,'mycompare' 函数被作为参数传递给 'L.sort()' 函数来进行排序。'sort()' 函数会根据 'mycompare' 函数的返回值来确定元素的顺序。'mycompare' 函数被称为回调函数,因为它由用户定义并作为参数传递给另一个函数,由另一个函数在特定情况下调用。在这里,'mycompare' 函数被 'L.sort()' 函数在排序时调用。
代码解释:
#include <list>
#include <iostream>
using namespace std;
void display(list<int> &L)
{
for(list<int>::iterator it=L.begin(); it!=L.end(); it++)
cout << *it << " ";
cout << endl;
}
bool mycompare(int a,int b)
{
return a>b; //左边大于右边为真,是从大到小排序
}
int main()
{
list<int> 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;
}
回调函数的作用:
在 C++ 中,回调函数通常用于提供自定义行为,例如在排序算法中定义比较规则。'sort()' 函数本身不知道如何比较两个元素,它需要一个外部函数来告诉它如何进行比较。'mycompare' 函数正是承担了这个角色,它根据用户的需要定义比较规则,并在 'sort()' 函数内部被调用。
总结:
'mycompare' 函数是一个回调函数,它被用作 'L.sort()' 函数的比较函数,以实现自定义排序功能。通过将回调函数作为参数传递给其他函数,可以扩展函数的功能并实现灵活的代码设计。
原文地址: https://www.cveoy.top/t/topic/pcCP 著作权归作者所有。请勿转载和采集!