在 c++ 中,这段代码涉及对象数组的排序有什么问题?
What's wrong with this code in c++ involving sorting of an array of objects?
#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)
我建议你:
- 删除原始固定大小的数组并使用
std::vector<student>
或std::list<student>
, 例如std::vector<student> a;
- 将
a[i] = person;
替换为a.emplace_back(std::move(person));
- 排序范围:
sort(a.begin(),a.end(),valuecmp);
-
更改比较函数的签名以接受
const student&
参数bool valuecmp(const student & a, const student& b)
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放