对包含整数和字符的字符串数组进行排序

时间:2017-10-16 20:47:26

标签: c++ arrays sorting

  • 我从文件中读取了5个元素。

  • 我的档案// H4,C8,HJ,C9,D10,D5,DK,D2,S7,DJ,SK,H3,H6

  • BTW这些是扑克牌。我忽略了第一个角色。
  • 我的前5个排序列表应该是这样的 - HJ,D10,C9,C8,H4

    while(getline(inputFile, val, ','))
    {
        stringstream ss(val);
        while(ss.good() && i < 5)
        {
            ss >> myArray[i];
            i++;
    
        }
    
  • 如何按升序对数组进行排序..

  • 或者在将数据字符串存储到数组中之前是否需要排序?

3 个答案:

答案 0 :(得分:1)

这是一个小例子,你如何对卡片进行排序(你还要考虑错误处理它,没有实现它):

#include <iostream>
#include <algorithm>

using namespace std;

int getCardRange(const std::string& card)
{
    switch(card[1])
    {
        case '2': return 2;
        case '3': return 3;
        case '4': return 4;
        case '5': return 5;
        case '6': return 6;
        case '7': return 7;
        case '8': return 8;
        case '9': return 9;
        case '1': return 10;
        case 'J': return 11;
        case 'Q': return 12;
        case 'K': return 13;
        case 'A': return 14;
    }
    return -1; // error
}

bool compare(const std::string& a, const std::string& b)
{
    return getCardRange(a) > getCardRange(b);
}

int main()
{
    std::string myArray[13] = {"H4","C8","HJ","C9","D10","D5","DK","D2","S7","DJ","SK","H3","H6"};
    // sort using a lambda expression 
    std::sort(std::begin(myArray), std::end(myArray), compare);

    for(auto card : myArray)
    {
        std::cout << card << ' ';
    }
    std::cout << '\n';

    return 0;
}

答案 1 :(得分:0)

您可以将std :: sort与矢量一起使用(您可以阅读更多in the documentation

它需要输入如下数组:

std::sort(cards.begin(), cards.end());

答案 2 :(得分:0)

你必须有矢量或数组。如果不允许使用向量,则首先通过读取数组并计算项目数(count)来创建数组。根据该大小创建一个数组,然后再次读取该文件并设置数组项:

string str;
int count = 0;
while(getline(file, str, ','))
    count++;

string *sarray = new string[count];

file.clear();
file.seekg(0, ios::beg);
int i = 0;
while(getline(file, str, ','))
{
    //trim spaces if any
    str.erase(0, str.find_first_not_of(' '));
    str.erase(str.find_last_not_of(' ') + 1);

    sarray[i] = str;
    i++;
    if(i == count)
        break;
}

要对值进行排序,请将字符串分为两部分。例如,将H4分为H4。然后进行比较。以下使用lambda排序。也许你想把它改成类似于其他答案的东西。

std::sort(sarray, sarray + count, [](string a, string b)
{
    //save the first character
    char chA = a[0];
    char chB = b[0];

    //remove the first character
    a.erase(0, 1);
    b.erase(0, 1);

    if(a == "J") a = "11";
    if(a == "Q") a = "12";
    if(a == "K") a = "13";
    if(a == "A") a = "14";

    if(b == "J") b = "11";
    if(b == "Q") b = "12";
    if(b == "K") b = "13";
    if(b == "A") b = "14";

    //convert to integer
    int v1 = stoi(a);
    int v2 = stoi(b);

    //if the two cards have the same values...
    if(v2 == v1) return chA > chB;

    return v1 > v2;
});

清理:

delete[]sarray;

注意,您可能希望为stoi

添加异常处理
相关问题