【问题标题】:Sorting vector keeps modifying data and prints incorrect results排序向量不断修改数据并打印不正确的结果
【发布时间】:2017-11-15 05:06:38
【问题描述】:

所以我的代码基本上将学生 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;
}
}

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

降序比较函数

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

插入学生 2016002 爱丽丝 88

插入学生 2016003 杰克逊 100

插入学生 2016004 埃里克 60

插入学生 2016005 约翰 97

插入学生 2016006 迈克尔 79

输出

杰克逊 d

大卫一个

约翰一

爱丽丝 X

迈克尔·奥

埃里克

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

【问题讨论】:

    标签: c++ sorting stl


    【解决方案1】:

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

    #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 码,因此当您将其值分配给 information 结构中的 string grade 时,杰克逊的成绩会变成这样。

    【讨论】:

      猜你喜欢
      • 2021-10-29
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多