自定义结构体的qlist 找到其中的一个最小值
时间: 2023-06-24 14:03:59 浏览: 127
可以使用 `std::min_element` 和自定义比较函数来找到自定义结构体的 qlist 中的最小值。
假设自定义结构体为 `MyStruct`,其中包含一个整型成员变量 `value`,可以按照以下步骤实现:
1. 创建一个自定义比较函数,比较函数需要接受两个 `MyStruct` 类型的参数,并返回一个布尔值。比较函数应该返回第一个参数是否小于第二个参数。
```cpp
bool compareMyStruct(const MyStruct &a, const MyStruct &b) {
return a.value < b.value;
}
```
2. 使用 `std::min_element` 函数在 `qlist` 容器中查找最小值,该函数接收三个参数:开始迭代器,结束迭代器和自定义比较函数。
```cpp
auto minElement = std::min_element(qList.begin(), qList.end(), compareMyStruct);
```
3. 检查 `minElement` 是否等于 `qList.end()`,如果是,则表示 `qList` 是一个空容器,否则,`minElement` 就是 `qList` 中的最小元素。
```cpp
if (minElement != qList.end()) {
qDebug() << "The minimum value in qList is: " << minElement->value;
} else {
qDebug() << "qList is empty!";
}
```
完整的示例代码如下:
```cpp
#include <QCoreApplication>
#include <QDebug>
#include <algorithm>
struct MyStruct {
int value;
};
bool compareMyStruct(const MyStruct &a, const MyStruct &b) {
return a.value < b.value;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<MyStruct> qList = {{1}, {3}, {2}, {5}, {4}};
auto minElement = std::min_element(qList.begin(), qList.end(), compareMyStruct);
if (minElement != qList.end()) {
qDebug() << "The minimum value in qList is: " << minElement->value;
} else {
qDebug() << "qList is empty!";
}
return a.exec();
}
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)