I'm trying to get familiar with maps, so im making a program that enters names and ages and puts them into a map but I dont know how to actually set them in the map since it takes 2 values.
std::pair<string, int> in this case, as the map is a map<string, int>
To create a pair object, you can specify the kind of pair yourself to insert, which would be something like: newMap.insert ( std::pair<string,int>(std::string("Beans"),1) );
or use the std::make_pair function, something like this: newmap.insert(std::make_pair("Beans",1));
Great, thank you, I got it working. I have one question though about something unrelated to map, in my for loop, I had a getline, and after it would get the first name and age it would then skip thge name and get the age and screw up, why is that? I changed it to a cin >> and it works fine now. How would I use getline in the for loop?
As you said a map takes two values, so line 20 should not be there until you have both "name" and "age" to put into the map.
The easiest way to add to a map is:
newMap[name] = age;
which would be done on line 23.
Line 17 I would put above the for loop and replace the variable "nameCount" with 5.
Change line 17 something like this: std::cout << "Enter name " << i + 1 << ": ";
and maybe something similar for line 21. And about line 25 print a blank line.
After this "nameCount" would no longer have any use.
After the cin >> age; the next line needs to be: std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires heder file <limits>.
#include <iostream>
#include <map>
#include <string>
int main()
{
std::map< std::string, int > name_age_map;
std::string name ;
int age = 0;
for(int i = 0; i < 5; i++)
{
std::cout << "Name: ";
std::getline( std::cin, name ) ; // unformatted input
std::cout << "Age: ";
std::cin >> age ; // formatted input
// formatted input leaves trailing white space (typically a new line)
// in the input buffer. extract it and throw it away. otherwise
// the unformatted input (for name), which does not skip leading white space
// would read only up to the new line remaining in the input buffer
std::cin.ignore( 1000, '\n' ) ;
// it is more efficient (and, in this case, less verbose) to construct the string in-place
// within the map. however, if the name is already present in the map, the age would not be
// updated. we can check for this; but in this simple example the check is omitted
name_age_map.emplace( name, age );
}
std::cout << "\n\n\n" ;
// classical for loop: simpler to let the compiler deduce the type of the iterator
// that way, the code is more readable and more maintenance-free
for( auto it = name_age_map.begin(); it != name_age_map.end(); ++it )
{
std::cout << "Name: " << it->first << " Age: " << it->second << '\n';
}
// simplest: in general favour a range-based loop over a classical for loop
for( constauto& pair : name_age_map )
{
std::cout << "Name: " << pair.first << " Age: " << pair.second << '\n';
}
}