1 / 1 / 1
Регистрация: 29.11.2013
Сообщений: 46
1

Не могу разобраться с сортировкой

20.12.2013, 16:24. Показов 748. Ответов 19
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "stdafx.h"
#include <iostream>
#include <locale.h>
#include <string>
using namespace std;
int f=0;
struct price{
    char n[20];
    char s[20];
    int c;
    int g;
    char k[20];
}m[10];
 
void input(int n){
    f=f+n;
    for(int i=f;i<f+n;i++){
    cout << "Введите название товара: ";
    cin >> m[i].n;
    cout << "Введите страну изготовитель: ";
    cin >> m[i].s;
    cout << "Введите год выпуска: ";
    cin >> m[i].g;
    cout << "Введите цену: ";
    cin >> m[i].c;
    cout << "Введите название магазина: ";
    cin >> m[i].k;}
    return;
}
void sortirovka(price m[],int x){
    for(int i=0;i<x;i++){
        for(int j=i+1;j<x;j++){
            if(m[i].c>m[j].c){
                price temp=m[i];
                m[i]=m[j];
                m[j]=temp;}}}
return;
}
 
void vivod(int c){
    for(int i=0;i<f;i++){
    cout << " Товар: " <<m[i].n << " Страна: " <<m[i].s << " Год: " <<m[i].g << " Цена: " <<m[i].c << " Магазин: " <<m[i].k <<endl;}
    return;
}
 
void vibor(int z,int p){
    int y=10;
    for(int i=0;i<p;i++){
        if(m[i].c==z){ cout << " Товар: " << m[i].n << " Магазин: " << m[i].k << endl;
        y--;}}
    if(y==10) cout << "Товаров с ценой " << z << " нет" << endl;
    return;}
int _tmain(int argc, _TCHAR* argv[])
{setlocale(LC_ALL,"Russian");
int a,d,k;
for(;;){
    cout << "Выберете действие:\n"<< "1.Ввод\n" << "2.Вывод\n" <<  "3.Вывод по цене\n" << "4.Выход\n" << endl;
    cin >> a;
    if(a==1){ cout << "Введите кол-во записей: ";
        cin >> k;
        if(k>10) cout << "Перебор\n";
        else {
        input(k);
        sortirovka(m,10);}}
    else if(a==2) vivod(k);
    else if(a==3){ cout << "Введите цену: ";
                    cin >> d;vibor(d,k);}
    else if(a==4) break;}
return 0;}
Проблема в том что в функции sortirovka, я вроде как должен сортировать по возрастанию цены, но при выводе нет никаких записей.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.12.2013, 16:24
Ответы с готовыми решениями:

Не могу разобраться с сортировкой
Пытаюсь сделать сортировку товаров. Застрял на одном моменте. Предположим, у товара есть какая-то...

Не могу разобраться с сортировкой даты в Stringgrid, чтобы при вводе дд.мм.гггг сначала смотрело на год, потом на месяц, потом на день
Добрый вечер. Не могу разобраться с сортировкой даты в Stringgrid, чтобы при вводе дд.мм.гггг...

Задали работу, не могу разобраться. Используется делфи 10, не могу разобраться, как это сделать
В одномерном массиве, состоящем из n вещественных элементов, вычислить: минимальный элемент массива...

Разобраться с сортировкой вставками
1) разобраться с сортировкой вставками. void insertSort(int a, int size) { int x; int i, j;...

19
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
20.12.2013, 16:35 2
Отформатируй код, может поймешь.

Не по теме:

Мне влом в таком коде что-то искать.

0
1 / 1 / 1
Регистрация: 29.11.2013
Сообщений: 46
20.12.2013, 16:40  [ТС] 3
Спасибо!
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "stdafx.h"
#include <iostream>
#include <locale.h>
#include <string>
 
 
using namespace std;
int f=0;
 
struct price{
    char n[20];
    char s[20];
    int c;
    int g;
    
    char k[20];
}m[10];
 
void input(int n){
    f=f+n;
    for(int i=f;i<f+n;i++){
    cout << "Введите название товара: ";
    cin >> m[i].n;
    cout << "Введите страну изготовитель: ";
    cin >> m[i].s;
    cout << "Введите год выпуска: ";
    cin >> m[i].g;
    cout << "Введите цену: ";
    cin >> m[i].c;
    cout << "Введите название магазина: ";
    cin >> m[i].k;}
    return;
}
 
void sortirovka(price m[],int x){
    for(int i=0;i<x;i++){
        for(int j=0;j<x;j++){
            if(m[i].c>m[j].c){
                price temp=m[i];
                m[i]=m[j];
                m[j]=temp;}}}
return;
}
 
void vivod(int c){
    for(int i=0;i<f;i++){
    cout << " Товар: " <<m[i].n << " Страна: " <<m[i].s << " Год: " <<m[i].g << " Цена: " <<m[i].c << " Магазин: " <<m[i].k <<endl;}
    return;
}
 
void vibor(int z,int p){
    int y=10;
    for(int i=0;i<p;i++){
        if(m[i].c==z){ cout << " Товар: " << m[i].n << " Магазин: " << m[i].k << endl;
        y--;}}
    if(y==10) cout << "Товаров с ценой " << z << " нет" << endl;
    return;
}
 
 
 
int _tmain(int argc, _TCHAR* argv[])
{setlocale(LC_ALL,"Russian");
int a,d,k;
for(;;){
    cout << "Выберете действие:\n"<< "1.Ввод\n" << "2.Вывод\n" <<  "3.Вывод по цене\n" << "4.Выход\n" << endl;
    cin >> a;
    if(a==1){ cout << "Введите кол-во записей: ";
        cin >> k;
        if(k>10) cout << "Перебор\n";
        else {
        input(k);
        sortirovka(m,10);}
    }
    else if(a==2) vivod(k);
    else if(a==3){ cout << "Введите цену: ";
                    cin >> d;
                vibor(d,k);
    }
    else if(a==4) break;
}
return 0;
}
0
Программист
307 / 182 / 176
Регистрация: 05.12.2013
Сообщений: 683
Записей в блоге: 5
20.12.2013, 16:50 4
C++
1
2
3
4
5
void vivod(int c){
    for(int i=0;i<f;i++){
    cout << " Товар: " <<m[i].n << " Страна: " <<m[i].s << " Год: " <<m[i].g << " Цена: " <<m[i].c << " Магазин: " <<m[i].k <<endl;}
    return;
}
Вы передаете в процедуру c, а в ней он не используется, зато используется f.

Не по теме:

Код отвратительный.

0
1 / 1 / 1
Регистрация: 29.11.2013
Сообщений: 46
20.12.2013, 16:59  [ТС] 5
Пишу как умею(даже скорее как учат), а f исправил все равно разницы нет.
0
1130 / 789 / 232
Регистрация: 12.04.2010
Сообщений: 2,012
20.12.2013, 19:00 6
Цитата Сообщение от Demon55 Посмотреть сообщение
при выводе нет никаких записей.
Какие значения переменных k, f когда нет записей при выводе? (Добавим cout << k ... перед выводом меню и int k=0 перед for(...) )
C++
1
2
3
4
int a,d,k=0;
for( ; ; ){
    cout << "\n k == " << k << "      f == " << f << "\n\n";
    cout << "Выберете действие:\n"<< "1.Ввод\n" << "2.Вывод\n" <<  "3.Вывод по цене\n" << "4.Выход\n" << endl;
Сейчас ввёл 3 записи. Вот результат - см.рис.
Миниатюры
Не могу разобраться с сортировкой  
0
1 / 1 / 1
Регистрация: 29.11.2013
Сообщений: 46
20.12.2013, 19:12  [ТС] 7
Значения 2, а вывод должен был быть по возрастанию цены...
0
Заблокирован
20.12.2013, 20:24 8
?//

Добавлено через 3 минуты
Цитата Сообщение от Demon55 Посмотреть сообщение
if(m[i].c>m[j].c){
это поиск максимального элемента, или я не прав?
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
20.12.2013, 20:46 9
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
Input test:
1
3
Товар1
Изготовитель1
Страна1
Год1
1
Магазин1
Товар3
Изготовитель2
Страна3
Год3
3
Магазин3
Товар2
Изготовитель3
Страна2
Год2
2
Магазин2
2
3
2
3
4
 
 */
 
#include <iostream>
#include <cstdlib>
 
typedef struct {
    char n[20], s[20];
    int c, g;
    char k[20];
} price;
 
int f = 0;
price m[10];
 
void input(int n) 
{
    f = f + n;
    for(int i = f; i < f + n; ++i) 
    {
        std::cout << "Введите название товара: ";
        std::cin >> m[i].n;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> m[i].s;
        std::cout << "Введите год выпуска: ";
        std::cin >> m[i].g;
        std::cout << "Введите цену: ";
        std::cin >> m[i].c;
        std::cout << "Введите название магазина: ";
        std::cin >> m[i].k;
    }
    return;
}
 
// прочтите как переменные передаются в функцию
// так как вы передаете копию объекта вместо ссылки
// или указателя на него
void sortirovka(price *m, int x)
{
    for (int i = 0; i < x; ++i)
        for (int j = 0; j < x; ++j)
            if (m[i].c > m[j].c)
            {
                price temp = m[i];
                m[i] = m[j];
                m[j] = temp;
            }
}
 
void vivod(int c)
{
    for (int i = 0; i < f; ++i) 
    {
        std::cout   << " Товар: "  << m[i].n 
                    << " Страна: "    << m[i].s 
                    << " Год: "  << m[i].g 
                    << " Цена: "    << m[i].c 
                    << " Магазин: "<< m[i].k << std::endl;
    }
}
 
// для индикации достаточно булевого значение
// int таскать не обязательно
void vibor(int z, int p)
{
    bool flag(false);
    for (int i = 0; i < p; ++i)
    {
        if (m[i].c == z) { 
            std::cout << " Товар: " << m[i].n << " Магазин: " << m[i].k << std::endl;
            flag = true;
        }
    }
    if (flag == false) {
        std::cout << "Товаров с ценой " << z << " нет" << std::endl;
    }
}
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    int a, d, k;
    bool running(true);
 
    while (running) 
    {
        // раз уж взялись писать юниксовые переводы строк
        // не надо еще универсальный сюда же писать
        // \n и std::endl
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> a;
 
        // вместо кучи if...else... лучше написать switch
        switch (a)
        {
        case 1:
            std::cout << "Введите кол-во записей: ";
            std::cin >> k;
            if (k > 10) std::cout << "Перебор\n";
            else 
            {
                input(k);
                sortirovka(m, 10);
            }
            break;
        case 2:
            vivod(k);
            break;
        case 3:
            std::cout << "Введите цену: ";
            std::cin >> d;
            vibor(d, k);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
Форматирование кода решает.
1
1130 / 789 / 232
Регистрация: 12.04.2010
Сообщений: 2,012
20.12.2013, 21:16 10
Цитата Сообщение от outoftime Посмотреть сообщение
// прочтите как переменные передаются в функцию
// так как вы передаете копию объекта вместо ссылки
// или указателя на него
void sortirovka(price *m, int x)
Если параметр массив, то в функцию передаётся указатель на него. Здесь у Demon55, правильно.
C++
1
2
3
/*эти записи эквивалентны*/
void sortirovka(price *m, int x)
void sortirovka(price m[], int x)
Сортировка по возрастанию
C++
1
2
3
4
5
6
7
8
9
10
11
12
void sortirovka(price m[],int x){
    for(int i=0;i<x;i++){
 
        for(int j = i+1;j<x;j++){
        //for(int j=0;j<x;j++){  // error 
 
            if(m[i].c>m[j].c){
                price temp=m[i];
                m[i]=m[j];
                m[j]=temp;}}}
return;
}
1
1 / 1 / 1
Регистрация: 29.11.2013
Сообщений: 46
20.12.2013, 21:33  [ТС] 11
Я уже пробовал так описывать сортировку, выводит пустые поля.
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
20.12.2013, 21:41 12
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void sort();
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            store.sort();
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "  << value.name 
        << " Страна: "    << value.manufacture
        << " Год: "      << value.year 
        << " Цена: "    << value.price
        << " Магазин: "  << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (auto it = value.begin(); it != value.end(); ++it)
        out << (*it);
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::sort() 
{
    std::sort(begin(), end(), [](const GoodsItem &value1, const GoodsItem &value2)
    {
        return value1.price > value2.price;
    });
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (auto it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}
Я правда не нашел какой оператор надо перегрузить для GoodsItem что-бы std::sort не надо было передавать компаратор.
Компилировать с флагом -std=c++11

Добавлено через 2 минуты
Demon55, оба мои варианта - рабочие.
Alex5, у него проблема была не в том что сортирует по убыванию.
0
413 / 250 / 118
Регистрация: 26.12.2012
Сообщений: 787
20.12.2013, 22:31 13
Alex5 У вас наверное опечатка
C++
1
2
3
4
5
6
7
8
9
10
11
12
void sortirovka(price m[],int x){
    for(int i=0;i<x;i++){
 
        for(int j = i+1;j<x;j++){
        //for(int j=0;j<x;j++){  // error 
 
            if(m[i].c>m[j].c){
                price temp=m[i];
                m[i]=m[j];
                m[j]=temp;}}}
return;
}
наверное надо
C++
1
2
3
4
5
6
7
8
9
10
11
12
void sortirovka(price m[],int x){
    for(int i=0;i<x -1;i++){// error 
 
        for(int j = i+1;j<x;j++){
        //for(int j=0;j<x;j++){  // error 
 
            if(m[i].c>m[j].c){
                price temp=m[i];
                m[i]=m[j];
                m[j]=temp;}}}
return;
}
0
1130 / 789 / 232
Регистрация: 12.04.2010
Сообщений: 2,012
21.12.2013, 15:00 14
Цитата Сообщение от Genn55 Посмотреть сообщение
Alex5 У вас наверное опечатка
Напишем мы
C++
1
2
    for(int i=0;i<x;i++){
         for(int j = i+1;j<x;j++){
или
C++
1
2
    for(int i=0;i<x -1;i++){
        for(int j = i+1;j<x;j++){
результат будет одинаковым.

Добавлено через 20 минут
Цитата Сообщение от Demon55 Посмотреть сообщение
Я уже пробовал так описывать сортировку, выводит пустые поля.
Цитата Сообщение от Demon55 Посмотреть сообщение
C++
1
2
3
4
5
6
if(a==1){ cout << "Введите кол-во записей: ";
 cin >> k;
 if(k>10) cout << "Перебор\n";
 else {
 input(k);
 sortirovka(m,10);}}
Если k<10, то элементы m[k+1], m[k+2], ... нулевые. И после вызова sortirovka(m,10) они будут перемещены в начало массива.(При сортировке по возрастанию.)

Добавлено через 20 минут
Цитата Сообщение от outoftime Посмотреть сообщение
какой оператор надо перегрузить для GoodsItem что-бы std::sort не надо было передавать компаратор
http://www.cplusplus.com/refer... t/?kw=sort void sort (RandomAccessIterator first, RandomAccessIterator last); The elements are compared using operator<
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
23.12.2013, 13:06 15
Alex5, http://lmgtfy.com/?q=c%2B%2B+r... oading&l=1

Добавлено через 7 минут
Объявление:
C++
1
2
3
4
5
6
7
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
Реализация:
C++
1
2
3
4
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
Весь код:
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            std::sort(store.begin(), store.end());
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (auto it = value.begin(); it != value.end(); ++it)
        out << (*it);
}
 
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (auto it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}


Добавлено через 4 минуты
P.S: если перегрузить оператор ввода, то можно будет передавать любой входной поток поддерживающий интерфейс istream, т.е. ifstream, istringstream и т.д.
0
0 / 0 / 0
Регистрация: 22.12.2013
Сообщений: 28
23.12.2013, 13:13 16
Весь код:
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            std::sort(store.begin(), store.end());
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (auto it = value.begin(); it != value.end(); ++it)
        out << (*it);
}
 
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (auto it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}


Добавлено через 4 минуты
P.S: если перегрузить оператор ввода, то можно будет передавать любой входной поток поддерживающий интерфейс istream, т.е. ifstream, istringstream и т.д.
у меня вообще vc++ 6.0 ругаеться
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(82) : error C2440: 'initializing' : cannot convert from 'const class GoodsItem *' to 'int'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(82) : error C2446: '!=' : no conversion from 'const class GoodsItem *' to 'int'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(82) : error C2040: '!=' : 'int' differs in levels of indirection from 'const class GoodsItem *'
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(83) : error C2100: illegal indirection
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(114) : error C2440: 'initializing' : cannot convert from 'class GoodsItem *' to 'int'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(114) : error C2446: '!=' : no conversion from 'class GoodsItem *' to 'int'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(114) : error C2040: '!=' : 'int' differs in levels of indirection from 'class GoodsItem *'
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(115) : error C2227: left of '->price' must point to class/struct/union
c:\program files (x86)\microsoft visual studio\myprojects\777\777.cpp(115) : error C2440: '=' : cannot convert from 'int' to 'class GoodsItem *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
23.12.2013, 14:54 17
denstan, я писал для g++ и компилировал с флагом std=c++11

Добавлено через 3 минуты
Этот код
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            std::sort(store.begin(), store.end());
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (int i = 0; i < value.size(); ++i)
        out << value[i];
}
 
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (std::vector<GoodsItem>::iterator it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}

Компилируется с флагом -std=c++98, по идее VS6.0 потянет.
1
0 / 0 / 0
Регистрация: 22.12.2013
Сообщений: 28
23.12.2013, 15:39 18
Цитата Сообщение от outoftime Посмотреть сообщение
denstan, я писал для g++ и компилировал с флагом std=c++11

Добавлено через 3 минуты
Этот код
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            std::sort(store.begin(), store.end());
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (int i = 0; i < value.size(); ++i)
        out << value[i];
}
 
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (std::vector<GoodsItem>::iterator it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}

Компилируется с флагом -std=c++98, по идее VS6.0 потянет.
где этот флаг ставить?

Добавлено через 3 минуты
Цитата Сообщение от outoftime Посмотреть сообщение
denstan, я писал для g++ и компилировал с флагом std=c++11

Добавлено через 3 минуты
Этот код
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
 
class GoodsItem
{
public:
    std::string name, shop, manufacture;
    int year, price;
    friend bool operator < (const GoodsItem &item1, const GoodsItem &item2);
};
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value);
 
class GoodsStore : public std::vector<GoodsItem>
{
public:
    void input(const int &amount);
    void printSelected(const int &price);
};
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value);
 
int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "Russian");
 
    bool running(true);
    GoodsStore store;
 
    while (running) 
    {
        int caseInput;
        std::cout   << "\nВыберете действие:\n"
                    << "1.Ввод\n" 
                    << "2.Вывод\n" 
                    << "3.Вывод по цене\n" 
                    << "4.Выход\n\n";
        std::cin >> caseInput;
 
        switch (caseInput)
        {
        case 1:
            int amount;
            std::cout << "Введите кол-во записей: ";
            std::cin >> amount;
            store.input(amount);
            std::sort(store.begin(), store.end());
            break;
        case 2:
            std::cout << store;
            break;
        case 3:
            int price;
            std::cout << "Введите цену: ";
            std::cin >> price;
            store.printSelected(price);
            break;
        default:
            running = false;
        }
    }
 
    return EXIT_SUCCESS;
}
 
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (int i = 0; i < value.size(); ++i)
        out << value[i];
}
 
bool operator < (const GoodsItem &item1, const GoodsItem &item2)
{
    return item1.price < item2.price;
}
 
void GoodsStore::input(const int &amount) 
{
    for (int i = 0; i < amount; ++i) {
        GoodsItem item;
 
        std::cout << "Введите название товара: ";
        std::cin >> item.name;
        std::cout << "Введите страну изготовитель: ";
        std::cin >> item.manufacture;
        std::cout << "Введите год выпуска: ";
        std::cin >> item.year;
        std::cout << "Введите цену: ";
        std::cin >> item.price;
        std::cout << "Введите название магазина: ";
        std::cin >> item.shop;
 
        this->push_back(item);
    }
}
 
void GoodsStore::printSelected(const int &price) 
{
    std::vector<GoodsItem>::iterator item = end();
    for (std::vector<GoodsItem>::iterator it = begin(); it != end(); ++it)
        if (price == it->price) item = it;
 
    if (item == end()) 
    {
        std::cout << "Товаров с ценой " << price << " нет" << std::endl;
    }
    else std::cout << (*item) << std::endl;
}

Компилируется с флагом -std=c++98, по идее VS6.0 потянет.
хм...поставил g++
начал компилировать в vs+6.0 и теперь начал ругаться

c:\program files (x86)\microsoft visual studio\myprojects\7777\777.cpp(77) : error C4716: 'operator<<' : must return a value
c:\program files (x86)\microsoft visual studio\myprojects\7777\777.cpp(84) : error C4716: 'operator<<' : must return a value
0
║XLR8║
1212 / 909 / 270
Регистрация: 25.07.2009
Сообщений: 4,361
Записей в блоге: 5
23.12.2013, 15:51 19
http://sourceforge.net/project... Installer/ Download mingw-get-setup.exe (86.5 kB) - ваше
После установки Path обновить для юзера и можно компилировать: g++ code.cpp -o run.exe -std=c++11

Добавлено через 1 минуту
Цитата Сообщение от denstan Посмотреть сообщение
c:\program files (x86)\microsoft visual studio\myprojects\7777\777.cpp(84) : error C4716: 'operator<<' : must return a value
C++
1
return out;
Дописать надо.

Добавлено через 1 минуту
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
    return out;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (int i = 0; i < value.size(); ++i)
        out << value[i];
    return out;
}
0
0 / 0 / 0
Регистрация: 22.12.2013
Сообщений: 28
24.12.2013, 01:26 20
Цитата Сообщение от outoftime Посмотреть сообщение
http://sourceforge.net/project... Installer/ Download mingw-get-setup.exe (86.5 kB) - ваше
После установки Path обновить для юзера и можно компилировать: g++ code.cpp -o run.exe -std=c++11

Добавлено через 1 минуту

C++
1
return out;
Дописать надо.

Добавлено через 1 минуту
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
std::ostream& operator << (std::ostream &out, const GoodsItem &value)
{
    out << " Товар: "   << value.name 
        << " Страна: "  << value.manufacture
        << " Год: "     << value.year 
        << " Цена: "    << value.price
        << " Магазин: " << value.shop
        << std::endl;
    return out;
}
 
std::ostream &operator << (std::ostream &out, const GoodsStore &value) 
{
    out << "Перечень товаров:" << std::endl;
    for (int i = 0; i < value.size(); ++i)
        out << value[i];
    return out;
}
спасибо, работает
0
24.12.2013, 01:26
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
24.12.2013, 01:26
Помогаю со студенческими работами здесь

Не могу сообразить с сортировкой, и с последним пунктом
Описать структуру STUDENT, содержащую следующие поля: Фамилия и инициалы номер группы...

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

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

Сортировать массив символов обменной, карманной сортировкой, сортировкой вставками
Сортировать массив символов обменной, карманной сортировкой, сортировкой вставками . Оценить...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru