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

帮我看看函数模板

kscooh1 发布于 2011-12-06 15:55, 773 次点击
--------------------Configuration: 函数模板 - Win32 Debug--------------------
Compiling...
median.cpp
F:\C语言加深\C++\函数模板\median.cpp(3) : error C2143: syntax error : missing ',' before '<'
F:\C语言加深\C++\函数模板\median.cpp(3) : error C2059: syntax error : '<'
Skipping... (no relevant changes detected)
16-27.cpp
执行 cl.exe 时出错.

函数模板.exe - 1 error(s), 0 warning(s)
代码如下:
程序代码:
//median.cpp
template<typename T>
bool median(const vector<T>&c,T&m)
{
    vector<T> temp(c);

    if(temp.size()%2==0)
        return false;

    sort(temp.begin(),temp.end());

    vector<T>::size_type index=temp.size()/2;
    if(temp[index]>temp[index-1]&&temp[index]<temp[index-1])
    {
        m=temp[index];
        return true;
    }
    else
        return false;
}
4 回复
#2
rjsp2011-12-06 16:58
难道没有#include <vector>?如果是,那就欠抽了。以下代码在gcc4.6.1和vc++9.0下都编译运行通过
程序代码:
#include <algorithm>
#include <vector>
using namespace std;

template<typename T>
bool median( const vector<T>& c, T& m )
{
    vector<T> temp(c);

    if( temp.size()%2 == 0 )
        return false;
    if( temp.size() == 1 )
    {
        m = c[0];
        return true;
    }

    sort( temp.begin(), temp.end() );

    typename vector<T>::size_type index = temp.size()/2;
    if(temp[index]>=temp[index-1] && temp[index]<=temp[index+1])
    {
        m = temp[index];
        return true;
    }

    return false;
}

#include <iostream>

int main()
{
    vector<int> c;
    c.push_back( 4 );
    c.push_back( 3 );
    c.push_back( 5 );

    int m;
    median( c, m );
    cout << m << endl;

    return 0;
}

#3
rjsp2011-12-06 17:00
顺便说一句,找中值肯定不需要全部排序,因此使用sort是不对的。
stl中已有这样的函数,名字叫 nth_element
#4
lucky5635912011-12-07 08:21
函数没问题啊。
#5
共和国鹰派2011-12-07 13:27
如果不使用如二楼所加的typename的话则会将size_type认为是vector<T>的一个静态成员所以出现这个错误
1