C++ 使用模板打印任何容器的所有数据
我计划写一个函数,可以打印任何容器的所有数据。换句话说,我可以使用不同的容器类型,比如vector、deque或list,我可以用不同的数据类型(整数、double或string)调用它。 模板函数可以通过编译器,但我不知道如何调用它C++ 使用模板打印任何容器的所有数据,c++,templates,containers,C++,Templates,Containers,我计划写一个函数,可以打印任何容器的所有数据。换句话说,我可以使用不同的容器类型,比如vector、deque或list,我可以用不同的数据类型(整数、double或string)调用它。 模板函数可以通过编译器,但我不知道如何调用它 #include <cstdlib> #include <stdio.h> #include <iostream> #include <list> using namespace std; template &l
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <list>
using namespace std;
template <typename C, template <typename C> class M>
void print(M<C> data){
typename M<C>::iterator it;
for(it=data.template begin();it!=data.template end();++it){
cout<<*it<<" ";
}
cout<<endl;
}
int main(int argc, char** argv) {
list<int> data;
for(int i=0;i<4;i++){
data.push_back(i);
}
print<int>(data); //compile error
print<int, list>(data); //compile error
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
模板
作废打印(M数据){
类型名M::迭代器;
对于(it=data.template begin();it!=data.template end();++it){
cout如注释中所述,std::list
实际上有多个模板参数(第二个参数是分配器)。此外,print
无需获取两个模板参数;您可以简单地在整个容器类型上对其进行参数化:
#include <iostream>
#include <iterator>
#include <list>
using namespace std;
template <typename C>
void print(const C &data){
for(auto it=begin(data);it!=end(data);++it){
cout<<*it<<" ";
}
cout<<endl;
}
int main(int argc, char** argv) {
list<int> data;
for(int i=0;i<4;i++){
data.push_back(i);
}
print(data);
return 0;
}
请注意,由于我们通过常量引用获取数据
,因此需要使用const\u迭代器
,如注释中所述,std::list
实际上有多个模板参数(第二个参数是分配器)。此外,print
无需获取两个模板参数;您只需在整个容器类型上对其进行参数化即可:
#include <iostream>
#include <iterator>
#include <list>
using namespace std;
template <typename C>
void print(const C &data){
for(auto it=begin(data);it!=end(data);++it){
cout<<*it<<" ";
}
cout<<endl;
}
int main(int argc, char** argv) {
list<int> data;
for(int i=0;i<4;i++){
data.push_back(i);
}
print(data);
return 0;
}
请注意,由于我们通过常量引用获取数据
,因此需要使用常量迭代器
使用c++11可以将其简化为:
template <typename C>
void print(const C &data){
for (auto &elem : data)
cout << elem << " ";
cout << endl;
}
模板
无效打印(常量C和数据){
用于(自动和电气:数据)
使用c++11可以将其简化为:
template <typename C>
void print(const C &data){
for (auto &elem : data)
cout << elem << " ";
cout << endl;
}
模板
无效打印(常量C和数据){
用于(自动和电气:数据)
coutstd::list
具有多个模板参数。您也不应该显式提供模板参数。std::list
具有多个模板参数。您也不应该显式提供模板参数。