Help with vectors (modifying, adding, deleting)

I've been having a really hard time with this assignment. The description of the assignment is a bit long, but basically we were given a code and asked to modify the code in the following ways. The assignment introduces vectors. I managed to figure out how to do everything except for MOD, ADD, and DEL. I know ADD involves pushback, and that MOD and DEL will be similar, but I'm not certain how to code it. Thank you for any help and further explanation, I am lost.

Modify the program as follows:
-print the time in hours and minutes, e.g., print "4 hours and 43 minutes" rather than 283 minutes XDONE
-If a user types “PRINT”, print the list of known countries along with the TV watch time for each country. XDONE
-If the user types "MAX", don't search the country list, but instead find the maximum minutes in the list and print that number along with the corresponding country. XDONE
-If the user types “ADD”, don’t search the country list, but instead allows the user to add a country and its corresponding TV watching time to the vectors. ???
-If the user types “MOD”, asks the user to enter the country for which data is modified and the new TV watching time, and then modifies the vectors accordingly. ???
-If the user types “DEL”, asks the user to enter the country for which data is modified, and then modifies the vectors accordingly. ???
--You can delete an element at a specific index in a vector using the erase function: myVector.erase(myVector.begin() + index);

-If a user types a country name that isn't found, the program behavior should be the same as if the user enters “PRINT”. XDONE


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
#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
   // Source: www.statista.com, 2010
   const int NUM_CTRY = 5;             // Num countries supported
   vector<string> ctryNames(NUM_CTRY); // Country names
   vector<int>    ctryMins(NUM_CTRY);  // Mins TV watched daily
   string userCountry;                 // User defined country
   bool foundCountry = false;          // Match to country supported
   int i = 0;                          // Loop index

   // Define vector contents
   ctryNames.at(0) = "China";
   ctryMins.at(0) = 158;

   ctryNames.at(1) = "India";
   ctryMins.at(1) = 119;

   ctryNames.at(2) = "Russia";
   ctryMins.at(2) = 226;

   ctryNames.at(3) = "UK";
   ctryMins.at(3) = 242;

   ctryNames.at(4) = "USA";
   ctryMins.at(4) = 283;

   // Prompt user for country name
   cout << "Enter country name: ";
   cin >> userCountry;

   // Find country's index and average TV time
   foundCountry = false;
   for (i = 0; i < NUM_CTRY; ++i) {
      if (ctryNames.at(i) == userCountry) {
         foundCountry = true;
         cout << "People in " << userCountry << " watch ";
         cout << ctryMins.at(i)/60 << " hours and " << ctryMins.at(i)%60 << " mins of TV daily." << endl;
         break;
      }
   }
   if (!foundCountry) {

        if ( userCountry == "PRINT") {

            for (i = 0; i < NUM_CTRY; i++){
                cout << ctryNames.at(i) << " - " << ctryMins.at(i)/60 << " hours and " << ctryMins.at(i)%60 << " mins of TV daily." << endl;
                if (i < (NUM_CTRY - 1)){
                    cout << " ";
			}
		}

    }

        else if (userCountry == "MAX") {

            int start = ctryMins.at(0);
            int place;

            for (i = 0; i < NUM_CTRY; i++ ) {

                if (ctryMins.at(i) > start) {

                start = ctryMins.at(i);
                place = i;

                }

            }

            cout << ctryNames.at(place) << " - " << start << " minutes" << endl;

        }

        else if (userCountry == "DEL") {

            cout << "Enter the country to be modified: " << endl;
            cin >> userCountry;

            NUM_CNTRY.erase(NUM_CNTRY.begin() + i);

}

        else if (userCountry == "MOD"){}
        else if (user Country == "ADD") {}

        else {

		cout << userCountry << " Country not found, this is the information we have " << endl;

                for (i = 0; i < NUM_CTRY; i++){
			cout << ctryNames.at(i) << " - " << ctryMins.at(i)/60 << " hours and " << ctryMins.at(i)%60 << " mins of TV daily." << endl;
			if (i < (NUM_CTRY - 1)){
				cout << " ";
			}
		}
   }

   }

   return 0;
}
notes: prefer vector[location] to vector.at(location) in most code.
you have at least one typo on user country (like that, with the space, is bad).


add is just going to be like this:

string tmp;
cout << "enter country name" ;
cin >> tmp;
ctryNames.push_back(tmp);

mod, you have to find the entry you want to modify and then its
ctryNames[found] = tmp; //where tmp is the new modified value.
to find the location, you can either look in a loop yourself or use .find(). .find is preferred, but many students seem to be blocked from using everything.

you need to read this:
https://en.wikipedia.org/wiki/Erase–remove_idiom
or, from their example of a vector of integers, your delete may look like this:

// removes all elements with the value 5
v.erase( std::remove( v.begin(), v.end(), 5 ), v.end() );

Last edited on
There are several different ways to create and initialize the contents of a vector.

1. Create an empty vector and push back the data:
1
2
3
4
5
6
7
   std::vector<std::string> nameCountries;

   nameCountries.push_back("China");
   nameCountries.push_back("India");
   nameCountries.push_back("Russia");
   nameCountries.push_back("UK");
   nameCountries.push_back("USA");


2. Create a sized vector and modify the elements:
1
2
3
4
5
6
7
8
9
   int NUMBER_OF_COUNTRIES = 5;

   std::vector<std::string> nameCountries(NUMBER_OF_COUNTRIES);

   nameCountries[0] = "China";
   nameCountries[1] = "India";
   nameCountries[2] = "Russia";
   nameCountries[3] = "UK";
   nameCountries[4] = "USA";

(Using operator[] is more common than using the vector's at() method.)

3. Since C++11 a vector can be created and initialized with an initializer list:
std::vector<std::string> nameCountries { "China", "India", "Russia", "UK", "USA" };

Notice that 1 & 3 don't need to specify a size to create. 1 increases the size with each push_back(). 3 is sized from the number of arguments in the initializer list.

2 does create a sized vector, but unlike a C style array doesn't need a const variable value.

Now that we've created our vector, totally forget the variable used to create the size. A vector internally stores the number of elements it contains. Use that for your loops.

There are several ways to loop through a vector.

1. Use the vector's size() method:
1
2
3
4
   for (size_t loop = 0; loop < nameCountries.size(); loop++)
   {
      std::cout << nameCountries[loop] << '\n';
   }
China
India
Russia
UK
USA


2. Use vector's iterators:
1
2
3
4
   for (auto itr = nameCountries.begin(); itr != nameCountries.end(); itr++)
   {
      std::cout << *itr << '\n';
   }

(This loop will allow you to modify the vector elements, if you don't want to allow this use the cbegin() and cend() iterators.

3. Use a range-based for loop:
1
2
3
4
   for (auto itr : nameCountries)
   {
      std::cout << itr << '\n';
   }

(This copies the vector. Recommended you use a reference to avoid needless copying:
for (auto& itr : nameCountries). This will let the vector be modified. To prevent modification:
for (const auto& itr : nameCountries))

Vectors are easy to pass into functions. Instead of having the code to PRINT your vectors in main:
1
2
3
4
5
6
7
8
9
10
void display(const std::vector<std::string>& countryNames, const std::vector<int>& countryTimes)
{
   for (size_t loop = 0; loop < countryNames.size(); loop++)
   {
      std::cout << countryNames[loop] << "\t- "
                << countryTimes[loop] / 60 << " hours and "
                << countryTimes[loop] % 60 << " mins of TV daily.\n";

   }
}

Call the function within main: display(ctryNames, ctryMins);
China   - 2 hours and 38 mins of TV daily.
India   - 1 hours and 59 mins of TV daily.
Russia  - 3 hours and 48 mins of TV daily.
UK      - 4 hours and 2 mins of TV daily.
USA     - 4 hours and 43 mins of TV daily.


Adding an element is easy with a push_back() (assume starting with the original 5):
1
2
3
   ctryNames.push_back("France");

   std::cout << "The number of countries is now " << ctryNames.size() << '\n';
The number of countries is now 6


A simple deletion of an element is done with the erase() method:
1
2
   // erasing the 3rd element
   ctryNames.erase(ctryNames.begin() + 2);


Deleting an element by comparing the element's data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   // erasing a specified element
   std::string toErase = "Russia";

   for (auto itr = ctryNames.begin(); itr != ctryNames.end();)
   {
      if (*itr == toErase)
      {
         itr = ctryNames.erase(itr);
      }
      else
      {
         itr++;
      }
   }

   for (const auto& itr : ctryNames)
   {
      std::cout << itr << '\n';
   }
China
India
UK
USA
France


Whew! That is a lot of material to digest. :)

One last thing to consider, consider this VERY extra credit: Instead of creating two separate yet parallel vectors, create just one, using std::pair as the data type (make sure to include <utility>:
1
2
3
   std::vector<std::pair<std::string, int>> country { std::make_pair("China", 158), std::make_pair("India", 119),
                                                      std::make_pair("Russia", 228), std::make_pair("UK", 242),
                                                      std::make_pair("USA", 283) };


Displaying the contents of this vector:
1
2
3
4
5
6
7
   for (const auto& itr : country)
   {
      std::cout << itr.first << "\t- "
                << itr.second / 60 << " hours and "
                << itr.second % 60 << " mins of TV daily.\n";

   }
China   - 2 hours and 38 mins of TV daily.
India   - 1 hours and 59 mins of TV daily.
Russia  - 3 hours and 48 mins of TV daily.
UK      - 4 hours and 2 mins of TV daily.
USA     - 4 hours and 43 mins of TV daily.

http://www.cplusplus.com/reference/utility/pair/
Topic archived. No new replies allowed.