any dangers to storing map iterator in vector?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • divideby0
    New Member
    • May 2012
    • 131

    any dangers to storing map iterator in vector?

    I'm trying out the code below; it runs and produces the output I'd expect, but could it lead to undefined behavior?

    To test with, I show the key and wait for user input; if the input doesn't match the value, the iterator is stored in the vector.

    Code:
    map<string, string> test;
    map<string, string>::iterator it;
    
    vector<map<string, string>::iterator> bad_input;
    
    string input;
    
    test["key 1"] = "value 1";
    test["key 2"] = "value 2";
    test["key 3"] = "value 3";
    
    for(it = test.begin(); it != test.end(); ++it)
    {
       cout << it->first;
       cin >> input;
    
       if(it->second != input)
           bad_input.push_back(it);
    }
    
    for(unsigned i=0; i < bad_input.size(); ++i)
        cout << bad_input[i]->first
             << "   "
             << bad_input[i]->second
             << "\n";
    I am also interested in knowing if I can use an iterator to walk through the vector? I tried

    Code:
    vector<map<string, string>::iterator>::iterator v_it;
    
    for(v_it = bad_input.begin(); v_it != bad_input.end(); ++v_it)
        cout << v_it-> ??
    However, I couldn't figure out how to access "first" and "second" using this method. Is it possible to do so?

    TIA
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    There is nothing inherently wrong in storing a map iterator in a string but remember that if the item is deleted from the map the iterator becomes invalid so it is probably not something you would want to keep stored long term but temporarily storing it during the execution of a single function would probably be OK.

    However my own approach to such a problem would be to store the key of the item of interest in a vector. Yes this may be a little less efficient but it does not suffer from the issue of the iterator possibly becoming invalid, if the item is deleted from the map then when you read your key from your vector and try to use it to access your map you get an error that can be dealt with rather than some form of undefined behaviour.

    However if you go ahead and store an iterator to a map in a vector and then you would use the vector iterator like this

    Code:
    vector<map<string, string>::iterator>::iterator v_it;
    
    // Point the iterator somewhere
    
    (*v_it)->first; // * derefence the vector iterator into the type of the vector, map iterator 
                    // then -> access members of the map iterator

    Comment

    • divideby0
      New Member
      • May 2012
      • 131

      #3
      Banfa, thank you for your time and explanation; as always, I appreciate it.

      Comment

      Working...