STL
程序员文章站
2022-03-23 11:36:07
...
STL,算法部分
// 测试数据
typedef struct _data
{
bool good;
int num;
QString desc;
_data(bool b = false, int n = 0, QString s = "") {
num = n;
good = b;
desc = s;
}
bool operator == (_data const &other){
return other.good == good && other.desc == desc && other.num == num;
}
friend QDebug operator << (QDebug os, _data const &other){
os << other.good << other.num << other.desc;
return os;
}
}Data;
class CountIf
{
public:
CountIf(bool b, int n)
:m_bFilter(b),m_iNum(n){}
bool operator()(Data const &other){
return ((other.good == m_bFilter)&&(other.num == m_iNum));
}
private:
bool m_bFilter;
int m_iNum;
};
std::vector<Data> vecs;
vecs.push_back(Data(true, 2, "B"));
vecs.push_back(Data(false, 1, "C"));
vecs.push_back(Data(false, 1, "A"));
vecs.push_back(Data(true, 1, "B"));
vecs.push_back(Data(false, 2, "A"));
vecs.push_back(Data(false, 1, "B"));
vecs.push_back(Data(true, 1, "A"));
// count_if
int ret = 0;
ret = std::count_if(vecs.begin(), vecs.end(), [](Data const &other){
return other.good == true; // 3
});
qDebug() << "ves is good , ret = " << ret;
CountIf filiter(false, 2);
ret = std::count_if(vecs.begin(), vecs.end(), filiter);
qDebug() << "vec good && num = 1, ret = " << ret;
// find
auto it = std::find(vecs.begin(), vecs.end(), Data(true, 1, "B"));
if(it!= vecs.end()){
auto one = *it;
qDebug() << "find" << one;
}
it = std::find_if(vecs.begin(), vecs.end(), [](Data const &other){
return other.desc == "A";
});
if(it!= vecs.end()){
auto one = *it;
qDebug() << "find" << one;
}
//sort 排序(快速排序)
std::sort(vecs.begin(), vecs.end(), [](Data const &left, Data const &right){
return left.desc < right.desc;
});
for(auto &one : vecs){
qDebug() << one;
}
//stable_sort 稳定排序
/*
std::stable_sort(vecs.begin(), vecs.end(), [](Data const &left, Data const &right){
return left.desc < right.desc;
});
for(auto &one : vecs){
qDebug() << one;
}
*/
排序中,快排,对于原来相等的元素不保持原有序列,而稳定排序可以为此解决,
addafter。
上一篇: 拥挤都市 中人物状态机