我有一组vector<pair<int,int>> 其中前面的是索引,后面的是数值,数值分布在1-21,我想将其分为4类,每一类的最小数值和最大数值的差值不超过2,请为我生成代码
时间: 2024-04-12 07:31:50 浏览: 22
好的,以下是一个示例代码来将给定的 vector<pair<int, int>> 分为四类,使得每一类的最小数值和最大数值的差值不超过2:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// 定义一个辅助函数,用于判断两个数的差值是否不超过2
bool withinRange(int a, int b) {
return abs(a - b) <= 2;
}
// 定义一个辅助函数,用于将元素分配到合适的类别中
void assignToCategory(const std::pair<int, int>& element, std::vector<std::vector<std::pair<int, int>>>& categories) {
for (auto& category : categories) {
if (category.empty() || withinRange(category[0].second, element.second)) {
category.push_back(element);
return;
}
}
// 若无合适类别,则创建新类别并将元素分配到其中
categories.push_back(std::vector<std::pair<int, int>>{element});
}
int main() {
std::vector<std::pair<int, int>> data = {
{0, 1}, {1, 3}, {2, 6}, {3, 4}, {4, 7}, {5, 9}, {6, 20}, {7, 17},
{8, 5}, {9, 8}, {10, 10}, {11, 13}, {12, 12}, {13, 15}, {14, 19}, {15, 14},
{16, 11}, {17, 16}, {18, 18}, {19, 2}, {20, 21}
};
// 按数值进行排序
std::sort(data.begin(), data.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b) {
return a.second < b.second;
});
std::vector<std::vector<std::pair<int, int>>> categories;
// 将元素分配到类别中
for (const auto& element : data) {
assignToCategory(element, categories);
}
// 打印每个类别中的元素
for (size_t i = 0; i < categories.size(); ++i) {
std::cout << "Category " << i + 1 << ":\n";
for (const auto& element : categories[i]) {
std::cout << "(" << element.first << ", " << element.second << ")\n";
}
std::cout << "\n";
}
return 0;
}
```
这段代码会将给定的数据按照数值排序,并将其分为四个类别,每一类的最小数值和最大数值的差值不超过2。你可以根据实际需要修改数据和调整代码。希望对你有所帮助!
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)