简体   繁体   English

访问对向量以使用迭代器返回

[英]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: 我的任务是重载[]运算符,并使用girl[index] = partner将内容写入对向量:

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? 而且更重要的是:在a[x] = y情况下,有没有更有效的方法将xy分配给对向量? 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). 想必你不想插入一个新的元素,如果已经有在地图中现有的密钥(即你想要一个unqiue关键词表,而不是一个多键映射)。 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 .) (但是然后您可能希望使用upper_bound以便在等距范围的末尾添加新元素,也请参见此处 。)

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; 您拼错了用例,应该说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). 它应该显示string & Dancers::operator[](int i) ...(或只是内联定义)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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