快排
#include
#include
using namespace std;
int partition(vector& arr, int left, int right){
int pivot = arr[left];
int j = left;
for (int i = left + 1; i <= right; i++) { //保留第一个pivot位置不变,往后面遍历,遇到一个小于pivot的就交换
if (arr[i] < pivot) {
int temp = arr[i];
arr[i] = arr[j + 1];
arr[j + 1] = temp;
j++;
}
}
arr[left] = arr[j];
arr[j] = pivot;
return j;
}
void quicksort(vector& arr, int left, int right) {
if (left < right) { //这里是递归的终止条件。
int mid = partition(arr, left, right);
quicksort(arr, left, mid - 1);
quicksort(arr, mid + 1, right);
}
}
int main() {
vector arr = { 1, 2, 5, 7, 3, 5, 9 };
quicksort(arr, 0, arr.size() - 1);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << endl;
}
return 0;
}
topk
#include
#include
#include
using namespace std;
//topk最大的k个用小顶堆,greater函数。或者自定义类 bool operator()(const........)
//topk最小的k个用大顶堆,默认即可。或者less,或者自定义
void topfrequent(vector& arr, int k) {
unordered_map map;
for (auto i : arr) {
map[i]++;
}
priority_queue, vector>, greater>> heap;
int num = 0;
for (auto i : map) {
heap.push({ i.second, i.first });
num++;
if (num > k) {
heap.pop();
}
}
for (int i = 0; i < k; i++) {
cout << heap.top().second << endl;
heap.pop();
}
}
int main() {
vector arr = { 1,1,1,2,2,3 };
topfrequent(arr, 2);
return 0;
}
NMS
#include
#include
#include
using namespace std;
struct BoundingBox {
float x1, y1, x2, y2;
float confidence;
};
//bool cmp(const BoundingBox& a1, const BoundingBox& a2) {
// return a1.confidence > a2.confidence;
//}
class MyCompare {
public:
bool operator() (const BoundingBox& a1, const BoundingBox& a2) {
return a1.confidence > a2.confidence;
}
};
float calculate_iou(const BoundingBox& box1, const BoundingBox& box2) {
float heigh = max(0.f, min(box1.y2, box2.y2) - max(box1.y1, box2.y1));
float width = max(0.f, min(box1.x2, box2.x2) - max(box1.x1, box2.x1));
float iou = (heigh * width) / ((box1.x2 - box1.x1) * (box1.y2 - box1.y1) + (box2.x2 - box2.x1) * (box2.y2 - box2.y1) - heigh * width);
return iou;
}
vector NMS(vector& boxes, float score_threshold) {
sort(boxes.begin(), boxes.end(), MyCompare());
vector result;
for (auto& box : boxes) {
bool keep = true;
for (auto& keep_box : result) {
float iou = calculate_iou(keep_box, box);
if (iou > score_threshold) {
keep = false;
break;
}
}
if (keep) {
result.push_back(box);
}
}
return result;
}
int main() {
std::vector detections = {
{10, 10, 50, 50, 0.9}, // 框1:左上角(10, 10),右下角(50, 50),置信度0.9
{20, 20, 60, 60, 0.85} // 框2:左上角(20, 20),右下角(60, 60),置信度0.85
};
float iouThreshold = 0.1;
std::vector filteredBoxes = NMS(detections, iouThreshold);
// 预期输出:只保留置信度更高的框1
// 输出结果的顺序可能会有所不同
for (const auto& box : filteredBoxes) {
std::cout << "Left: " << box.x1 << ", Top: " << box.y1 << ", Right: " << box.x2 << ", Bottom: "
<< box.y2 << ", Confidence: " << box.confidence << std::endl;
}
}