一个100*100的二维数组,数组中有0-100的随机数字,找到该二维数组中所有的峰值,峰值的定义为大于其周围的数字,用VS+QT实现
时间: 2024-03-28 22:42:05 浏览: 74
以下是用C++语言、VS和QT实现寻找二维数组中所有峰值的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
QT_CHARTS_USE_NAMESPACE
using namespace std;
// 定义峰值点的结构体
struct PeakPoint {
int row; // 峰值点所在的行
int col; // 峰值点所在的列
int val; // 峰值点的值
};
vector<PeakPoint> findPeakPoints(int** arr, int rows, int cols) {
vector<PeakPoint> peakPoints;
for (int i = 1; i < rows - 1; i++) {
for (int j = 1; j < cols - 1; j++) {
int val = arr[i][j];
if (val > arr[i - 1][j] && val > arr[i + 1][j] && val > arr[i][j - 1] && val > arr[i][j + 1]) {
// 找到一个峰值点
PeakPoint peakPoint = { i, j, val };
peakPoints.push_back(peakPoint);
}
}
}
return peakPoints;
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
// 初始化二维数组
int rows = 100;
int cols = 100;
int** arr = new int*[rows];
for (int i = 0; i < rows; i++) {
arr[i] = new int[cols];
for (int j = 0; j < cols; j++) {
arr[i][j] = rand() % 101; // 生成0-100的随机数
}
}
// 找到所有峰值点
vector<PeakPoint> peakPoints = findPeakPoints(arr, rows, cols);
// 输出峰值点的信息
for (auto peakPoint : peakPoints) {
cout << "Peak point: row = " << peakPoint.row << ", col = " << peakPoint.col << ", val = " << peakPoint.val << endl;
}
// 可视化显示二维数组和峰值点
QMainWindow window;
QLineSeries* series = new QLineSeries();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
series->append(j, arr[i][j]);
}
}
QChart* chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
for (auto peakPoint : peakPoints) {
QLineSeries* peakSeries = new QLineSeries();
peakSeries->append(peakPoint.col, peakPoint.val);
chart->addSeries(peakSeries);
}
QChartView* chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
window.setCentralWidget(chartView);
window.resize(800, 600);
window.show();
return a.exec();
}
```
该程序首先初始化一个100*100的二维数组,并生成0-100的随机数填充到数组中。然后调用`findPeakPoints`函数寻找所有的峰值点,并输出它们的信息。最后使用QT库可视化显示二维数组和峰值点。
可以通过Visual Studio将该程序编译为可执行文件,也可以使用QT Creator将该程序编译为可执行文件。需要注意的是,QT库需要额外安装,并在项目配置中添加相应的库和头文件路径。
阅读全文