简体   繁体   English

为什么我不能使用范围 for 循环打印对象向量的内容?

[英]Why can't I print contents of vector of objects using a ranged for loop?

I'm a beginner and I solved an exercise involving 10 pie eaters with number of pies eaten set by user input.我是一个初学者,我解决了一个涉及 10 个吃馅饼的人的练习,其中吃的馅饼数量由用户输入设置。

  1. 1st task: Display Contestant number and pies eaten - Solved;第一项任务:显示参赛者人数和吃的馅饼 - 已解决;
  2. 2nd task: Find winners with most pies eaten and list all - Solved;第二项任务:找到吃掉馅饼最多的获胜者并列出所有 - 已解决;
  3. 3rd task: Find losers with least pies eaten and list all - Solved;第三项任务:找到吃掉馅饼最少的失败者并列出所有 - 已解决;
  4. Final task: Sort Contestants and list them in order of most pies to least pies eaten - Partially Solved.最后的任务:对参赛者进行排序并按照吃的最多的馅饼的顺序列出他们 - 部分解决。

I did everything, no errors or warnings (even stepping over/ into in debugger showed that the vector was sorted correctly), but right when I try to print out the sorted vector, the console screen just won't display anything more (not even the standard message that program execution is finished).我做了所有事情,没有错误或警告(甚至在调试器中跨步/进入显示向量已正确排序),但是当我尝试打印出排序后的向量时,控制台屏幕将不再显示任何内容(甚至程序执行完成的标准消息)。

I made a Contestant class with constructor Contestant with two arguments, and declared a vector of objects.我用构造函数 Contestant 和两个 arguments 创建了一个 Contestant class,并声明了一个对象向量。 Here's the code in main, class header and class solution:这是主要的代码,class header 和 class 解决方案:

#include <iostream>
#include <vector>
#include "Contestant.h"
using namespace std;

int main()
{
    cout << "Type the number of pies eaten by each of the 10 contestants:" << endl;
    cout << "#1 #2 #3 #4 #5 #6 #7 #8 #9 #10" << endl;

    vector<Contestant> pie_eaters;
    vector<Contestant*> winners; 
    vector<Contestant*> losers; 


    for (int i=0; i<10; i++)
    {
       int pies_eaten;
       cin >> pies_eaten;
       pie_eaters.emplace_back(i+1, pies_eaten);
       cout << "Contestant number " << i+1 << " ate " << pie_eaters[i].GetPancakes() << endl;
    }
    cout << endl;


    FindWinners(pie_eaters, winners);
    ListWinners(winners);

    FindLosers(pie_eaters, losers);
    ListLosers(losers);


    cout << endl;

    SortPieEaters(pie_eaters);

    ListSortedPieEaters(pie_eaters);


}

Class header (edited, just for the sorting and printing out, which are outside the class): Class header(已编辑,仅用于排序和打印,属于课外):

#pragma once
#include <iostream>
#include <vector>

class Contestant
{
private: 
    int pancakes_eaten;
    int number;

public:
    Contestant(int number, int pancakes);

    ~Contestant();
    int GetPancakes() const { return pancakes_eaten; }
    int GetNumber() const { return number; }

};


void SortPieEaters(std::vector<Contestant>& pie_eaters);

void ListSortedPieEaters(std::vector<Contestant> const& pie_eaters);

and Class solution (just the sorting and printing out parts, which are outside the class):和 Class 解决方案(只是分类和打印出来的部分,在类之外):

#include "Contestant.h"

using namespace std;

Contestant::Contestant(int number, int pancakes) : pancakes_eaten(pancakes), number(number)
{
}

Contestant::~Contestant() {};


void SortPieEaters(vector<Contestant>& pie_eaters)
{
    while(bool swapped=true)
        {
        swapped = false;
           for (int i = 0; i < static_cast<int>(pie_eaters.size()-1); i++)
           {
                if (pie_eaters[i].GetPancakes() < pie_eaters[i + 1].GetPancakes())
                {
                    swap(pie_eaters[i], pie_eaters[i + 1]);
                    swapped = true;
                }

           }
        }
}

void ListSortedPieEaters(vector<Contestant> const& pie_eaters)
{
    cout << "From most pies eaten, to fewest pies eaten, the results are as follows:" << endl;
    for (auto const& c : pie_eaters)
    {
        cout << "Contestant #" << c.GetNumber() << ": ate " << c.GetPancakes() << " pies" <<endl;

    }
}

And lastly, here's and example output: Output最后,这里是示例 output: Output

Everything works fine, but it won't print out the vector or warn there are any issues with it.一切正常,但它不会打印出矢量或警告它有任何问题。 Tried, everything like passing by constant or non-constant reference, tried writing the body of the function directly in main(avoiding the function), but nothing.尝试过,通过常量或非常量引用传递所有东西,尝试直接在 main 中编写 function 的主体(避免该函数),但没有。 And accessing the vector and printing out content was the same as in the case of the winner and losers vectors (even though they are vectors of pointers to the object elements of the pie eaters vector)并且访问向量并打印出内容与赢家和输家向量的情况相同(即使它们是指向馅饼向量的 object 元素的指针向量)

What am I doing wrong?我究竟做错了什么?

That is because the while loop never ends, since you have initialized the value of swapped = true in the while loop condition, the value of swapped becomes true when the inner for loop ends and the while loop is reprocessed.那是因为 while 循环永远不会结束,因为您已经在 while 循环条件中初始化了swapped = true的值,所以当内部 for 循环结束并且重新处理 while 循环时, swapped的值变为 true。

The program never leaves the while loop.程序永远不会离开 while 循环。 thus, the line never executes因此,该行永远不会执行

SortPieEaters(pie_eaters); //Executes

ListSortedPieEaters(pie_eaters); //does not execute

You could just do你可以做

bool swapped = true;
while(swapped)
{
    swapped = false;
    for (int i = 0; i < static_cast<int>(pie_eaters.size()-1); i++)
    {
        if (pie_eaters[i].GetPancakes() < pie_eaters[i + 1].GetPancakes())
        {
            swap(pie_eaters[i], pie_eaters[i + 1]);
            swapped = true;
        }
    }
}

Also, I would suggest you to change your sorting logic to something simpler by overloading < in the Contestant class and using std::sort instead另外,我建议您通过在Contestant class 中重载 < 并改用std::sort来将排序逻辑更改为更简单的东西

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

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