![]() |
#2
rjsp2014-11-13 12:22
为什么代码不完整,未#include必要的文件?
既然编译无法通过,为什么不贴出编译器给出的错误信息? 若在你源代码上改 ![]() #include <iostream> template<class C> void show_ar( typename C::iterator first, typename C::iterator last ) { for( typename C::iterator itor=first; itor!=last; ++itor ) std::cout << *itor << ' '; } #include <string> #include <vector> int main() { using namespace std; vector<int> arint(4,3); vector<string> arstr(4, "xiaogang"); show_ar<vector<int>>(arint.begin(),arint.end()); cout << endl; show_ar<vector<string>>(arstr.begin(), arstr.end()); cout << endl; return 0; } 其实那个模板函数可以做得更通用,不需要调用时显式指明容器类型 ![]() #include <iostream> template<class InputIterator> void show_ar( InputIterator first, InputIterator last ) { for( InputIterator itor=first; itor!=last; ++itor ) std::cout << *itor << ' '; } #include <string> #include <vector> int main() { using namespace std; vector<int> arint(4,3); vector<string> arstr(4, "xiaogang"); show_ar( arint.begin(), arint.end() ); cout << endl; show_ar( arstr.begin(), arstr.end() ); cout << endl; return 0; } 最后,当然,根本没必要做这个函数 ![]() #include <iostream> #include <string> #include <vector> #include <algorithm> #include <iterator> int main() { using namespace std; vector<int> arint(4,3); vector<string> arstr(4, "xiaogang"); copy( arint.begin(), arint.end(), ostream_iterator<int>(cout," ") ); cout << endl; copy( arstr.begin(), arstr.end(), ostream_iterator<string>(cout," ") ); cout << endl; return 0; } |

template<class object>
void show_ar(object::iterator a,object::iterator b)
{
object::iterator p = a, p1 = b;
for (; p != p1; ++p)
cout << *p << ' ';
}
int main()
{
using namespace std;
vector<int> arint(4,3);
vector<string> arstr(4, "xiaogang");
show_ar<vector<int>>(arint.begin(),arint.end());//为什么此处编译无法通过呢?请讲解一下,谢了。
cout << endl;
show_ar<vector<string>>(arstr.begin(), arstr.end());
cout << endl;
system("pause");
return 0;
}
void show_ar(object::iterator a,object::iterator b)
{
object::iterator p = a, p1 = b;
for (; p != p1; ++p)
cout << *p << ' ';
}
int main()
{
using namespace std;
vector<int> arint(4,3);
vector<string> arstr(4, "xiaogang");
show_ar<vector<int>>(arint.begin(),arint.end());//为什么此处编译无法通过呢?请讲解一下,谢了。
cout << endl;
show_ar<vector<string>>(arstr.begin(), arstr.end());
cout << endl;
system("pause");
return 0;
}