samedi 9 novembre 2019

Vector Iterators (of String) inside a Map

I am trying to create a C++ Map which contains a String as the Key and a C++ Iterator(a Vector Iterator) as the Value. In the Attached Code: I have a Vector called numbers which keeps the key's value and I am taking the iterator of this vector element storing it in the map called Directory. The code should work as written but when I try to print the Directory Key-Value, some of the Values are not appearing in the Directory. I really need a second look at this as I have now spent hours and don't know where I am wrong. Please Help!

#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<string> keys;
map<string, vector<string>::iterator> Directory;
void printStuff()
{
    for (auto x : Directory)
    {
        cout << "Key: " << x.first << "---- Value: " << (*x.second) << endl;
    }
}
void add()
{
    string name;
    string number;
    printf("Enter Key : ");
    cin >> name;
    printf("Enter Value : ");
    cin >> number;
    keys.push_back(number);
    vector<string>::iterator num;
    num = keys.end() - 1;
    Directory[name] = num;
}
int main()
{
    int ch = 10;
    while (ch != 0)
    {
        cout << "1. Add a Contact\n";
        cout << "2. Lookup Directory\n";
        cin >> ch;
        switch (ch)
        {
        case 1:
            add();
            break;

        case 2:
            printStuff();
            break;

        case 3:
            exit(0);
            break;
        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire