Error in Getting Value from Vector of Pairs

后端 未结 1 1650
盖世英雄少女心
盖世英雄少女心 2021-01-18 20:22

Why do I get the error below when accessing the pair\'s values in a iterator of a vector of pairs?

vector< pair > mapper;
if(Hash(inp         


        
相关标签:
1条回答
  • 2021-01-18 20:52

    This is an issue which applies for pointers, too (an iterator behaves pretty much like a pointer). There are two ways to access a member of the value the pointer (or iterator) points to:

    it->first     // preferred syntax: access member of the pointed-to object
    

    or

    (*it).first   // verbose syntax: dereference the pointer, access member on it
    

    The operator precedence turns your expression into

    *(it.first)   // wrong! tries to access a member of the pointer (iterator) itself
    

    which tries to access the member first on the iterator itself, which fail, because the it doesn't have a member called first. If it did, you'd then dereference the value of that member.


    However, in most such cases you should use std::map to map from key to values. Instead of vector<pair<int,string> >, you should use map<int,string> which behaves similar (insertion, iteration and stuff also happens with pairs), but it sorts the keys in the data structure for faster random access:

    map<int,string> mapper;
    if(Hash(input, chordSize) != id){
        mapper.push_back(make_pair(tmp, input));
    }
    
    for (map<int,string>::iterator it = mapper.begin(); it != mapper.end(); ++it)
    {
        cout << "1st: " << it->first << " "
             << "2nd: " << it->second << endl;
    }
    

    Note that an essential difference between a map and a vector of pairs is that a map rearranges the elements by sorting them by their key. The order of insertion can't be queried afterwards. There are cases in which you don't want to do that (when insertion order matters), so in such cases either your solution or a vector with custom types containing at least the key and value are the correct solution.

    0 讨论(0)
提交回复
热议问题