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

What's wrong with this code in c++ involving sorting of an array of objects?

本文关键字:数组 对象 排序 问题 什么 c++ 段代码 代码      更新时间:2023-10-16
#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&)]'

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

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

指示 sort 算法正在尝试将const参数传递给比较器,比较器错误地将其参数视为非常量引用。

要修复它,请将参数设为const

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

我建议你:

  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&参数

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