且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以从此代码中打印出特定的行?

更新时间:2023-11-24 18:41:40


上一点:


Previous point:

正如注释部分 using namespace std; 所指出的那样,这是一个错误的选择,您的代码中有一个示例,说明了为什么重新定义更大的原因之一>已经存在于名称空间中.

As was noted in the comment section using namespace std; is a bad choice and your code has an example of one of the reasons why that is, the redefinition of greater which is already present in the namespace.

提供的链接具有进一步的说明和替代方法.

The provided link has further explanation and alternatives.

对于您的代码,据我所知,如果目标是从 CC 开始不带选项的行(按 GPA 排序),则更简单例如,您可以使用 std :: find 只能解析开头为"CC" 的行,然后从那里开始工作.
您还可以使用 std :: string :: starts_with ,但是它仅在C ++ 20中可用,因此我将选择第一个选项.

As for you code, if the goal is to output the lines, starting with CC without the options, ordered by GPA, as I understand it, there are simpler ways of doing it, for instance, you can use std::find to parse only lines with "CC" at its beginning and work from there.
You could also use std::string::starts_with however it's only available with C++20, so I'll go with the first option.

实时演示

int main()
{
    std::vector<std::string> v;

    std::ifstream File;
    File.open("DSA.txt");
    if (!File.is_open())
        return EXIT_FAILURE;

    std::string line;

    while (File >> line)
    {
        if (line.find("CC") == 0)    // find lines that start with CC
            v.push_back(&line[9]);   // add lines without the options
    }                                // or v.push_back(line.substr(9));

    sort(v.begin(), v.end(), std::greater<std::string>()); //sort the lines

    std::cout << "GPA" << "\t" << "Name" <<"\n\n"; // Title for the table
    for (auto& str : v) //print the lines
    {   
        std::replace(str.begin(), str.end(), ',', '\t'); //let's replace de comma
        std::cout << str << "\n";
    }
    return EXIT_SUCCESS;
}

获取样本,将输出:

GPA    Name

3.9    MuruArun
3.7    DamianKoh
3.3    MattWiliiams
3.3    IrfanMuhaimin

带有"CC"的行第二个或第三个选项将不会被解析,这是我们的目标.

Lines with "CC" in second or third options will not be parsed, as is our goal.

注意:

这种按字符串的排序方法是可行的,并且在这种情况下可以使用,因为 GPA 的值小于10,否则我们将不得不转换 GPA 字段并对字符串进行排序按其值 eg 排列:10大于9,但作为字符串将首先排序,因为按字典顺序排序,9被认为较大,字符9较大比字符1.

This sorting method by string is possible and works in this case because the GPA values are lower than 10, otherwise we would have to convert the GPA field and sort the lines by its value, e.g.: 10 is larger than 9 but as a string it would be sorted first because lexicographicaly ordered, 9 would be considered larger, the character 9 is larger than the character 1.

如您所见,我使用了默认的 更大 模板,在这种情况下,您无需自己制作模板,只需使用此模板即可.

As you can see I used the default greater template, in this case you don't need to make your own, you can just use this one.

还有一件事, main 必须具有 int 返回类型.

One more thing, main must have int return type.