读书人

模板函数器皿的iterator

发布时间: 2012-07-08 17:43:44 作者: rapoo

模板函数,容器的iterator
我想实现一个能够打印容器元素的模板函数,
一开始的想法是。

C/C++ code
template<typename T>void print_container(T t) {    T::iterator it;                  //编译错误     for(; it != t.end(); it++) {        std::cout << *it << " ";    }    std::cout << "\n";}

改了之后
C/C++ code
template<typename T>void print_container(vector<T> t) {    vector<T>::iterator it;                  //编译错误     for(; it != t.end(); it++) {        std::cout << *it << " ";    }    std::cout << "\n";}

iterator不支持泛型,有什么比较好的解决办法吗?
我尝试了使用宏,但并不能在函数调用的时候,才去识别类型。
C/C++ code
//头文件里#define PRINT_VECTOR(T)  void print_container(vector<T> t) { \    vector<T>::iterator it = t.begin();  \    for(; it != t.end(); it++) { \        std::cout << *it << " "; \    }                         \    std::cout << "\n"; }


C/C++ code
//只能在这先定义了,只是简化了我的编码而已PRINT_VECTOR(int)int main() {    int a[ELEMENT_SIZE] = {2,3,4,5,90,12,34,3};    vector<int> vec(a,a+ELEMENT_SIZE);    vector<int> vec2;    copy(vec.begin(),vec.end(),back_inserter(vec2));    print_container(vec2);    return 0;}

这种方法只是简化了我去编写各种类型的函数,其实还是定义了多个函数的,而不是一个模板函数。


[解决办法]
修改了一下,只要1个模板参数,不用2个

C/C++ code
#include <iostream>#include <vector>#include <string>#include <iterator>using namespace std;template <typename T>void display(const T & t){    T::const_iterator it;    for (it = t.begin(); it != t.end(); ++it)        cout << *it << " ";    cout << endl;}int main(){    vector<string> a;    a.push_back("hello");    a.push_back("world!");    display(a);    return 0;}
[解决办法]
C/C++ code
typedef struct{    int x, y;}T;std::ostream& operator<<(std::ostream &os, const T &t){    os << t.x << ", " << t.y;    return os;}template<class InputIterator> void PrintInfo(InputIterator first, InputIterator last)  {    for ( ; first!=last; ++first )    {        std::cout << *first << std::endl;    }  }int _tmain(int argc, _TCHAR* argv[]){    T x[3] = {{1, 2}, {3, 4}, {5, 6}};    std::vector<T> vec(x, x+3);    PrintInfo(vec.begin(), vec.end());    system("pause");    return 0;}
[解决办法]
C/C++ code
typename vector<T>::iterator it; 

读书人网 >C++

热点推荐