【问题标题】:Vectors with cout operator issue in C++C++ 中带有 cout 运算符问题的向量
【发布时间】:2014-02-23 05:19:50
【问题描述】:

在我的程序中,我在尝试打印矢量的 end() 时遇到错误。代码如下:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include "inFrench.h"

using namespace std;

class student
{
    int m_studentNumber;
public:
    string nameFirst;
    string nameLast;
    string nameFull;
    int getStudentNumber() { return m_studentNumber; }
    void setStudentNumber(int studentNumber) { m_studentNumber = studentNumber; }
};

class group
{
public:
    vector<student> groupMembers;
};

ostream& operator<<(ostream& os, const student& s)
{
    return os << s.nameFirst << ' ' << s.nameLast;
}

student typeName()
{
    student bar;
    cout << "Type in a student's first name: ";
    cin >> bar.nameFirst;
    cout << "Type in that student's last name: ";
    cin >> bar.nameLast;
    bar.nameFull = bar.nameFirst + " " + bar.nameLast;
    return bar;
}

void displayStudents(student listOfStudents[50], int studentHeadCount)
{
    for (int i = 0; i < studentHeadCount; i++)
    {
        cout << listOfStudents[i].nameFull << endl;
        cout << listOfStudents[i].getStudentNumber() << endl;
        cout << "\n";
    }
}

void generateGroups(int numberOfGroups, int maxStudents, int studentsPerGroup, int remainder, group foo, student theStudents[], int studentsBeenAssigned)
{
    int k;
    numberOfGroups = maxStudents / studentsPerGroup;
    cout << numberOfGroups << endl;
    srand(time(NULL));
    while (studentsBeenAssigned << maxStudents)
    {
        for (int j = 0; j < maxStudents; j++)
        {
            k = rand() % maxStudents;
            foo.groupMembers.push_back(theStudents[k]);
            cout << foo.groupMembers.end() << endl;
            studentsBeenAssigned++;
        }
    }
    if (remainder < studentsPerGroup && remainder > 0) // Still coding this section
    {
        foo.groupMembers.push_back(theStudents[k]);
    }
}

void languageChoices()
{
    cout << "Select your language from the following:\n";
    cout << "a) English\n";
    cout << "b) French\n";
    cout << "\n";
}

void options()
{

    cout << "Select what you want to do:\n";
    cout << "1) Exit application\n";
    cout << "2) Enter a Student\n";
    cout << "3) Display Students\n";
    cout << "4) Display Groups\n";
    cout << "5) Output groups as text file\n";
    cout << "\n";
}

int main()
{
    char selectedLanguage;
    languageChoices();
    cin >> selectedLanguage;
    switch (selectedLanguage)
    {
        case 'a':
        {
            group finishedListOfStudents;
            student allStudents[50]; // Having 50 students alone is ridiculous!
            bool endProg = 0;
            int maxStudents;
            int studentsPerGroup;
            int optionSelect;
            int studentHeadCount = 0;
            int remainder = 0;
            int numberOfGroups;
            int studentsBeenAssigned;
            cout << "GroupPicker 1.0\n";
            cout << "Note: This version of the program is intended for purposes of education only, " 
            << "specifically for teacher use in a classroom.\n\n";
            cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
            cin >> maxStudents;
            if (maxStudents > 50)
            {
                cerr << "Too many students!\n" << "Exiting program...\n";
                system("PAUSE");
                exit(1);
            }
            if (maxStudents >= 35 && maxStudents <= 50)
            {
                cout << maxStudents << " students? You are a pro!\n";
            }
            cout << "How many students per group?\n";
            cin >> studentsPerGroup;
            if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
            {
                cerr << "You're kidding, right?\n" << "Exiting program...\n";
                system("PAUSE");
                exit(1);
            }
            while (endProg == 0) {
                options();
                cin >> optionSelect;
                switch (optionSelect) {
                    case 1:
                        endProg = 1;
                        break;
                    case 2:
                    {
                        if (studentHeadCount == maxStudents)
                        {
                            cerr << "You can't enter more than " << maxStudents << " students\n";
                        }
                        else
                        {
                            allStudents[studentHeadCount] = typeName();
                            allStudents[studentHeadCount].setStudentNumber(studentHeadCount);
                            cout << "Student (" << allStudents[studentHeadCount].nameFull << ") entered.\n";
                            cout << "\n";
                            studentHeadCount++;
                        }
                        break;
                    }
                    case 3:
                        cout << "Current list of students:\n\n";
                        displayStudents(allStudents, studentHeadCount);
                        break;
                    case 4:
                    {
                        if (studentHeadCount < studentsPerGroup || studentHeadCount < maxStudents)
                        {
                            cerr << "Invalid group parameters.\n" << "Returning to main menu...\n\n";
                            break;
                        }
                        else
                        {
                            cout << "Here are the groups:\n";
                            generateGroups(numberOfGroups, maxStudents, studentsPerGroup, remainder, finishedListOfStudents, allStudents, studentsBeenAssigned);
                        }
                        break;
                    }
                    case 5:
                    {
                        cout << "Saving groups to file...\n";
                        ofstream studentGroups;
                        studentGroups.open("studentGroups.txt");
                        break;
                    }
                }
            }
            break;
        }
        case 'b':
        {
            mainInFrench();
        }
    }
}

我得到以下结果:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion) [Line 66]
IntelliSense: no operator "<<" matches these operands. operand types are: std::ostream << std::_Vector_iterator<std::_Vector_val<std::_Simple_types<student>>> [Line 66]

我已经考虑过再次重载ostream operator&lt;&lt; 运算符,但是还有其他选择吗?

【问题讨论】:

  • 也请分享您的"inFrench.h"代码。
  • 你不能打印end(),因为它是一个过去的值。你可能想要back()。不过,我认为这不会导致您的编译错误。
  • @herohuyongtao 和main.cpp一样,但是文字是法语的。

标签: c++ vector operator-overloading


【解决方案1】:

std::vector::end() 返回 an iterator to the end of the vector ,而不是实际的最后一个元素。

您可以像这样打印最后一项:

cout << foo.groupMembers.at(foo.groupMembers.size() - 1);

【讨论】:

  • foo.groupMembers.back()
  • foo.groupMembers[foo.groupMembers.size() - 1)]
  • 但是向量不是不能像数组那样定位值吗?
  • @DJHead-On:不。查看std::vector 上的文档,尤其是atoperator[]This 是一个很好的参考。
【解决方案2】:

事实证明,我一开始就不需要向量。我只需要使用数组。我已经回答了我自己的问题。

【讨论】:

  • 使用矢量通常意味着以后的痛苦更少。他们负责内存管理,跟踪大小,可以确保您不会越界读/写等。如果您使用普通数组,所有这些都必须手动完成。 std::vector 通常是处理一组连续同质数据的更好选择。
  • @FredLarson 可能是这样,但就我使用它们而言,它们是完美的。
  • @DJHead-On:一旦您对vector 更加熟悉,我想您会发现它是一种更高功率、更易于使用的阵列。当然,这取决于您的预期用途,但在大多数情况下,我会选择 vector 而不是基本数组。
  • @DJHead-On:你迟早会学到其他东西。他们在这里并不完美。例如,您的班级人数限制为 50。您正在分配一个 50 人的数组,即使班级人数要小得多。向量可以精确地调整大小。如果你有一个有 200 名或更多学生的礼堂式课程怎么办?我在大学时有几个。数组在 C++ 中是一个非常低级的概念,并且充满危险。请注意,我之前的评论是一个链接。阅读链接。
  • @FredLarson 确实如此,但就像我在程序中写的那样:cout &lt;&lt; "Note: This version of the program is intended for purposes of education only, " &lt;&lt; "specifically for teacher use in a classroom.\n\n";
猜你喜欢
  • 1970-01-01
  • 2021-10-27
  • 2011-09-30
  • 1970-01-01
  • 2011-06-15
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多