简体   繁体   中英

Accessing pair-vector to return using iterator

my task is to overload the [] operator and use girl[index] = partner to write stuff into a pair vector:

class Dancers {
    unsigned long & operator [] (int i);
    vector<pair<int,string>> m_dancers;
};
unsigned long & operator [] (int i) {
    auto iter = lower_bound(m_dancers.first.begin(), m_dancers.first.end(), i, cmpInt);
    m_dancers.first.insert(iter, i);
    //what now?
}     
int main() {
    Pairs girl;
    girl[0] = "Richard";

    return 0;
}

So I've managed to sort the girls and now I have the girl that I want to assign a partner to. From what I understand, now it's time to return the reference so I can assign the partner. How do I do that using the iterator?

And MORE IMPORTANTLY: is there a more efficient way to assign x and y to a pair-vector in a a[x] = y situation? Or am I trying to reinvent a wheel?

Presumably you don't want to insert a new element if there is already an existing key in your map (ie you want a unqiue-key map, not a multi-key map). So you need to check the key and only insert conditionally. And you want to return the mapped element, not they key.

string & operator[](int key) {
    auto it = lower_bound(m_dancers.begin(), m_dancers.end(), key, cmpInt);

    if (it->first != key)
        it = m_dancers.insert(it, make_pair(i, string()));

    return it->second;
}

If you wanted a multi-key map instead, then just omit the conditional check and make the insertion unconditionally. (But then you'd probably want to use upper_bound so that new elements are added at the end of their equal-range, also see here .)

To summarize, things that needed to be fixed in your code:

  • Return type
  • Iterators are from the vector, not from the pair
  • Insertion is conditional
  • Remember the result of the insertion
  • You misspelled your use case, it should say Dancers girl;
  • You are probably misspelling the out-of-line member definition; it should say string & Dancers::operator[](int i) ... (or just define it inline).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM