用c++实现模板排序不同类型的数据 {46 15 33 51 2 100 0 30} {4.4 5.1 3.3 5.5 2.2 3 15 8.9} {"banana" "apple" "pear" "watermelon"}
时间: 2024-06-17 10:01:32 浏览: 7
在C++中,模板是一种强大的工具,它允许编写通用的代码来处理不同类型的数据,包括整数、浮点数和字符串。要对不同类型的集合如 {46, 15, 33, 51, 2, 100, 0, 30}、{4.4, 5.1, 3.3, 5.5, 2.2, 3, 15, 8.9} 和 {"banana", "apple", "pear", "watermelon"} 进行排序,你可以使用STL(Standard Template Library)中的`std::sort`函数,配合C++11或以后版本的模板元编程特性。
首先,你需要一个通用的比较函数,这里我们可以定义一个模板函数`compare`来处理不同类型的比较:
```cpp
template <typename T>
bool compare(const T& a, const T& b) {
// 根据类型的不同实现相应的比较逻辑
if constexpr (std::is_arithmetic<T>::value) {
return a < b; // 对于数值,直接使用标准小于运算符
} else {
return a.compare(b); // 对于字符串,可能需要重载compare方法
}
}
```
然后,你可以使用`std::sort`和上述的比较函数来对任意类型的容器进行排序:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
// 假设你已经有了这样的容器
std::vector<int> intVec = {46, 15, 33, 51, 2, 100, 0, 30};
std::vector<double> doubleVec = {4.4, 5.1, 3.3, 5.5, 2.2, 3, 15, 8.9};
std::vector<std::string> stringVec = {"banana", "apple", "pear", "watermelon"};
// 使用模板函数对每个容器进行排序
void sortContainer(std::vector<T>& vec) {
std::sort(vec.begin(), vec.end(), compare<T>);
}
int main() {
sortContainer(intVec);
sortContainer(doubleVec);
sortContainer(stringVec);
// 打印排序后的结果
for (const auto& item : intVec) {
std::cout << item << " ";
}
std::cout << "\n";
for (const auto& item : doubleVec) {
std::cout << item << " ";
}
std::cout << "\n";
for (const auto& item : stringVec) {
std::cout << item << " ";
}
std::cout << "\n";
return 0;
}
```
执行这段代码后,你会看到三个容器中的数据都已经按升序排列了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)