模板函数,容器的iterator
我想实现一个能够打印容器元素的模板函数,
一开始的想法是。
template<typename T>void print_container(T t) { T::iterator it; //编译错误 for(; it != t.end(); it++) { std::cout << *it << " "; } std::cout << "\n";}
template<typename T>void print_container(vector<T> t) { vector<T>::iterator it; //编译错误 for(; it != t.end(); it++) { std::cout << *it << " "; } std::cout << "\n";}
//头文件里#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"; }
//只能在这先定义了,只是简化了我的编码而已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;}
#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;}
[解决办法]
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;}
[解决办法]
typename vector<T>::iterator it;