void PRINT_ELEMENTS(const T& coll, const char* optcstr = " ") { typename T::const_iterator pos; cout << optcstr; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos <<" "; } cout << endl; }
一个案例实现:
#include<iostream> #include<cstdlib> #include<string> using namespace std; template <class T> void PRINT_ELEMENTS(const T& coll, const char* optcstr = " ") { typename T::const_iterator pos; cout << optcstr; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos <<" "; } cout << endl; } int main() { char name1[10]; char name2[10]; cin.get(name1,9,'.'); cin >> name2; PRINT_ELEMENTS(static_cast<string>(name1)); PRINT_ELEMENTS(static_cast<string>(name2)); cin.get(); cin.getline(name1, 9, '.'); cin >> name2; PRINT_ELEMENTS(static_cast<string>(name1)); PRINT_ELEMENTS(static_cast<string>(name2)); system("pause"); }
输入:123.456 123.456
输出结果:
1 2 3
. 4 5 6
1 2 3
4 5 6