removing array[x]?

Hi I'm working on dropping array.
for example, there are these three arrays
[0]mary 2 90
[1]john 1 85
[2]james 3 70
if I cin >> row, for example 0, it should print out
[0]john 1 85
[1]james 3 70
I could remove [0] in my code, moved the array elements, but cannot remove array[2]. can you guys tell me how to do it?

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
#include<iostream>
#include<string>
using namespace std;
int main() {
    string command;
    string name[20];
    int section[20];
    int grade[20];
    int low = 0;
    int high = 0;
    int itemp=0;
    int row;
    int max;
    int i=0;
    
    cout << "Enter a command (add, print, drop, sort, average, quit):\n";
    cin >> command;
    while (command != "quit") {
        if (command == "add") {
            cout << "Enter name section grade:\n";
            cin >> name[i];
            cin >> section[i];
            cin >> grade[i];
            i++;
            }
        else if (command == "print") {
            int j;
            if (i>0) {
            itemp = i-1;
                for (j = 0; j <= itemp; j++) {
                    cout << "[" << j << "]: " << name[j] << " " << section[j] << " " << grade[j] << "\n";
                }
            }
        }
        else if (command == "drop") {
            cin >> row;
            int j;
            if (itemp == row) {
                name[row];
            }
            for (j = row; j <= itemp; j++) {
                name[j] = name[j+1];
                section[j] = section[j+1];
                grade[j] = grade[j+1];
            }
                
        }

return 0;
}
Arrays are a set size and I don't think there is a way to change it once created (tells you how often I use them). You need to look into vectors as you can move elements around like an array and then remove the last element in the array.

http://www.cplusplus.com/reference/vector/vector/?kw=vector

You can add to the end of the list with push_back() or delete the last element with pop_back().


Poorly done fast example:
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
#include <iostream>
#include <vector>

int main()
{
	std::vector<int> vecList;
	vecList.push_back(20);
	vecList.push_back(30);
	vecList.push_back(40);
	
	for (unsigned int i = 0; i < vecList.size(); i++)
	{
		std::cout << vecList[i] << " ";
	}
	std::cout << std::endl;
	
	int temp = vecList[1];
	vecList[0] = temp;
	vecList[1] = vecList[2];
	vecList.pop_back();
	
	for (unsigned int i = 0; i < vecList.size(); i++)
	{
		std::cout << vecList[i] << " ";
	}
	std::cout << std::endl;
	
	return 0;
}
20 30 40 
30 40 
Last edited on
Topic archived. No new replies allowed.