这个代码在c ++中涉及到对象数组的排序有什么问题?

时间:2014-08-30 15:55:04

标签: c++

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
class student
{
    public:
    string s;
    int age;
};

istream& operator >>(istream& in, student& val) 
{
    return in >> val.s >> val.age;
}
bool valuecmp(student & a, student & b)
{
    return a.s < b.s;
}

int main (void)
{
    student a[5];

    fstream myfile; 
    myfile.open("a1.txt",ios::in);
    int i = 0;

    for (string line; getline(myfile, line);) 
    {
        istringstream stream(line);
        student person;
        stream >> person;
        a[i] = person;
        cout<<a[i].s<<a[i].age<<"\n";
        i++;
    }
    sort(a,a+2,valuecmp);
    for ( i = 0; i < 2; i++ )
    {
        cout<<a[i].s<<a[i].age<<"\n";
    }   
    return 0;
}

我要做的是基本上读取包含不同行中的对象信息的文件。然后我尝试根据字符串s的值对这些对象进行排序。但是,此代码显示错误。为什么会这样?

错误:(这是一个非常大的,添加了一部分)

In file included from /usr/include/c++/4.8.2/algorithm:62:0,
             from faltu1.cpp:5:
/usr/include/c++/4.8.2/bits/stl_algo.h: In instantiation of '_RandomAccessIterator   std::__unguarded_partition(_RandomAccessIterator, _RandomAccessIterator, const _Tp&, _Compare) [with _RandomAccessIterator = student*; _Tp = student; _Compare = bool (*)(student&, student&)]':
/usr/include/c++/4.8.2/bits/stl_algo.h:2296:78:   required from '_RandomAccessIterator std::__unguarded_partition_pivot(_RandomAccessIterator, _RandomAccessIterator, _Compare)   [with _RandomAccessIterator = student*; _Compare = bool (*)(student&, student&)]'

2 个答案:

答案 0 :(得分:0)

我建议你:

  1. 删除原始固定大小的数组并使用std::vector<student>std::list<student>,例如std::vector<student> a;
  2. a[i] = person;替换为a.emplace_back(std::move(person));
  3. 排序范围:sort(a.begin(),a.end(),valuecmp);
  4. 更改比较功能的签名以接受const student& args

    bool valuecmp(const student & a, const student& b)

答案 1 :(得分:0)

您忘记发布错误的描述部分:

error: invalid initialization of reference of type ‘student&’ from expression 
    of type ‘const student’
    while (__comp(*__first, __pivot))

表示sort算法试图将const参数传递给比较器,该比较器错误地将其参数作为非const引用。

要修复它,请创建参数const

bool valuecmp(student const & a, student const & b)