向量排序中的C ++模板函数出错

时间:2014-08-01 21:07:32

标签: c++ templates

我想使用模板函数来排序类的向量,但是我遇到了编译错误。错误是由于模板。它在我使用类而不是模板时编译。

class Person
{
    private:
      int ssn;
      string name;

    public:
      Person() {};
      Person(int s, string na) { ssn = s; name = na; }
      const int getSSN() { return ssn; }

      friend ostream& operator <<(ostream& out, const Person& per) {
          out << per.ssn << "  " << per.name;
      }
};

template <typename T> 
bool myfunction(T i, T j) { return (i.getSSN() < j.getSSN()); }
// it complies fine when I use 
// bool myfunction(Person i, Person j) { return (i.getSSN() < j.getSSN()); }

int main()
{
    ifstream in("personal.dat");
    string st;
    vector<Person> *vect = new vector<Person>;
    int ssn;
    string name;
    while(in >> ssn >> name) {
            Person per(ssn, name);
            vect->push_back(per);
    }
    in.close();

    sort(vect->begin(), vect->end(), myfunction);
    for(int i=0; i<vect->size(); i++) cout << vect->at(i) << endl;
}

编译错误:

read.cxx: In function ‘int main()’:
read.cxx:41:45: error: no matching function for call to  ‘sort(std::vector<Person>::
iterator, std::vector<Person>::iterator, <unresolved overloaded function type>)’
sort(vect->begin(), vect->end(), myfunction);

read.cxx:41:45: note: candidates are:
In file included from /usr/include/c++/4.8.3/algorithm:62:0,
         from read.cxx:6:
/usr/include/c++/4.8.3/bits/stl_algo.h:5438:5: note: template<class _RAIter> 
void std::sort(_RAIter, _RAIter) sort(_RandomAccessIterator __first,
_RandomAccessIterator __last)
.................
.................

有什么建议吗?非常感谢。

3 个答案:

答案 0 :(得分:3)

您应该告诉它要比较的元素类型:

sort(begin, end, myfunction<Person>);

答案 1 :(得分:2)

myfunction是一个表示无限过载集的函数模板。为了让编译器解决您想要的过载,您需要提供模板参数。在这种情况下,您需要Person比较函数:

std::sort(vect->begin(), vect->end(), myfunction<Person>);

或者,您可以提供lambda表达式,将参数转发到myfunction

std::sort(vect->begin(), vect->end(),
[&] (Person const& lhs, Person const& rhs) { return myfunction(lhs, rhs); });

此外,您不必要地动态分配std::vector。向量的要点是省去了动态C风格数组的手动内存管理。只需静态分配,而不是使用->运算符使用.

std::vector<Person> vect;

答案 2 :(得分:-2)

//Actually, it was simple. I used following line in small test code it works fine.

//sort(fileVector->begin(), fileVector->end(), myfunction<T>);

//However, in my actual code, it crashes with Segmentation fault (core dumped). I am 
//looking on this.

template <class T>
bool myfunction(T i, T j) { return (i.getSSN() < j.getSSN()); }

template <class T>
void sortt(vector<T> *vect)
{
    sort(vect->begin(), vect->end(), myfunction<T>);
}


int main()
{
   ..............
   ..............
   sortt(vect);
}