c++ - 排序 vector 不断修改数据并打印不正确的结果

标签 c++ sorting stl

所以我的代码基本上将学生 ID 和姓名映射到他或她的年级和许多功能,并且包含允许您按年级、ID 等搜索特定学生的内部功能。

我尝试实现的一个特定功能是按降序打印所有输入学生的成绩。

程序类

#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class student{
public:
student();
student(int,string);
int id;
string name;
};

class table{
public:
void InsertStudent(student x, int y);
void PrintAll(table t);
void SearchbyID(student x);
void SearchbyGrade(int y); 
void SortbyGrade(table t);


private:
map<student, int > records;

};

主要功能

int main (){
table t;
string command;
int id;
string name;
int grade;
student x;
while ( cin >> command ){

if (command=="InsertStudent"){

cin >> id >> name>> grade;

student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "PrintAll"){
t.PrintAll(t);
}else if (command == "SearchbyID"){
cin >> x.id;
t.SearchbyID(x);
}else if (command == "SearchbyGrade"){
cin >> grade;
t.SearchbyGrade(grade);
}
else if (command == "SortbyGrade"){
t.SortbyGrade(t);
}
else if (command == "exit"){
return 0;
 }
 }
}

排序等级函数

为了简化,我包含了以下结构。

struct information{
string id;
string name;
string grade;
};

void table::SortbyGrade(table t){
map<student,int>::iterator itr;
information a;
vector<information> v;
for(itr=records.begin();itr!=records.end();itr++)
{
    a.id=(*itr).first.id;
    a.name=(*itr).first.name;
    a.grade=(*itr).second;
    v.push_back(a);
}
vector<information>::iterator itr2;
sort(v.begin(),v.end(),compare);
for(itr2=v.begin();itr2!=v.end();itr2++){
    cout<<(*itr2).id<<" "<<(*itr2).name<<" "<<(*itr2).grade<<endl;
}
}

在这段代码中,我基本上是将映射中的键和值复制到 vector 上以实现排序算法

降序比较函数

bool compare(const information &a, const information & b){
if(a.grade>b.grade)
    return true;
else if(a.grade<b.grade)
    return false;
 else 
    return a.id<b.id;
}

相同的输入和输出

输入

插入学生 2016001 大卫 97

InsertStudent 2016002 爱丽丝 88

InsertStudent 2016003 jackson 100

InsertStudent 2016004 Eric 60

插入学生 2016005 约翰 97

插入学生 2016006 迈克尔 79

输出

jackson

大卫

约翰

爱丽丝 X

迈克尔欧

埃里克

这表明排序正确,但信息似乎已被更改。

最佳答案

我已经为您创建了一个最小示例来重现该行为:

#include <string>
#include <iostream>

int main() {
    std::string s;
    s = 100;
    std::cout << s << std::endl;
}

在你进一步阅读之前,你现在能自己找出原因吗?

std::string::operator= 有一些重载,这里最适合的是 std::string::operator=(char ch)。 100 是 'd' 的 ASCII 代码,因此当您将 Jackson 的成绩赋值给 information 结构中的 string grade 时,它就是 Jackson 的成绩.

关于c++ - 排序 vector 不断修改数据并打印不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47299730/

相关文章:

c++ - 从Lambda中的空指针调用方法

c++ - CMake - 模块 + 库混淆

c++ - 编译 Havok 演示

c++ - c++ 中是否有任何众所周知的基于文件的键-> 值数据结构可用?

c++ - GDI C/C++ - 将 BITMAP 转换为现有的 HBITMAP

sql - 在应用程序中排序与在数据库中排序

c++ - 将元素传递给 std::sort 中的比较函数的顺序背后的逻辑是什么?

java - 在java中使用值对象内的阿拉伯值对映射进行排序

c++ - 与多组件 key 的快速部分匹配

c++ - 对 C++ STL 列表有疑问