简体   繁体   English

我的代码有什么问题? 没有得到正确的 C++ 程序的 output

[英]What is the issue in my code? Not getting correct output of C++ program

I'm not getting the correct output of my elab question.我的 elab 问题没有得到正确的 output 。 Here's the question:这是问题:

There are faculties in the department, you have to arrange the list of faculties depending upon ID numbers.系里有院系,你要根据身份证号来安排院系名单。

TEST CASE 1测试用例 1

INPUT输入

5 Ram 101 Rahul 95 Ashwin 75 Ahamed 106 Saurav 110

OUTPUT OUTPUT

 After Sorting Name ID Ashwin 75 Rahul 95 Ram 101 Ahamed 106 Saurav 110

Here's the code I implemented using structures:这是我使用结构实现的代码:

#include<bits/stdc++.h>
#include<iostream>

using namespace std;

struct faculty{
  string name;
  int id;
};

int main(){
  int n;
  struct faculty arr[n];
  for(int i=0;i<n;i++){
    cin>>arr[i].name;
    cin>>arr[i].id;
  }
  cout<<"After Sorting"<<endl;
  cout<<"Name ID"<<endl;
  
  //insertion sort
  for(int i=1;i<n;i++){
    struct faculty key=arr[i];
    int j=i-1;
    while(j>=0 && arr[j].id>key.id)
    {
      arr[j+1]=arr[j];
      j--;
    }
    arr[j+1]=key;
  }
  
  //printing
  for(int i=0;i<n;i++){
    cout<<arr[i].name<<" "<<arr[i].id;
  }
  return 0;
}

My output:我的 output:

After Sorting
Name ID
5 0

Can someone help me?有人能帮我吗? I can't figure out what the mistake is.我无法弄清楚错误是什么。

First, some analysis for your code:首先,对您的代码进行一些分析:

  • Do not ever use #include<bits/stdc++.h> .永远不要使用#include<bits/stdc++.h> This is non-compliant C++ code.这是不兼容的 C++ 代码。 It will not work with other compilers它不适用于其他编译器
  • Do not use using namespace std;不要使用using namespace std; . . Always prefer using the scope explicitly总是更喜欢明确使用 scope
  • Always initialize all variables.始终初始化所有变量。 There should not be any exception不应该有任何例外
  • Do not use C-style arrays in C++ code.不要在 C++ 代码中使用 C 风格的 arrays。 Never.绝不。 There is no reason for that没有理由这样做
  • VLA (Variable length arrays) are non-standard in C++. VLA(可变长度数组)在 C++ 中是非标准的。 ( arr[n] ) ( arr[n] )
  • Enable all warnings for your compiler, like with for example -std=c++14 -Wall -Wextra -Wpedantic为您的编译器启用所有警告,例如-std=c++14 -Wall -Wextra -Wpedantic
  • Use existing containers from the standard library, like std::vector使用标准库中的现有容器,例如std::vector

Concrete errors:具体错误:

  • You forgot to read n你忘了读 n
  • You must replace the VLA by a std::vector您必须用std::vector替换 VLA
  • You need to add a new line after outputting one record输出一条记录后需要添加新行

So, your fixed software would look like this:因此,您的固定软件将如下所示:

#include<iostream>
#include <string>
#include <vector>

struct faculty {
    std::string name;
    int id;
};

int main() {
    int n;
    std::cin >> n;
    std::vector<faculty> arr(n);
    for (int i = 0; i < n; i++) {
        std::cin >> arr[i].name;
        std::cin >> arr[i].id;
    }
    std::cout << "After Sorting" << std::endl;
    std::cout << "Name ID" << std::endl;

    //insertion sort
    for (int i = 1; i < n; i++) {
        faculty key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j].id > key.id)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }

    //printing
    for (int i = 0; i < n; i++) {
        std::cout << arr[i].name << " " << arr[i].id << '\n';
    }
    return 0;
}

But this is not the preferred solution.但这不是首选的解决方案。

You should tackle your problem in a different way to come to a better solution.您应该以不同的方式解决您的问题,以获得更好的解决方案。

First, we need to initialize WHAT to do.首先,我们需要初始化要做什么

  1. We need to address data that consists of "name" and "ID"我们需要处理由“名称”和“ID”组成的数据
  2. Reading this data from a stream, like std::cin must be possible从 stream 读取此数据,如std::cin必须是可能的
  3. Outputting the data is necessary需要输出数据
  4. The number of members with name and ID shall be read from the user名称和ID的成员数量应从用户处读取
  5. All data shall be stored for further evaluation应存储所有数据以供进一步评估
  6. The number of entries, as specified above, shall be read应读取上述条目的数量
  7. Data must be sorted by the ID数据必须按ID排序
  8. The result shall be printed on std::cout结果应打印在std::cout

Next, we need to think on HOW we can fullfill the requirements.接下来,我们需要考虑如何满足需求。 We do not write any code yet.我们还没有编写任何代码。 Ok, lets's see:好的,让我们看看:

  1. For storing that data, we will use a struct, with a std::string for the name and an unsigned int for the ID, because, we assume that the ID will never be negative.为了存储该数据,我们将使用一个结构体,名称为std::string ,ID 为unsigned int ,因为我们假设 ID 永远不会是负数。
  2. In an object-oriented approach, we keep data and methods operating on that data together.在面向对象的方法中,我们将数据和操作该数据的方法放在一起。 So reading and writing will be defined as a method in a struct.所以读和写将被定义为结构中的一个方法。 And to save work, we simply overwrite the extractor operator >> .为了节省工作,我们只需覆盖提取器运算符>> So, we can read the data now from any stream.因此,我们现在可以从任何 stream 读取数据。
  3. For output purposes, we also overwrite the inserter operator << .出于 output 的目的,我们还覆盖了插入操作符<<
  4. We need to read the number of members.我们需要读取成员的数量。 We read n, then use an if - statement and check, if that worked.我们读取 n,然后使用if - 语句并检查是否有效。
  5. The number of elements is given by the user and can be anything.元素的数量由用户给出,可以是任何东西。 So, we need a dynamic container which can grow in size.所以,我们需要一个可以扩大规模的动态容器。 We will use a std::vector for that.我们将为此使用std::vector
  6. Now, we must read the specified number of entries.现在,我们必须读取指定数量的条目。 This will call the extractor operator这将调用提取器操作员
  7. Sort the data对数据进行排序
  8. Show the sorted data on the screen, by outputting all data from vector.通过输出向量中的所有数据,在屏幕上显示排序后的数据。 This will call the inserter operator.这将调用插入器运算符。

OK, we clarified the WHAT and the HOW.好的,我们澄清了 WHAT 和 HOW。 Now (not before), we can start coding.现在(不是之前),我们可以开始编码了。

Unfortunately, there are millions of possible solutions.不幸的是,有数百万种可能的解决方案。 I will show a more advanced version, but you can implement anything according to your needs.我将展示一个更高级的版本,但您可以根据需要实现任何内容。

Please see the below example:请看下面的例子:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct Faculty {
    // 1. Our data. Initiliaze with default
    std::string name{};
    unsigned int id{};
    // 2. Define extractor operator for this data
    friend std::istream& operator >> (std::istream& is, Faculty& f) {
        return is >> f.name >> f.id;
    }
    // 3. Define inserter operator for this data
    friend std::ostream& operator << (std::ostream& os, const Faculty& f) {
        return os << f.name << '\t' << f.id;
    }
};

int main() {
    // 4. Get the number of members that we should read, and check, if input worked
    size_t numberOfMembers{};
    if (std::cin >> numberOfMembers) {

        // 5. Here we will store all data
        std::vector<Faculty> data{};

        // 6. Copy all data from std::cin into our data vector
        std::copy_n(std::istream_iterator<Faculty>(std::cin), numberOfMembers, std::back_inserter(data));

        // 7. Sort according to ID
        std::sort(data.begin(), data.end(), [](const Faculty& f1, const Faculty& f2) { return f1.id < f2.id; });

        // 8. Output
        std::copy(data.begin(), data.end(), std::ostream_iterator<Faculty>(std::cout, "\n"));
    }
    return 0;
}

To be compiled with C++14 enabled.编译时启用 C++14。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM