Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.69/13: Рейтинг темы: голосов - 13, средняя оценка - 4.69
1 / 1 / 4
Регистрация: 08.08.2013
Сообщений: 86
1

Удаление элементов вектора со сдвигом

28.03.2014, 19:29. Показов 2394. Ответов 3
Метки нет (Все метки)

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
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
#include <iostream>
#include <conio.h>
#include <vector>
#include <string>
using namespace std;
void spc(int x);
class Directory
{
public:
    int num[12];
    int code[4];
    string name;
    string last_name;
    Directory(string nn,string ln,char(n)[12],char(k)[4])
    {
       name = nn;
       last_name = ln;
       for(int i = 0;i<12;i++)
       {
           num[i]=n[i];
       }
       for(int i = 0;i<4;i++)
       {
           code[i] = k[i];
       }
    }
};
int true_input(int i)
{
    int x = 1;
    i = _getch();
    for(int j = 47;j < 58;j++)
    {
        if(i==j){x = 0;break;}
    }
    if(x == 0)
    {
    i -= 48;
    cout << i;
    return i;
    }
    else
    {
        return -1;
    }
}
Directory get_phone()
{
    char n[12] = {};
    char k[4] = {};
    string name = " ";
    string l_name = " ";
    int x = 0;
    cout << "Input name -> ";
    cin >> name;
    cout << endl << 
    "Input last name -> ";
        cin >> l_name;
        cout << endl;
    while (x == 0)
    {
    cout << "Input number of phone -> ";    
    x = 1;
      for(int i = 0;i<11;i++)
      {
        n[i] = true_input(n[i]);
        if(n[i] == -1)
        {
          cout << endl <<
          "Not tru input, try again."<<
          endl;
          x = 0;
          i = 12;
        }
      }
    }
    cin.clear();
    x = 0;
    cout << endl;
    while (x == 0)
    {
      cout << "Inptu code of town -> ";
      x = 1;
       for (int i = 0;i<4;i++)
      {
        k[i] = true_input(k[i]);
        if(k[i] == -1)
        {
          cout << endl <<
          "Not tru input, try again."<<
          endl;
          x = 0;
          i = 12;
        }
      }
    }
    return Directory(name,l_name,n,k);
}
vector<Directory>phone;//Хранение всех номеров
vector<Directory>buf;
void addnum()
{
    system("cls");
    while(cin)
    {
        Directory t = get_phone();
        phone.push_back(t);
        cout << endl << endl 
        << "Number is added"
        << endl <<
        "Do you want add next  number?"<<
        endl << "1 - Yes" << endl <<
        "Else - No.Back to manu" << endl
        << "->>> ";
        char q = ' ';
        q = _getch();
        switch (q)
        {
        case'1': {system("cls");}
            break;
        default: {return;}
        }
    }
}
void main_manu()
{
    system("cls");
    spc(24);
    cout << "MAIN MANU" << endl;
    cout << "1 = add number." << endl;
    cout << "2 = see the list of numbers." << endl;
    cout << "3 = deleting numbers." << endl;
    cout << "4 = search phones in directory" << endl;
    cout << "0 = exit." << endl;
} 
void spc(int x)//Пробелы
{
    for(int i = 0;i<x;i++)
    {
        cout << " ";
    }
}
void output()
{
    spc(24);
    cout << "List of numbers.";
    for(int i = 0;i<phone.size();i++)
    {
    cout << endl
    << i << ") " << phone[i].name <<
    " " << phone[i].last_name
    << endl
    << "Num: ";
    for(int j = 0;j<12;j++)
      {
        cout << 
        phone[i].num[j];
      }
    cout << endl << "Code: ";
    for(int j = 0;j<4;j++)
      {
          cout <<  
          phone[i].code[j];
      }
    }
}
void output_num(int x)
{
    system("cls");
    if(phone.size()!=0)
    {
       output();
    }
    else
    {
    spc(24);
    cout << 
    "Phone list is empty";
    }
    if(x == 1){
    cout << endl <<
    "For back to manu,input any kay.";
    _getch();}
    }
//HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP
void good_delete(int x)
{
   
    
    int j = 0;
    if(x==1)
    {
        int k = 0;
        cout << endl << "START";
        cout << endl << "phone size: " << phone.size();
        for(int k = 0;k<phone.size()+1;k++);
          {
             buf.push_back(phone[k]);
             
          }
        cout << endl << "1 buf true";
        phone.clear();
        int i = 0;
       for(int j = 0;j<buf.size();j++)
       {
           cout << "size: " << buf.size() << endl;
           cout << endl << endl << "name: " <<
           buf[j].name << endl << "last name: " <<
           buf[j].last_name << endl << "num: " << 
           buf[j].num << endl << "code: " << 
           buf[j].code << endl;
           system("PAUSE");
       }
               cout << endl << "3 phone true";
    }
    
    
    
    else{
    cout << endl << "Start delet";
    
    for(int j = 0;j<x;j++);
   {
      buf.push_back(phone[j]);
   }
   cout << endl << "1 buf true";
   j = x;
   for(j;j<phone.size();j++)
   {
       buf.push_back(phone[j]);
   }
   cout << endl << "2 buf true";
   phone.clear();
   int i = 0;
   for (i;i<buf.size();i++)
   {
       phone.push_back(buf[i]);
   }
   cout << endl << "3 phone true";
   }
    buf.clear();
}
void delete_num()
{
   while(true)
   {
   system("cls");
   char bad = 0;
   output_num(2);
   cout << endl << "For back to manu, intput -1";
   cout << endl << "Number of bad telephone -> ";
   
     cin >> bad;
     bad -= 48;
     if(cin)
     {
     if(bad == -1)
     {
         return;
     }
     if(bad > phone.size() || bad<0)
     {
       cout << endl << "Number not find.";
     }
     else{good_delete(bad);}
     }
     else{
     cout << endl << "Not true number.Try again";
     cin.clear();
     }
   }
}
//--------------------------------------------------------------------------
void search_num()
{
 
}
int main()
{
  bool x = true;
   do
  {
     char com = ' ';
     main_manu();
     cout << "Input command -> ";
     cin >> com;
     switch(com)
     {
     case '1': addnum();
         break;
     case '2': output_num(1);
         break;
     case '3': delete_num();
         break;
     case '4': search_num();
         break;
     case '0': {return 0;}
         break;
     default:{cout << "Not true command, try again";}
     }
  }while(x = true);
}
Жесть просто, помогите написать функцию delete_num(), и вызывающуюся ей функцию void good_delete(int x)

Нужно что бы , в case 3 в main , при вводе 1, удалялся первый элемент вектора phone, и остальные элементы сдвигались.
и так же при вводе 2, удаляется второй элемент, остальные сдвигаются
Пробовал через копирование в вектор buf.
но там походу куча косяков.
Помогите дописать )))
Кто поможет, тому + 1 спасибо, и +1 лучший ответ )

Добавлено через 1 час 11 минут
Аааа!!! Вы все плахие !

Добавлено через 26 секунд
Ладно, ладно, хорошие)

Добавлено через 18 минут
Ахааха, я сам всё исправил. Завидуйте моей гениальности!
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
28.03.2014, 19:29
Ответы с готовыми решениями:

Удаление элементов вектора
как вызвать деструктор? почему не удаляется объект class a { public: a() { std::cout &lt;&lt;...

Удаление элементов вектора
Я конечно понимаю, что вектор это такая штука, которая удаляется сама при выходе из функции в...

Удаление элементов из вектора
Что я делаю не так string f=&quot;/.+(STL).$1/&quot;; vector&lt;string&gt; words; words.push_back(f); ...

Удаление элементов вектора
Доброе. Данная программа выводит таблицу, и работает с ней. Как удалить строку в таблице? Не...

3
12 / 12 / 7
Регистрация: 09.10.2013
Сообщений: 222
29.03.2014, 04:48 2
а можешь выложить решение? хотелось бы посмотреть
0
135 / 134 / 53
Регистрация: 13.09.2013
Сообщений: 260
Записей в блоге: 2
29.03.2014, 08:10 3
Можно сделать, как-то так:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool List::removeElement(ui num)
{
    if (num > list.size())
        return 0;
    for(ui i = num; i < list.size(); i++)
    {
        if (num+1 == list.size())
        {
            list[i] = 0;
            break;
        }
        list[i] = list[++num];
    }
    return 1;
}
0
1 / 1 / 4
Регистрация: 08.08.2013
Сообщений: 86
01.04.2014, 17:56  [ТС] 4
У меня вот так:
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
void good_delete(int x)
{
 int j = 0;
if(x == 0)
{
    for(int j = 1;j<phone.size();j++)
    {
        buf.push_back(phone[j]);
    }
    phone.clear();
    for(int j = 0;j<buf.size();j++)
    {
        phone.push_back(buf[j]);
    }
}
else
{
  for(int j = 0;j<x;j++)
  {
      buf.push_back(phone[j]);
  }
  for(int j = x+1;j<phone.size();j++)
  {
      buf.push_back(phone[j]);
  }
  phone.clear();
  for(int j = 0;j<buf.size();j++)
  {
      phone.push_back(buf[j]);
  }
 }
buf.clear();
}
void delete_num()
{
   while(true)
   {
   system("cls");
   int bad = 0;
   output_num(2);
   cout << endl << "For back to manu, intput -1";
   cout << endl << "Number of bad telephone -> ";
   cin >> bad;
     if(cin)
     {
     if(bad == -1)
     {
         return;
     }
     if(bad > phone.size() || bad<-1)
     {
       cout << endl << "Number not find.";
     }
     else{good_delete(bad);}
     }
     else{
     cout << endl << "Not true number.Try again";
     cin.clear();
     }
   }
}
В вектор buf переписываются все значения phone кроме того, которое нужно удалить. Затем удаляем все элементы phone, переписываем в phone вектор buf, и очищаем buf для дальнейшего использования)))

Добавлено через 8 минут
Вот полная рабочая программа
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
#include <iostream>
#include <conio.h>
#include <vector>
#include <string>
#include<stdio.h>
using namespace std;
void spc(int x);
class Directory
{
public:
    int num[12];
    int code[4];
    string name;
    string last_name;
    Directory(string nn,string ln,char(n)[12],char(k)[4])
    {
       name = nn;
       last_name = ln;
       for(int i = 0;i<12;i++)
       {
           num[i]=n[i];
       }
       for(int i = 0;i<4;i++)
       {
           code[i] = k[i];
       }
    }
};
int true_input(int i)
{
    int x = 1;
    i = _getch();
    for(int j = 47;j < 58;j++)
    {
        if(i==j){x = 0;break;}
    }
    if(x == 0)
    {
    i -= 48;
    cout << i;
    return i;
    }
    else
    {
        return -1;
    }
}
Directory get_phone()
{
    char n[12] = {};
    char k[4] = {};
    string name = " ";
    string l_name = " ";
    int x = 0;
    cout << "Input name -> ";
    cin >> name;
    cout << endl << 
    "Input last name -> ";
        cin >> l_name;
        cout << endl;
    while (x == 0)
    {
    cout << "Input number of phone[11] -> ";    
    x = 1;
      for(int i = 0;i<11;i++)
      {
        n[i] = true_input(n[i]);
        if(n[i] == -1)
        {
          cout << endl << endl <<
          "Not true input!"<< endl <<
          "Need press 11 numbers!"<<
          endl;
          x = 0;
          i = 12;
        }
      }
    }
    cin.clear();
    x = 0;
    cout << endl;
    while (x == 0)
    {
      cout << "Inptu code of town[4] -> ";
      x = 1;
       for (int i = 0;i<4;i++)
      {
        k[i] = true_input(k[i]);
        if(k[i] == -1)
        {
          cout << endl << endl <<
          "Not true input!"<< endl <<
          "Need press 4 numbers!"<<
          endl;
          x = 0;
          i = 12;
        }
      }
    }
    return Directory(name,l_name,n,k);
}
vector<Directory>phone;//Хранение всех номеров
vector<Directory>buf;
void addnum()
{
    system("cls");
    while(cin)
    {
        Directory t = get_phone();
        phone.push_back(t);
        cout << endl << endl 
        << "Number is added"
        << endl <<
        "Do you want add next  number?"<<
        endl << "1 - Yes" << endl <<
        "Else - No.Back to manu" << endl
        << "->>> ";
        char q = ' ';
        q = _getch();
        switch (q)
        {
        case'1': {system("cls");}
            break;
        default: {return;}
        }
    }
}
void main_manu()
{
    system("cls");
    spc(24);
    cout << "MAIN MANU" << endl;
    cout << "1 = add number." << endl;
    cout << "2 = see the list of numbers." << endl;
    cout << "3 = deleting numbers." << endl;
    cout << "4 = search phones in directory" << endl;
    cout << "5 = Sort by numbers" << endl;
    cout << "0 = exit." << endl;
} 
void spc(int x)//Пробелы
{
    for(int i = 0;i<x;i++)
    {
        cout << " ";
    }
}
void output(int x)
{
    if(x != -1)
    {
        cout << endl << "Desired number:"
        << endl;
        for(int i = 0;i<phone.size();i++)
    {
    cout << endl
    << x << ") " << phone[x].name <<
    " " << phone[x].last_name
    << endl
    << "Num: ";
    for(int j = 0;j<12;j++)
      {
        cout << 
        phone[x].num[j];
      }
    cout << endl << "Code: ";
    for(int j = 0;j<4;j++)
      {
          cout <<  
          phone[x].code[j];
      }
    }
    cout << endl <<
    "For back to manu,input any kay.";
    _getch();
    
    }
    if(x == -1)
    {
    spc(24);
    cout << "List of numbers.";
    for(int i = 0;i<phone.size();i++)
    {
    cout << endl
    << i << ") " << phone[i].name <<
    " " << phone[i].last_name
    << endl
    << "Num: ";
    for(int j = 0;j<12;j++)
      {
        cout << 
        phone[i].num[j];
      }
    cout << endl << "Code: ";
    for(int j = 0;j<4;j++)
      {
          cout <<  
          phone[i].code[j];
      }
    }
  }
}
void output_num(int x)
{
    system("cls");
    if(phone.size()!=0)
    {
       output(-1);
    }
    else
    {
    spc(24);
    cout << 
    "Phone list is empty";
    }
    if(x == 1){
    cout << endl <<
    "For back to manu,input any kay.";
    _getch();}
    }
void good_delete(int x)
{
 int j = 0;
if(x == 0)
{
    for(int j = 1;j<phone.size();j++)
    {
        buf.push_back(phone[j]);
    }
    phone.clear();
    for(int j = 0;j<buf.size();j++)
    {
        phone.push_back(buf[j]);
    }
}
else
{
  for(int j = 0;j<x;j++)
  {
      buf.push_back(phone[j]);
  }
  for(int j = x+1;j<phone.size();j++)
  {
      buf.push_back(phone[j]);
  }
  phone.clear();
  for(int j = 0;j<buf.size();j++)
  {
      phone.push_back(buf[j]);
  }
 }
buf.clear();
}
void delete_num()
{
   while(true)
   {
   system("cls");
   int bad = 0;
   output_num(2);
   cout << endl << "For back to manu, intput -1";
   cout << endl << "Number of bad telephone -> ";
   cin >> bad;
     if(cin)
     {
     if(bad == -1)
     {
         return;
     }
     if(bad > phone.size() || bad<-1)
     {
       cout << endl << "Number not find.";
     }
     else{good_delete(bad);}
     }
     else{
     cout << endl << "Not true number.Try again";
     cin.clear();
     }
   }
}
void search_num()
{
    int x = 0;
    char n[11];
    int j = 0;
    int i = 0;
    int y = 0;
    int k = 0;
    system("cls");
    spc(24);
    cout << "Search numbers";
    cout << endl << "For back to manu, intput -1"
    << endl;
 
 
    while (x == 0)
    {
    cout << "Input the desired number[11] -> "; 
    x = 1;
      for(int i = 0;i<11;i++)
      {
        n[i] = true_input(n[i]);
        if(n[i] == -1)
        {
          cout << endl << endl <<
          "Not true input!"<< endl <<
          "Need press 11 numbers!"<<
          endl;
          x = 0;
          i = 12;
        }
      }
    }
 
    for(int j = 0;j<phone.size();j++)
    {
        for(int i = 0;i<11;i++)
        {
            if(phone[j].num[i]==n[i])
            {
                 k++;
                 if(k==11)
                 {
                     for(int y = 0;y<11;y++)
                     {
                         output(j);
                         return;
 
                     }
                 }
            }
        }
    }
 
    cout << endl<< 
    "Number missing!";
    cout << endl <<
    "For back to manu,input any kay.";
    _getch();
    
    return;
 
}
void sort_code()
{
    system("cls");
    spc(15);
    cout << "Кому нужна эта сортировка, есть же крутой поиск!";
    cout << endl <<
    "For back to manu,input any kay.";
    _getch();
    return;
}
int main()
{
  setlocale( LC_ALL,"Russian" );
   bool x = true;
   do
  {
     char com = ' ';
     main_manu();
     cout << "Input command -> ";
     cin >> com;
     switch(com)
     {
     case '1': addnum();
         break;
     case '2': output_num(1);
         break;
     case '3': delete_num();
         break;
     case '4': search_num();
         break;
     case '5': sort_code();
         break;
     case '0': {return 0;}
         break;
     default:{cout << "Not true command, try again";}
     }
  }while(x = true);
}
Добавлено через 4 минуты
Цитата Сообщение от Blueeyer Посмотреть сообщение
а можешь выложить решение? хотелось бы посмотреть
Пожалуйста!
0
01.04.2014, 17:56
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
01.04.2014, 17:56
Помогаю со студенческими работами здесь

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

Удаление элементов из вектора
С консоли вводится вектор значений double и точность, удалить и вектора элементы разность между...

Удаление одинаковых элементов вектора
Здравствуйте. Нужно удалить из вектора одинаковые элементы. Вектор состоит из стрингов и это надо...

Удаление из вектора повторяющихся элементов
есть вектор vector&lt;int&gt; array; я считаю в него из файла, подскажите как мне удалить одинаковые...


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

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