Работа с очередями и ООП (C++)

255
29 июня 2018, 05:10

Дан текстовый файл с изображением целых чисел, которые необходимо переписать в очередь Qu1. В очередь Qu2 сначала записать числа палиндромы, затем числа, сумма цифр которых нечетная, остальные числа записать в выходной файл. Создать программу с применением методов ООП.

Сделал что смог, но появилось много ошибок... Прошу вашей помощи!

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <queue>
#include <fstream>
#include <algorithm>
#include <iterator>
using namespace std;
unsigned getReverse(unsigned n) {
    unsigned r = n % 10;
    while (n /= 10) {
        r = r * 10 + n % 10;
    }
    return r;
}
bool isPalindrom(const unsigned n) {
    return n == getReverse(n);
}
class cQueue
{
protected:
    queue<int> p_;
public:
    void IO();
    void Del()
    {
        while (!p_.empty())
        {
            p_.pop();
        }
    };
};
void cQueue::IO()
{
    ifstream ifile("text.txt");
    ofstream ofile("output.txt", ios::trunc);
    queue<int> qu1 = p_;
    for_each(istream_iterator<int>(ifile), istream_iterator<int>(), [&qu1](int n)
    {
        qu1.push(n);
    });
    cout << "Number of items in the queue: " << qu1.size() << endl;
    while (!qu1.empty())
    {
        cout << "\nHere they are: " << qu1.front() << '\n';
    }
    queue<int> qu2;
    copy_if(queue<int>(qu1), queue<int>(), queue<int>(qu2), [&qu1](int n) -> bool
    {
        if (isPalindrom(n)) {
            return n;
        }
        else if (n) {
            // Сумма нечетных чисел ?
        }
        else
        {
            // В выходной файл ?
        }
    });
    cout << "Number of items in the queue: " << qu2.size() << endl;
    while (!qu2.empty())
    {
        cout << "\nHere they are: " << qu2.front() << '\n';
    }
}

int main()
{
    cout << "Demo Queue OOP" << endl;
    cQueue queue;
    queue.IO();
    cout << endl;
    queue.Del();
    _getch();
    return 0;
}

Ошибка C2675 унарный "++": "std::queue>>" не определяет этот оператор или преобразование к типу приемлемо к встроенному оператору \algorithm 594

Ошибка C2100 недопустимое косвенное обращение \algorithm 596

Ошибка C2100 недопустимое косвенное обращение \algorithm 598

Ошибка C2675 унарный "++": "std::queue>>" не определяет этот оператор или преобразование к типу приемлемо к встроенному оператору \algorithm 599

Ошибка C4996 'std::copy_if::_Unchecked_iterators::_Deprecate': Call to 'std::copy_if' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators' \algorithm 589

Answer 1
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
struct IsPoli {
    bool operator()(const int i)
    {
        string s = to_string(i), t = s;
        std::reverse(t.begin(), t.end());
        return  s == t;
    }
};
struct CheckSum {
    bool operator()(int n)
    {
        int count{};
        while(n) {
            if(n & 1) ++count;
            n /= 10;
        }
        return (count & 1);
    }
};
int main()
{    
    ifstream ifile("text.txt");
    ofstream ofile("output.txt");
    queue<int> Qu1, Qu2;
    for_each(istream_iterator<int>(ifile), istream_iterator<int>(),
             [&](const int& i) { Qu1.push(i);});
    IsPoli p;
    CheckSum cmp;
    int k{};
    vector<int> v;
    while(!Qu1.empty()) {
        k = Qu1.front();
        if (!p(k) && !cmp(k))
            ofile << k << ' ';
        else if (p(k)){
            Qu2.push(k);
        } else
            v.emplace_back(k);
        Qu1.pop();
    }
    for (const int& i :v)
        Qu2.push(i);
    // дальше можно показать содержимое второй очереди
    while(!Qu2.empty()) {
        cout << endl << Qu2.front();
        Qu2.pop();
    }
    return 0;
}
Answer 2

Свой copy_if для очередей сделать надо. Или не пользоваться очередями.

std::queue<int> input;
...
std::queue<int> result;
std::queue<int> inputcopy(input);
while(not input_copy.empty()){
  if(...) result.push(input_copy.front());
  input_copy.pop();}
READ ALSO
C++ Передача списка va_list в функцию

C++ Передача списка va_list в функцию

Подскажите, как реализовать функцию:

237
Холивар по поводу реализации. С++ и Qt

Холивар по поводу реализации. С++ и Qt

Есть объект A который владеет объектом B (объявляется и инициализируется в конструкторе объекта A и является членом объекта A)

243
Перезапуск цикла через n секунду

Перезапуск цикла через n секунду

Есть приложение, реализующее обработку изменяющегося файлаНа форме есть кнопки "Старт" и "Стоп" меняющие значение переменной active

249