Valrok Valrok - 2 months ago 8
C++ Question

Enter standard input for values of map

I'm trying to write a map that takes in an integer as the key and then an x amount of int values that are given to it via standard input. This is my first time working with maps so I'm running into several issues and was wondering if someone could help understand better what I am doing incorrectly. Normally with a vector/array the following would work fine:

int standardInput;
for (int i = 1; i<=n; i++){
cin standardInput;
array[i] = standardInput;
}


I can't get that to work similarly when using a map:

int numberToCompare = 4;
map<int numberToCompare, int>myMap;
int standardInput;
cout << "Enter numbers: " << endl;
for (int i = 1; i <= n; i++){
cin standardInput;
myMap.insert(standardInput);
}


I'm still trying to understand about the key and values. The way I understood when reading about maps was that with a map the key is unique unlike multi maps. What I don't know how to do is allow user input to fill the rest of the map. I saw lots of examples online where inside the code people manually entered all of the input doing the following (this goes against what I want to accomplish).

portMap_.insert(pair<string,int>("fourth", 4444));
portMap_.insert(pair<string,int>("fifth", 5555));


EDIT: To clarify in case I caused some confusion, I'm trying to fill a map with numbers that are given via standard input.

Answer

I would recommend you browse the documentation for std::map found here. Then take a look at the examples provided in the insert() method documentation here.

The declare a map object, you need to specify the type for the key and the type for the value by providing the type name as template parameters:

#include <map>
using namespace std;

map<int,int> myMap;

If you then want to insert a key/value pair:

int myKey = 10;
int myVal = 100;
myMap.insert(pair<int,int>(myKey, myVal));

The above can be made a bit more terse with some typedefs:

typedef map<int,int> IntMap;
typedef pair<int,int> IntPair;

IntMap myMap;
myMap.insert(IntPair(10, 100));

If you want the key/value pairs to be provided by user input, just write a simple loop that accepts the values from standard input and insert the values into your map.

There are plenty of resources here for reading values from standard input. Something like the below would do the trick:

// pseudo-code
while (did the user quit?)
{
    int key   = 0;
    int value = 0;

    cin >> key >> value;

    // maybe if the user enters -1, then you quit, otherwise:

    myMap.insert(pair<int,int>(key, value));
}