Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.76/21: Рейтинг темы: голосов - 21, средняя оценка - 4.76
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39

Реализовать систему поиска

09.05.2019, 18:29. Показов 4432. Ответов 19

Студворк — интернет-сервис помощи студентам
Надо написать функцию для нахождения информации о людях чье имя начинается на "ф" ну или другую(другие) буквы
Здесь это функция poiskPanel
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <iomanip>
 
using namespace std;
const int SIZE_OF_ACCOUNTS = 500;
string const FILE_OF_ACCOUNTS = "C://Accounts.txt";
const int SIZE_ARR_OF_INFOTMATION = 500;
const string FILE_OF_INFORMATION = "C://Information.txt";// ПУТЬ К ФАЙЛУ
 
struct Account
{
    string login;
    string pass;
    int role; //0-пользователь,1-администратор
};
struct Information
{
    string fio;
    string tarif;
    string nomer;
    int godpodkluchenija;
};
void UserPanel(Information *arr_of_Information, int &num_of_Information);
void delInformation(Information *arr_of_Information, int &num_of_Information);
void authorization(Account *arr_of_accounts, int &number_of_accounts, Information *arr_of_Information, int &num_of_Information);
void readFileAccounts(Account *arr_of_accounts, int &number_of_accounts);
string check_unique_login(Account *arr_of_accounts, int &number_of_accounts);
void readFileInformation(Information *arr_of_information, int &number_of_information);
void menuInformation(Account *arr_of_accounts, int number_of_accounts, Information *arr_of_Information, int &num_of_Information);
void addAdmin(Account *arr_of_accounts, int &number_of_accounts);
void AddInformation(Information *arr_of_Information, int &num_of_Information);
void AdminPanel(Account *arr_of_accounts, int number_of_accounts, Information *arr_of_Information, int &num_of_Information);
void addUser(Account *arr_of_accounts, int &number_of_accounts);
void boostAccounts(Account *arr_of_accounts, int number_of_accounts);
void delAccount(Account *arr_of_accounts, int &number_of_accounts);
void writeEndFileAccounts(Account new_account);
void writeEndFileInformation(Information svegak);
void showAccounts(Account *arr_of_accounts, int number_of_accounts); //Вывод содержимого массива на экран
void ShowInformation(Information *arr_of_Information, int &num_of_Information);
void boostInformation(Information *arr_of_Information, int num_of_Information);
string check_unique_login(Account *arr_of_accounts, int &number_of_accounts);
void PoiskPanel(Information *arr_of_Information, int num_of_Information);
string Vvodparol();
int main(){
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    Account arr_of_accounts[SIZE_OF_ACCOUNTS];
    int number_of_accounts = 0;
    Information arr_of_Information[SIZE_ARR_OF_INFOTMATION];
    int num_of_Information = 0;//addAdmin(arr_of_accounts, number_of_accounts); 
    //addAccounts(arr_of_accounts, number_of_accounts);
    authorization(arr_of_accounts,number_of_accounts, arr_of_Information, num_of_Information);
    
}
void readFileAccounts(Account *arr_of_accounts, int &number_of_accounts)
{
    ifstream fin(FILE_OF_ACCOUNTS, ios::in); //Открыли файл для чтения
    if (!fin.is_open()) cout << "Указанный файл не существует!" << endl;
    else
    {
        int i = 0;
        while (!fin.eof())
        {
            fin >> arr_of_accounts[i].login
                >> arr_of_accounts[i].pass
                >>arr_of_accounts[i].role;
            i++;
        }
        number_of_accounts = i;
    }
    fin.close(); //Закрыли открытый файл
}
void readFileInformation(Information *arr_of_information, int &number_of_information)
{
    ifstream fin(FILE_OF_INFORMATION, ios::in); //Открыли файл для чтения
    if (!fin.is_open()) cout << "Указанный файл не существует!" << endl;
    else
    {
        int i = 0;
        while (!fin.eof())
        {
            fin >> arr_of_information[i].fio
                >> arr_of_information[i].nomer
                >> arr_of_information[i].tarif
                >>arr_of_information[i].godpodkluchenija;
            i++;
        }
        number_of_information = i;
    }
    fin.close(); //Закрыли открытый файл
}void authorization(Account *arr_of_accounts, int &number_of_accounts, Information *arr_of_Information, int &num_of_Information)
{
    readFileAccounts(arr_of_accounts, number_of_accounts);
    readFileInformation(arr_of_Information, num_of_Information);
    system("cls");
    string newlogin, newpass; int i = 0;
    cout << "____________________________________________АВТОРИЗАЦИЯ____________________________________________\n";
    cout << "Введите логин: " << endl;
    cin >> newlogin;
    for (i; i < number_of_accounts; i++)
    {
        if (newlogin == arr_of_accounts[i].login) {
            newpass=Vvodparol(); cout << endl;
            //cin >> newpass;
            if (newpass == arr_of_accounts[i].pass)
            {
                cout << "\n____________________________________________ДОБРО ПОЖАЛОВАТЬ В СИСТЕМУ____________________________________________ \n" << endl;
                if(0==(arr_of_accounts[i].role) )
                {
                    cout << "Вы вошли как пользователь" << endl;
                    cout << "____________________________________________МЕНЮ ДЛЯ РАБОТЫ ПОЛЬЗОВАТЕЛЯ____________________________________________\n " << endl;
                    UserPanel( arr_of_Information, num_of_Information);
                    break;
                }
                else {
                    cout << "Вы вошли как администратор" << endl;
                    cout << "____________________________________________МЕНЮ ДЛЯ РАБОТЫ АДМИНИСТРАТОРА____________________________________________\n " << endl;
                    AdminPanel(arr_of_accounts, number_of_accounts, arr_of_Information, num_of_Information);
                    break;
                }
                
            }
            else { cout << "Вы ввели неверный пароль!\n"; }break;
        }
 
    }
}
 string Vvodparol() {
     string pass;
    cout << "Введите пароль пользователя(английскими буквами и цифрами): \n" << endl;
    int ch = 0;               // Переменная для символа.
    while (true)                // Создание бесконечного цикла.
    {
        ch = _getch();        // Помещаем код нажатой клавиши в переменную.
        if (ch == 13)         // Установка Enter на прерывание цикла.
        {
            break;         // Прерывание цикла.
        }
        if (ch == 27)   // Установка Esc на закрытие консоли.
        {
            exit(0);      // Выход из консоли.
        }
        if (ch == 8)     // Установка Backspace на удаление символов.
        {
 
            cout << (char)8 << ' ' << char(8);
            /*Смещение курсора на одну позицию  в лево вывод пробела и
            снова смещение курсора влево, то есть при нажатии Backspace
            символ будет стираться, а курсор перемещаеться. */
 
            if (!pass.empty())
                /*Если строка pass не являеться пустой, то из неё
                можно удалять  последний символ (Иначе закрывалась консоль.)*/
 
                pass.erase(pass.length() - 1);
            // позволяет удалить последний символ из строки pass
        }
 
        else
        {
            cout << '*';            // Замена символов на *
            pass += (char)ch;       // Преврашение кода из целого числа в символ.
        }
    }return pass;
}
 void AdminPanel(Account *arr_of_accounts, int number_of_accounts, Information *arr_of_Information, int &num_of_Information)
 {
 
     int var_vvoda, menu, var;
     while (true) {
         cout << "1 - МЕНЮ ДЛЯ РАБОТЫ С УЧЕТНЫМИ ЗАПИСЯМИ ПОЛЬЗОВАТЕЛЕЙ" << endl;
         cout << "2 - МЕНЯ ДЛЯ РАБОТЫ С  ДАННЫМИ" << endl;
         cin >> menu;
         if (menu == 1)
         {
             system("cls");
             cout << "1 - ПРОСМОТРЕТЬ ВСЕ УЧЕТНЫЕ ЗАПИСИ" << endl;
             cout << "2 - ДОБАВИТЬ УЧЕТНУЮ ЗАПИСЬ" << endl;
             cout << "3 - УДАЛИТЬ УЧЕТНУЮ ЗАПИСЬ" << endl;
             cout << "4 - РЕДАКТИРОВАТЬ УЧЕТНУЮ ЗАПИСЬ" << endl;
             cout << "5 - ВЫХОД В МЕНЮ АДМИНИСТРАТОРА" << endl;
             cout << "0 - ВЫХОД ИЗ СИСТЕМЫ" << endl;
             cout << endl;
             cin>>var_vvoda;
             switch (var_vvoda)
             {
             case 1:showAccounts(arr_of_accounts, number_of_accounts); continue;
             case 2:
                 cout << "Добавить аккаунт администратора-1,пользователя-любая цифра\n";
                 cin>>var;
                 if (var == 1)  addAdmin(arr_of_accounts, number_of_accounts);
                else addUser(arr_of_accounts, number_of_accounts);
                 continue;
            case 3:delAccount(arr_of_accounts, number_of_accounts); continue;
            case 4:boostAccounts(arr_of_accounts, number_of_accounts); continue;
             case 5:AdminPanel(arr_of_accounts, number_of_accounts, arr_of_Information, num_of_Information); continue;
             case 0:exit(0);
             }
         }
         if (menu == 2)menuInformation(arr_of_accounts, number_of_accounts, arr_of_Information, num_of_Information);
     }
 }
 void boostAccounts(Account *arr_of_accounts, int number_of_accounts)
 {
     showAccounts(arr_of_accounts,number_of_accounts);
     cout << "Введите номер редактируемой записи ";
     int upd_item;
     cin >> upd_item;
     cout << "отредактируейте данные учётной записи: " << endl;
     cout << "логин: !";
     cin >> arr_of_accounts[upd_item - 1].login;
     cout << "Пароль: !";
     cin >> arr_of_accounts[upd_item - 1].pass;
     cout << "роль: !";
     cin >> arr_of_accounts[upd_item - 1].role;
     system("cls");
     cout << "запись отредактирована !" << endl;
     cout << endl;
 }
 void addAdmin(Account *arr_of_accounts, int &number_of_accounts)
 {
     if (number_of_accounts + 1 < SIZE_OF_ACCOUNTS)
     {
         number_of_accounts++;
         arr_of_accounts[number_of_accounts - 1].role = 1;
         cout << "Введите логин администратора: \n";
         arr_of_accounts[number_of_accounts - 1].login = check_unique_login(arr_of_accounts, number_of_accounts);
         arr_of_accounts[number_of_accounts - 1].pass=Vvodparol();
         writeEndFileAccounts(arr_of_accounts[number_of_accounts - 1]);
         system("cls");
         cout << "Аккаунт администратора успешно создан!) \n";
     }
     else { cout << "ОШИБКА!!Вся память занята! \n"; }
 }
 string check_unique_login(Account *arr_of_accounts, int &number_of_accounts)
 {
     string login;
     cin >> login;
     for (int i = 0; i < number_of_accounts; i++)
     {
         if (login == arr_of_accounts[i].login) {
             do {
                 cout << "Такой  логин  уже существует!Введите другой!" << endl;
                 cin >> login;
             } while (login == arr_of_accounts[i].login);
         }
         else break;
     }
     return login;
 }
 void writeEndFileAccounts(Account new_account)
 {
     ofstream fadd(FILE_OF_ACCOUNTS, ios::app); //Открыли файл для дозаписи
     fadd << endl;
     fadd << new_account.login << "   "
         << new_account.pass << "    "
         << new_account.role;
     fadd.close();
 }
 void addUser(Account *arr_of_accounts, int &number_of_accounts)
 {
     if (number_of_accounts + 1 < SIZE_OF_ACCOUNTS)
     {
         number_of_accounts++;
         arr_of_accounts[number_of_accounts - 1].role = 0;
         cout << "Введите логин пользователя: \n";
         arr_of_accounts[number_of_accounts - 1].login = check_unique_login(arr_of_accounts, number_of_accounts);
        arr_of_accounts[number_of_accounts - 1].pass=Vvodparol();
         writeEndFileAccounts(arr_of_accounts[number_of_accounts - 1]);
         system("cls");
         cout << "Аккаунт пользователя успешно создан!) \n";
     }
     else { cout << "ОШИБКА!!Вся память занята!" << endl; }
 }
 void showAccounts(Account *arr_of_accounts, int number_of_accounts) {
     for (int i = 0; i < number_of_accounts; i++)
         cout<<i+1<<"." << arr_of_accounts[i].login << " "
         << arr_of_accounts[i].pass << " "
         << arr_of_accounts[i].role << endl;
 }
 void delAccount(Account *arr_of_accounts, int &number_of_accounts)//Шаблон бахнуть
 {
     showAccounts(arr_of_accounts, number_of_accounts);
     cout << "Введите номер удаляемой записи ";
     int del_item;
     cin >> del_item;
     for (int i = del_item - 1; i < number_of_accounts; i++)
         arr_of_accounts[i] = arr_of_accounts[i + 1];
     number_of_accounts--;
     system("cls");
     cout << "запись удалена !" << endl;
     cout << endl;
 
 }
 void menuInformation(Account *arr_of_accounts, int number_of_accounts, Information *arr_of_Information, int &num_of_Information) {
     cout << "Меню для работы с абонентами сотовой связи";
     cout << "1 - ПОКАЗАТЬ" << endl;
     cout << "2 - ДОБАВИТЬ" << endl;
     cout << "3 - УДАЛИТЬ" << endl;
     cout << "4 - РЕДАКТИРОВАТЬ" << endl;
     cout << "5 - ВЫХОД" << endl;
     int vibor;
     cin >> vibor;
     switch (vibor) {
     case 1: ShowInformation(arr_of_Information,num_of_Information);
         break;
     case 2: AddInformation(arr_of_Information, num_of_Information);
         break;
     case 3: delInformation(arr_of_Information, num_of_Information);
         break;
     case 4: boostInformation(arr_of_Information, num_of_Information);
         break;
     }
}
 void ShowInformation(Information *arr_of_Information, int &num_of_Information) {
     for (int i = 0; i < num_of_Information; i++)
         cout << i + 1 << "." << arr_of_Information[i].fio << " "
         << arr_of_Information[i].nomer << " "
         << arr_of_Information[i].tarif << " " << arr_of_Information[i].godpodkluchenija<< endl;
 }
 void AddInformation(Information *arr_of_Information, int &num_of_Information)
 {
     if (num_of_Information + 1 <= SIZE_ARR_OF_INFOTMATION) {
         num_of_Information++;
         cout << "ВВЕДИТЕ ДАННЫЕ ДЛЯ НОВОГО СОТРУДНИКА" << endl;
         cout << "ФИО: ";
         cin >> arr_of_Information[num_of_Information - 1].fio;
         cout << "Hoмер: ";
         cin >> arr_of_Information[num_of_Information - 1].nomer;
         cout << "Тариф: ";
         cin >> arr_of_Information[num_of_Information - 1].tarif;
         cout << "Год подключения: ";
         cin >> arr_of_Information[num_of_Information - 1].godpodkluchenija;
         writeEndFileInformation(arr_of_Information[num_of_Information - 1]);
         cout << "НОВЫЙ АБОНЕНТ ДОБАВЛЕН!!!" << endl;
         cout << endl;
     }
 }
void writeEndFileInformation(Information svegak) {
         ofstream fadd(FILE_OF_INFORMATION, ios::app); //Открыли файл для дозаписи
         fadd << endl;
         fadd << svegak.fio << "   "
             << svegak.nomer << "    "
             << svegak.tarif << "   "
             << svegak.godpodkluchenija << "   ";
         fadd.close();
     } 
void delInformation(Information *arr_of_Information, int &num_of_Information)//Шаблон бахнуть
     {
    ShowInformation(arr_of_Information, num_of_Information);
         cout << "Введите номер удаляемой записи ";
         int del_item;
         cin >> del_item;
         for (int i = del_item - 1; i < num_of_Information; i++)
             arr_of_Information[i] = arr_of_Information[i + 1];
         num_of_Information--;
         system("cls");
         cout << "запись удалена !" << endl;
         cout << endl;
 
     }
void boostInformation(Information *arr_of_Information, int num_of_Information) {
    ShowInformation(arr_of_Information, num_of_Information);
    cout << "Введите номер редактируемой записи ";
    int upd_item;
    cin >> upd_item;
    cout << "отредактируейте данные учётной записи: " << endl;
    cout << "Что хотите редактировать?" << endl;
    cout << "1-ФИО\n2-Номер\n3-Тариф\n4-Год подключения" << endl;
    int vibor;
    cin >> vibor;
    switch (vibor) {
    case 1: cout << "ФИО: !";
        cin >> arr_of_Information[upd_item - 1].fio;
        break;
    case 2: cout << "Номер: !";
        cin >> arr_of_Information[upd_item - 1].nomer;
        break;
    case 3: cout << "Тариф: !";
        cin >> arr_of_Information[upd_item - 1].tarif;
        break;
    case 4:cout << "Год подключения: !";
        cin >> arr_of_Information[upd_item - 1].godpodkluchenija;
        break;
    }
        system("cls");
        cout << "запись отредактирована !" << endl;
        cout << endl;
    
}
void UserPanel(Information *arr_of_Information, int &num_of_Information)
{
    cout << "1 - ПРОСМОТРЕТЬ ВСЕ ДАННЫЕ" << endl;
    cout << "2 - ВЫПОЛНЕНИЕ ИНДИВИДУАЛЬНОГО ЗАДАНИЯ" << endl;
    cout << "3 - ПОИСК ДАННЫХ" << endl;
    cout << "4 - СОРТИРОВКА ДАННЫХ" << endl;
    cout << "0 - ВЫХОД ИЗ СИСТЕМЫ" << endl;
    cout << endl;
    int item;
    cin >> item;
    switch (item)
    {
    case 1: ShowInformation(arr_of_Information, num_of_Information); 
        break;
//  case 2: individulka(arr_of_Information, num_of_Information);
        break;
    case 3: PoiskPanel(arr_of_Information, num_of_Information); 
        break;
//  case 4: SortPanel(arr_of_Information, num_of_Information);  
        break;
    }
}
void PoiskPanel(Information *arr_of_Information, int num_of_Information) {
    
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
09.05.2019, 18:29
Ответы с готовыми решениями:

Как реализовать систему поиска?
У меня есть код поисковой формы, украшенного через css: &lt;input placeholder=&quot;Найти!&quot; type=&quot;search&quot;&gt; Уже не один месяц...

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

Реализовать систему поиска И и ИЛИ по базе данных
Есть следующая задача, не знаю как к ней подступиться. Дано: кей,текст текст текст... порядка 100-200кб кей2,текст текст текст......

19
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 18:56
Лучший ответ Сообщение было отмечено Fodugj как решение

Решение

Fodugj,
C++
1
2
3
4
5
6
7
void PoiskPanel(Information *arr_of_Information, int num_of_Information, char ch) {
    for (int i = 0; i < num_of_Information; ++i)
        if (arr_of_Information[i].fio.size() && std::tolower(arr_of_Information[i].fio.front()) == std::tolower(ch))
        {
            // выводим arr_of_Information[i] в консоль или что там вам нужно
        }
}
1
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 19:25  [ТС]
Все равно выводит лишнее((
Миниатюры
Реализовать систему поиска  
0
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 19:28  [ТС]
zayats80888, все так же выводит лишнее
Миниатюры
Реализовать систему поиска  
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 19:32
Fodugj, покажи как вывод в консоль реализовал в этой функции
0
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 19:33  [ТС]
zayats80888,
C++
1
2
3
4
5
6
7
8
void PoiskPanel(Information *arr_of_Information, int num_of_Information, char ch) {
    for (int i = 0; i < num_of_Information; ++i)
        if (arr_of_Information[i].fio.size() && tolower(arr_of_Information[i].fio.front()) == tolower(ch))
        {
            //cout << arr_of_Information[i].fio << arr_of_Information[i].nomer;
            ShowInformation(arr_of_Information, num_of_Information);//arr_of_Information[i] не выводит ошибку выдает
        }
}
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 19:38
Цитата Сообщение от Fodugj Посмотреть сообщение
ShowInformation(arr_of_Information, num_of_Information);
Ну ясен пень, эта функция же весь массив распечатывает
Просто воткни это
C++
1
2
3
         cout << i + 1 << "." << arr_of_Information[i].fio << " "
         << arr_of_Information[i].nomer << " "
         << arr_of_Information[i].tarif << " " << arr_of_Information[i].godpodkluchenija<< endl;
1
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 19:44  [ТС]
zayats80888, Спасибо за помощь)

Добавлено через 4 минуты
zayats80888, А не подскажешь например как эту функцию написать без копипаста на разный поиск фамилия,телефон т.д.?
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 19:57
Лучший ответ Сообщение было отмечено Fodugj как решение

Решение

Fodugj,
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
struct by_name
{
    char ch;
    by_name(char c) : ch(c) {}
    bool operator()(const Information& inf) { return inf.fio.size() && tolower(inf.fio.front()) == tolower(ch); }
};
 
struct by_nomer
{
    string nomer;
    by_nomer(const string& n) : nomer(n) {}
    bool operator()(const Information& inf) { return nomer == inf.nomer; }
};
 
struct by_tarif
{
    string tarif;
    by_tarif(const string& t) : tarif(t) {}
    bool operator()(const Information& inf) { return tarif == inf.tarif; }
};
 
template<class Pred>
void PoiskPanel(Information *arr_of_Information, int num_of_Information, Pred p) {
    for (int i = 0; i < num_of_Information; ++i)
        if (p(arr_of_Information[i]))
        {
            //печатаем
        }
}
 
// вызываем так:
 
PoiskPanel(arr, num, by_name(ch));
PoiskPanel(arr, num, by_nomer(nomer));
1
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 20:13  [ТС]
zayats80888,
Миниатюры
Реализовать систему поиска  
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 20:15
Все норм. Потом пропадет
1
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 20:27  [ТС]
zayats80888, Серьезность Код Описание Проект Файл Строка Состояние подавления
Ошибка C2065 inf: необъявленный идентификатор Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 26
Ошибка C2065 inf: необъявленный идентификатор Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 33
Ошибка C2065 inf: необъявленный идентификатор Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 19
Ошибка C4430 отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 33
Ошибка C4430 отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 26
Ошибка C4430 отсутствует спецификатор типа - предполагается int. Примечание. C++ не поддерживает int по умолчанию Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 19
Ошибка C2143 синтаксическая ошибка: отсутствие "," перед "&" Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 33
Ошибка C2143 синтаксическая ошибка: отсутствие "," перед "&" Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 26
Ошибка C2143 синтаксическая ошибка: отсутствие "," перед "&" Курсач c:\users\philipp\source\repos\kursach\ку рсач\курсач.cpp 19

Добавлено через 55 секунд
zayats80888, все оке)

Добавлено через 9 минут
zayats80888, можешь пояснить
C++
1
2
3
4
5
6
struct by_name
{
* * char ch;
* * by_name(char c) : ch(c) {}//что тут происходит
* * bool operator()(const Information& inf) { return inf.fio.size() && tolower(inf.fio.front()) == tolower(ch); }//и тут а то хз
};
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 20:43
Цитата Сообщение от Fodugj Посмотреть сообщение
можешь пояснить
C++
1
2
3
4
5
6
7
8
9
10
11
12
struct by_name
{
    char ch;
    by_name(char c) : ch(c) {} // конструктор, инициализирует ch значением, которое мы передаем при вызове by_name(name)
    bool operator()(const Information& inf) // оператор вызова с семантикой функции, т.е. obj(arg);
    { 
        return //возвращаем true
            inf.fio.size() && // если строка не пустая
            tolower(inf.fio.front()) == tolower(ch);    // и первый символ равен тому что мы передали в конструктор
                                                        // приведя их к нижнему регистру с помощью tolower
    }
};
0
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 21:01  [ТС]
zayats80888, Спасибо)

Добавлено через 16 минут
zayats80888, а можно ли эти функции использовать для сортировки. Или как отсортировать по алфавиту, тарифу,году.
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 21:03
Цитата Сообщение от Fodugj Посмотреть сообщение
Или как отсортировать по алфавиту, тарифу,году.
Вот тут человеку помогал, думаю разберетесь, смысл тот же
Сортировка массива по двух параметрам
0
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 21:13  [ТС]
zayats80888,
Миниатюры
Реализовать систему поиска  
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 21:16
Fodugj, strcmp это функция для сравнения С-строк, стринги сравниваются str1 > str2
0
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
09.05.2019, 21:38  [ТС]
zayats80888, Переделал не сортирует(
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
bool by_name1(const Information& lh, const Information& rh) { return (lh.fio == rh.fio) != NULL; }
bool by_group(const Information& lh, const Information& rh) { return lh.godpodkluchenija == rh.godpodkluchenija > 0; }
bool by_nm_gr(const Information& lh, const Information& rh) {
    return
        by_name1(lh, rh) ||
        ((lh.fio == rh.fio) == 0 && by_group(lh, rh));
}
//...и т.д.
template<class Foo>
void my_sort(Information *s, int n, Foo f)
{
    Information t;
    for (int i = 0; i < n - 1; i++)
    {
        for (int g = i + 1; g < n; g++)
        {
            if (f(s[i], s[g]))
            {
                t = s[i];
                s[i] = s[g];
                s[g] = t;
            }
        }
    }
};
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
09.05.2019, 21:55
Лучший ответ Сообщение было отмечено Fodugj как решение

Решение

Fodugj,
C++
1
2
bool by_name1(const Information& lh, const Information& rh) { return lh.fio > rh.fio; }
bool by_group(const Information& lh, const Information& rh) { return lh.godpodkluchenija > rh.godpodkluchenija; }
1
0 / 0 / 0
Регистрация: 15.11.2017
Сообщений: 39
10.05.2019, 00:15  [ТС]
zayats80888, как убрать лишний вывод, где -846565643, не подскажешь?
Миниатюры
Реализовать систему поиска  
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
10.05.2019, 00:15
Помогаю со студенческими работами здесь

Реализовать операцию поиска узла с заданным значением в дереве, не являющемся деревом поиска
На основе процедуры обхода дерева снизу вверх реализовать операцию поиска узла с заданным значением в дереве, не являющемся деревом поиска....

Google совершенствует систему поиска
С сегодняшнего дня Google позволяет пользователям производить тонкую подстройку поискового механизма компании и вручную менять рейтинги...

Элемент в массиве через двоичную систему поиска
Нужно найти элемент в массиве через двоичную систему поиска и поставить счетчик, который вычислит количество операций сравнений.

Невозможно поменять систему поиска yamdex.net
Здравствуйте! Вот собственного лог...

Реализовать систему
предположим, что в начальный момент времени на расстоянии S0 от собаки пробегает заяц. Его движение прямолинейно и скорость равна U. Собака...


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

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru