find a pair in a STL list where only first element is known

十年热恋 提交于 2020-01-02 07:05:14

问题


assumend I have a (filled) list

std::list<std::pair<int,otherobject>> myList;

and want to find() the first element within this list, where int has a specific value - how can I do that?

To explain it a bit further:

I want to append these pairs to the list with an int that identifies otherobject but is not unique. The order where these int/otherobject pairs arrive has to be kept.

When an int is found during access to elements of this list the first occurence of that int has to be given back (and removed).

Thanks!


回答1:


I think I'd use the standard find_if algorithm:

auto pos = std::find_if(myList.begin(), myList.end(),
                        [value](std::pair<int, otherobject> const &b) { 
                            return b.first == value; 
                        });

That gives an iterator to the element with the required value -- from there, you can copy the value, delete the value, etc., just like with any other iterator.




回答2:


According to your need the better option would be to use a multimap. In you case it would give :

std::multimap<int, otherobject> myMultiMap;

Then when looking for otherobjects linked to a int ( myInt) you'll do :

    std::pair<std::multimap<int, otherobject>::iterator, std::multimap<int, otherobject>::iterator> result = myMultiMap.equal_range(myInt);

    for (std::multimap<int,otherobject>::iterator iter=result.first; iter!=result.second; ++iter)
    {
        std::cout << it->second;
    }

This is a STL container so you'll easilly find online documentation.



来源:https://stackoverflow.com/questions/17965728/find-a-pair-in-a-stl-list-where-only-first-element-is-known

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!