find a pair in a STL list where only first element

2019-05-18 02:40发布

问题:

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.