Проблема с оператором << в классе StringSet - PullRequest
0 голосов
/ 07 марта 2020

Я определяю свой собственный класс строк с именем StringSet, используя вектор строк. Мне назначена перегрузка операторов >>, <<, ==, >, >=, +, += и *, и возникла проблема с <<. Вывод должен быть:

Welcome to stringset

hi everyone

"all" does not exist in the set.

hi

Но, похоже, пропускаются вторая и третья строки. Я очень плохо знаком с перегрузкой операторов, поэтому я, вероятно, пропускаю очевидную ошибку.

объявление заголовка и класса:

#include <iostream>
#include <vector>
#include<string>
#include <iterator>
#include <algorithm>
#include <fstream>
using namespace std;

class StringSet
{
public:
    //Constructor
    StringSet();

    //Copy Constructor
    StringSet(const StringSet& s);

    //Default constructors
    StringSet(string initialStrings[], const int ARRAYSIZE);

    //Destructor
    ~StringSet();

    void add(const string s);
    void remove(const string s);

    //Returns length
    int size()
    {
       return length;
    }

    // Overload the << operator so that it outputs the strings
    friend ostream& operator <<(ostream& outs, const StringSet& s);

private:
    //size of the vector
    int length;
    // Vector to store strings
    vector <string> data;
};

определения функций:

ostream& operator<<(ostream& outs, const StringSet& s) 
{
    outs << "\n";
    for (int i = 0; i < s.length; i++)
    {
        outs << s.data[i] << " ";
    }
    outs << "\n";
    return outs;
}

//Add a string to the vector
void StringSet::add(const string s)
{
    bool c = check(s);
    if (c == false)
    {
        data.push_back(s);
    }
    else
    {
        cout << "\"" << s << "\" already exists in the set.";
    }
}

// Remove a string from the vector 
void StringSet::remove(const string s)
{
    bool c = check(s);
    if (c == true)
    {
        vector<string>::iterator position = search(s);
        data.erase(position);
    }
    else
    {
        cout << "\"" << s << "\" does not exist in the set\n";
    }
}

StringSet::StringSet()
{
    length = 0;
}

StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
    for (int i = 0; i < data.size(); i++)
    {
        initialStrings[i] = " ";
    }
}

// Copy constructor
StringSet::StringSet(const StringSet& s)
{
    for (int i = 0; i < data.size(); i++)
    {
        data[i] = s.data[i];
    }
}

StringSet::StringSet()
{
    length = 0;
}

StringSet::StringSet(string initialStrings[], const int ARRAYSIZE)
{
    for (int i = 0; i < data.size(); i++)
    {
        initialStrings[i] = " ";
    }
}

// Copy constructor
StringSet::StringSet(const StringSet& s)
{
    for (int i = 0; i < data.size(); i++)
    {
        data[i] = s.data[i];
    }
}

// Check if a string exists in the vector
bool StringSet::check(const string s)
{
    vector<string>::iterator it = find(data.begin(), data.end(), s);
    if (it != data.end())
    {
        return true;
    }
    else
    {
        return false;
    }
}

Main функция:

int main()
{
    ofstream outs;
    ifstream ins;
    StringSet doc1, doc2, query

    cout << "Welcome to stringset\n";
    doc1.add("hi");
    doc1.add("everyone");
    outs << doc1;
    doc1.remove("everyone");
    doc1.remove("all");
    outs << doc1;
}

1 Ответ

2 голосов
/ 08 марта 2020

Если вы используете переменную, которая хранит размер набора, вы должны увеличивать / уменьшать ее при добавлении / удалении элементов. Вы также можете изменить определение StringSet::size():

int size() const
{
    return static_cast<int>(data.size());
}
...