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

橙三吉。 提交于 2019-12-06 02:32:20

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.

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.

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