注册 登录
编程论坛 C++教室

使用了一个函数模板,用于输出对象,但编译错误。

ClarenceC 发布于 2014-11-13 11:04, 456 次点击
程序代码:
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;
}
3 回复
#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;
}

#3
七夜之华2014-11-13 13:28
楼上正解。。。。神回复,一起采纳吧。。。。。
#4
ClarenceC2014-11-13 22:34
回复 2 楼 rjsp
谢谢你啊。
1