请大神帮忙~C++ 分组并排序

问题描述:
Read the datasets and write them into cout in the following order:
first by dataset (first a, then b) and then by value. Example:
input: a 3 b 2 b 1 a 1 a 4 b 2
output: 1 3 4 1 2 2

我的代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

    vector<int> a;  //将vector a, b 定义为全局变量,因为之后要用
    vector<int> b;  

void assignGroup(char groupName, int x){
    vector<int> a1;  //定义两个局部变量,接收用户输入的数x
    vector<int> b1;
    switch(groupName){
        case 'a':    //若输入a x, 则x放入vector a1
            a1.push_back(x); 
            break;
        case 'b':   //若输入b x, 则x放入vector b1
            b1.push_back(x);
            break;
        default:
            break;
    }

    a=a1;  //将a1,b1 赋给全局变量a,b
    b=b1;
}
void displaya(){  
    sort(a.begin(),a.end()); //vector a 中的元素以从小到大的顺序排列
    for (auto e : a){        //输出vector a 中的元素
        cout<<e<<" ";
    }
}
void displayb(){
    sort(b.begin(),b.end()); //vector b 中的元素以从小到大的顺序排列
    for (auto e : b){        //输出vector b 中的元素
        cout<<e<<" ";
    }
}

int main(){
    char groupName;
    int x;
    while (true){
        cin>>groupName;   //输入例如 a 3 a 2 b 1 a 4....
        cin>>x;

        if (cin.fail()){
            break;
        }
        assignGroup(groupName,x);//先将数字分成ab两组
        displaya();              //输出排列好的a b
        displayb();
    }
    return 0;
}

输入:a 3 b 2 b 1 a 1 a 4 b 2
正确输出:1 3 4 1 2 2
我的输出:3 2 1 1 4 2
看上去既没有分组也没有排序。。。

Thank you for your time:)

    vector<int> a1;  //定义两个局部变量,接收用户输入的数x
    vector<int> b1;
去掉这些
直接pushback到a b中,然后检查groupName输入正确了没有
换成scanf

不晓得你的问题解决没,有以下几个问题,但是思路是没问题的:
1.你的displaya(),displayb()在接收完一对数据后就打印怎么可能有排序的效果嘛。
2.你设了全局变量函数里面就没必要在设vector a1, b1了,你那样赋值以后如果改正了第一个问题估计最后的输出都只有两个。
3.还有cin.fail()的解释你都没看懂就在乱用了,不知道你有没有发现自己的程序跑起来都结束不了,所以如果只改前面两个问题,会看不到输出,因为程序结束不了。
以下是修改的代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

    vector<int> a;
    vector<int> b;

void assignGroup(char groupName, int x){
    switch(groupName){
        case 'a':
            a.push_back(x);
            break;
        case 'b':
            b.push_back(x);
            break;
        default:
            break;
    }
}
void displaya(){
    sort(a.begin(),a.end());
    for (auto e : a){
        cout<<e<<" ";
    }
}
void displayb(){
    sort(b.begin(),b.end());
    for (auto e : b){
        cout<<e<<" ";
    }
}

int main(){
    char groupName;
    int x;
    while (true){
        cin>>groupName;
        cin>>x;
        assignGroup(groupName,x);
        char c = cin.get();
        if(c=='\n')
            break;
    }
    displaya();
    displayb();
    return 0;
}