如何在 C++ 中编写接受任何 STL 容器作为参数的函数
STL 容器接受两个模板参数,容器内的类型 T 和分配器(默认为 std::allocator<T>)。
因此要编写接受任何类 STL 容器的函数,你必须像此示例函数那样做:
container_template.cpp
/**
* 将任何类 STL 容器转换为 std::vector。
*/
template<template<typename, typename> typename Container, typename T, typename Allocator>
std::vector ToVector(const Container<T, Allocator>& args) {
std::vector ret;
ret.reserve(args.size());
for(const T& arg : args) {
ret.push_back(arg);
}
return ret;
}此函数可以接受任何类 STL 容器如 std::list、std::vector 以及来自第三方库的 STL 兼容容器,并将其转换为 std::vector。
完整示例:
container_example.cpp
#include <list> // std::list
#include <vector> // std::vector
#include <iostream> // std::cout, std::endl
using namespace std;
/**
* 将任何类 STL 容器转换为 std::vector。
*/
template<template<typename, typename> typename Container, typename T, typename Allocator>
std::vector ToVector(const Container<T, Allocator>& args) {
std::vector ret;
ret.reserve(args.size());
for(const T& arg : args) {
ret.push_back(arg);
}
return ret;
}
int main() {
// 创建列表
list myList;
myList.push_back(2);
myList.push_back(3);
myList.push_back(5);
// 转换为 vector
vector myVector = ToVector(myList);
// 打印 vector - 应该打印 2、3 和 5
for(int val : myVector) {
cout << val << endl;
}
}感谢 Jesse Good 在 StackOverflow 上发布关于如何解决此问题的提示。但是,他的版本仅适用于使用 std::allocator 的 STL 容器,不适用于没有自定义分配器的 STL 容器。根据我的经验,你很少需要使用自定义分配器,但如果使用,很难调试模板为何不匹配。
Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow