【问题标题】:Arranging an array in ascending order w/ a string array & int array使用字符串数组和整数数组按升序排列数组
【发布时间】:2025-12-17 08:50:02
【问题描述】:

因此,我已经为此工作了几个小时,并尝试在互联网上寻找更好的解决方案,但我无法为我的具体问题找到答案。

任务是... 计算每个名称中的字符数,然后将它们从最少字母到最多字母排序。

它们必须排序的格式如下:

名称 1 - 计数 1

Name2 - Count2

[...]

现在,我遇到的问题是:我可以成功地将int array[] 排列成升序,但是我需要string array[] 对应于int array[] 并并排输出。

以下是我拥有的以下代码。我已经尝试使用自己的知识尽我所能解决这个问题。如果有人能指出我正确的方向(不是为我解决),或者解释为什么我的while 函数没有按我的预期工作。不胜感激!~

    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 7           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    int alphaCount[26];
    int sortedCount[26];
    int temp;
    string temp2;
    string sortedNames[26];
    string t;
 
    for (int i = 1; i < 26; i++) {
        string t = n.names[i];
        t.erase(remove_if(t.begin(), t.end(), isspace), t.end());
        alphaCount[i] = t.size();
    }
 
    for (int i = 0; i < 26; i++) {
        sortedCount[i] = alphaCount[i];
    }
 
    for (int i = 0; i < 26; i++) {
        for (int j = i + 1; j < 26; j++) {
            if (sortedCount[i] > sortedCount[j]) {
                temp = sortedCount[i];
                sortedCount[i] = sortedCount[j];
                sortedCount[j] = temp;
            }
        }
    }
 
    int i = 0;
 
    while (i < 26) {
        int j = 1;
        while (j < 26) {
            if (sortedCount[i] == n.names[j].length()) {
                cout << n.names[j] << " - " << sortedCount[i] << endl;
                i++;
            }
            if (sortedCount[i] != n.names[j].length()) {
                j++;
            }
        }
    }
 
    systemClear();
}

如果您想查看所有代码,这里是完整的 cpp 文件。您正在专门查看例程 7

#include <iomanip>
#include <string>
#include <fstream>
 
using namespace std;
 
struct file {
    string names[26];
};
 
void systemClear();
void routineOne(file& n);
void routineTwo(file& n);
void routineThree(file& n);
void routineFour(file& n);
void routineFive(file& n);
void routineSix(file& n);
void routineSeven(file& n);
void routineEight(file& n);
 
int main()
{
    file n;
 
    //Function Execution
    routineOne(n);
    routineTwo(n);
    routineThree(n);
    routineFour(n);
    routineFive(n);
    routineSix(n);
    routineSeven(n);
    routineEight(n);
}
 
void systemClear() {
    short a = 0;
 
    cout << "\n\nPlease enter any number to continue: ";
    cin >> a;
    if (a != 0) {
        system("cls");
        return;
    }
    else {
        system("cls");
        return;
    }
}
 
void restart() {
    char a = 0;
 
    cout << "\n\nWould you like to restart the program? (y/n): ";
    cin >> a;
    if (a == 'y') {
        system("cls");
        main();
    }
    else {
        system("cls");
        cout << "\nThe program will now close, thank you\n\n";
        return;
    }
}
 
void routineOne(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 1           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    ifstream inFile;
    inFile.open("Student.txt");
 
    inFile.ignore(12);
 
    for (int i = 0; i < 26; i++) {
        getline(inFile, n.names[i]);
        inFile.ignore(1);
    }
 
    cout << "The input file has successfully been passed to an array.";
    systemClear();
}
 
void routineTwo(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 2           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    int x = 1;
    int y = 25;
 
    while (y != 13) {
        cout << n.names[x] << endl;
        x++;
        cout << n.names[y] << endl;
        y--;
    }
 
    cout << n.names[13] << endl;
 
    systemClear();
}
 
void routineThree(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 3           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    //I attempted an algorithm I found, however I couldn't get it to function properly (Is this the proper way of solving this problem?)
    cout << n.names[24] << endl;
    cout << n.names[14] << endl;
    cout << n.names[13] << endl;
    cout << n.names[22] << endl;
    cout << n.names[4] << endl;
    cout << n.names[16] << endl;
    cout << n.names[25] << endl;
    cout << n.names[21] << endl;
    cout << n.names[9] << endl;
    cout << n.names[19] << endl;
    cout << n.names[6] << endl;
    cout << n.names[12] << endl;
    cout << n.names[7] << endl;
    cout << n.names[2] << endl;
    cout << n.names[11] << endl;
    cout << n.names[20] << endl;
    cout << n.names[17] << endl;
    cout << n.names[23] << endl;
    cout << n.names[3] << endl;
    cout << n.names[8] << endl;
    cout << n.names[18] << endl;
    cout << n.names[5] << endl;
    cout << n.names[15] << endl;
    cout << n.names[10] << endl;
    cout << n.names[1] << endl;
 
    systemClear();
}
 
void routineFour(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 4           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    //I attempted an algorithm I found, however I couldn't get it to function properly (Is this the proper way of solving this problem?)
    cout << n.names[24] << endl;
    cout << n.names[14] << endl;
    cout << n.names[13] << endl;
    cout << n.names[22] << endl;
    cout << n.names[4] << endl;
    cout << n.names[16] << endl;
    cout << n.names[25] << endl;
    cout << n.names[21] << endl;
    cout << n.names[9] << endl;
    cout << "James N Blythe" << endl;
    cout << n.names[19] << endl;
    cout << n.names[6] << endl;
    cout << n.names[12] << endl;
    cout << n.names[7] << endl;
    cout << n.names[2] << endl;
    cout << n.names[11] << endl;
    cout << n.names[20] << endl;
    cout << n.names[17] << endl;
    cout << n.names[23] << endl;
    cout << n.names[3] << endl;
    cout << n.names[8] << endl;
    cout << n.names[18] << endl;
    cout << n.names[5] << endl;
    cout << n.names[15] << endl;
    cout << n.names[10] << endl;
    cout << n.names[1] << endl;
 
    systemClear();
}
 
void routineFive(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 5           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    string oddNames[12];
    int j = 0;
 
    for (int i = 1; i < 25; i++) {
            i++;
            oddNames[j] = n.names[i];
            j++;
    }
 
    for (int i = 0; i < 12; i++) {
        cout << oddNames[i] << endl;
    }
 
    systemClear();
}
 
void routineSix(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 6           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    cout << "???";
 
    systemClear();
 
}
 
void routineSeven(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 7           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    int alphaCount[26];
    int sortedCount[26];
    int temp;
    string temp2;
    string sortedNames[26];
    string t;
 
    for (int i = 1; i < 26; i++) {
        string t = n.names[i];
        t.erase(remove_if(t.begin(), t.end(), isspace), t.end());
        alphaCount[i] = t.size();
    }
 
    for (int i = 0; i < 26; i++) {
        sortedCount[i] = alphaCount[i];
    }
 
    for (int i = 0; i < 26; i++) {
        for (int j = i + 1; j < 26; j++) {
            if (sortedCount[i] > sortedCount[j]) {
                temp = sortedCount[i];
                sortedCount[i] = sortedCount[j];
                sortedCount[j] = temp;
            }
        }
    }
 
    int i = 0;
 
    while (i < 26) {
        int j = 1;
        while (j < 26) {
            if (sortedCount[i] == n.names[j].length()) {
                cout << n.names[j] << " - " << sortedCount[i] << endl;
                i++;
            }
            if (sortedCount[i] != n.names[j].length()) {
                j++;
            }
        }
    }
 
    systemClear();
}
 
void routineEight(file& n) {
    cout << setw(34) << setfill('#') << "#\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << "#           Routine 8           #\n";
    cout << "#" << setw(33) << setfill(' ') << "#\n";
    cout << setw(35) << setfill('#') << "\n\n";
 
    restart();
}

【问题讨论】:

  • 您能看看std::sort 及其比较器功能吗?该函数只会比较参数字符串的长度并为您完成替换工作
  • 你需要一个名字数组和一个数字数组吗?如果您有一个聚合名称和数字的结构并拥有该结构的单个数组,则此类任务会容易得多。
  • @AdamKotwasinski 它不是比较字符串长度,它只是计算字母。对每次比较都进行此计数将非常低效。
  • 战术说明:您几乎从不想显示所有代码。你想展示一个小程序,用尽可能少的额外绒毛来演示问题。制作这个小程序可以让您缩小错误范围,并在您自己发现并修复错误时尽早结束。使用minimal reproducible example 获取灵感。
  • 旁注://I attempted an algorithm I found, however I couldn't get it to function properly (Is this the proper way of solving this problem?) 这将是另一个问题,但在你问我们之前先问问自己:“除了名称 routineThree 和我知道的代码不能正常工作之外,什么都没有,是潜在的帮助者能够确定代码应该做什么,以便他们可以帮助我修复代码?”

标签: c++ arrays


【解决方案1】:

鉴于 cmets 中所说的内容,您最好先将要比较的内容(字符串中的唯一字符)与字符串一起预先计算。 然后,使用这个 enriched 输入,您可以通过比较计算的属性对其进行排序。 得到结果后,您可以删除排序依据。

#include <iostream>
#include <set>
#include <string>
#include <vector>
#include <utility>

// Counts unique chars in string.
int count_chars(const std::string& arg) {
        std::set<char> chars;
        for (auto i = 0; i < arg.size(); i++) {
                chars.insert(arg[i]);
        }
        return chars.size();
}

// Change input vector into enriched vector, keeping string with number of its unique chars.
std::vector<std::pair<std::string, int>> process(const std::vector<std::string>& arg) {
        std::vector<std::pair<std::string, int>> result = {};
        for (const auto& e : arg) {
                std::pair<std::string, int> with_count = { e, count_chars(e) };
                result.push_back(with_count);
        }
        return result;
}

int main() {
        const auto i1 = "bbbccc";
        const auto i2 = "aaaabbbbccccdddddeeeeeefffffggghhh";
        const auto i3 = "aaa";

        // This is our input.
        const std::vector<std::string> input = { i1, i2, i3 };

        // This is our input, but this time the object stored also has the unique chars counted.
        std::vector<std::pair<std::string, int>> precomputed = process(input);

        // This is our sort section.
        std::sort(precomputed.begin(), precomputed.end(), [](const auto a, const auto b) {
                // This comparison will appear somewhere in middle of manually-written sort code.
                return a.second < b.second;
        });

        // 'precomputed' is now sorted by its second attribute (unique chars' count), so we can just take the real input (first field of pair).
        std::vector<std::string> output = {};
        for (const auto& e : precomputed) {
                output.push_back(e.first);
        }

        for (const auto& e : output) {
                std::cout << e << std::endl;
        }
}

结果是:

aaa
bbbccc
aaaabbbbccccdddddeeeeeefffffggghhh

以上示例使用标准库 - 鉴于您仍在学习,您的教授很可能要求您学习如何:

  • 将字符串与其“度量”绑定(阅读struct - 我在这里使用了标准库中的std::pair);
  • 如何计算字符串中有多少个唯一字符 - 我只是使用了一个集合,但很可能您需要使用 26 元素数组左右“手动”计算它;
  • 如何排序(我使用了std::sort) - 您可以从简单的冒泡排序开始,您只需要自己对两个结构/对进行compare

【讨论】:

  • 哇,我非常感谢您的响应和背后的工作。老实说,我们还没有学到大部分这些东西,在我的 CSC101 课程中也没有。 (我觉得我们总体上真的落后了,因为我知道我已经用谷歌搜索过/等等)。 整个 csc102 类只关注封装。仅此而已。 sort函数我稍微懂了一点,但还没到会用到的程度,对vector也不是很懂。
  • 我要先声明,我不希望您向我解释其中的任何一个,我只是想告诉您,我感谢您付出的努力。我目前的行动计划(虽然优化不佳)是使用与我对int array 进行排序时相同的排序函数,除了使用 sortedNames[i].length()
  • 对,恐怕在这种情况下,您应该(需要?)保留两个向量而不是两个属性的单个向量。所以像vector&lt;string&gt; input 这样的输入数据和预先计算的vector&lt;int&gt; lengths 可以满足您的任何需求。然后就在你要做的排序代码中if (length[i] &lt; length[j]) { swap(input, i, j); swap(lengths, i, j); }
  • 是的,遗憾的是,我们班的成绩远远落后于我。我不确定它是否是特别需要的,就我得到的指示而言,我只是被告知“解决问题”。然而,我的问题来自于我对这些概念的一般理解,并且有时在他们需要帮助时不得不向班上的其他人解释它们。我不想解释一些我不完全理解 yk 用法的事情
  • CSC101 或 CSC102 都没有详细介绍 sort() 或向量,所以我所知道的只是我使用过的少数算法/概念。还没有真正解释过什么它们是或它们的功能是什么。 (部分原因是我没有看得太远)