为什么代码不完整,未#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;
}