I have declared a multimap that holds string and map. That map holds string and pair of ints.

std::multimap<string, std::map<string, std::pair<int, int>>> traders;
std::map<string, std::pair<int, int>> products;
std::pair<int, int> side;

I add new values to that multimap by:

products.emplace(stringValue1, std::pair<int, int>(intValue1, intValue2));
traders.emplace(stringValue2, products);

Now, the problem I have. I am trying to find traders that have the same key value and then read associated values of each found trader. To find traders with given key value, I use following code and it works

std::pair< 
    std::multimap<string, std::map<string, std::pair<int, int>>>::iterator, 
    std::multimap<string, std::map<string, std::pair<int, int>>>::iterator
> ret;
ret = traders.equal_range(stringKeyValue);

I can access first value of the multimap (which is string) by following code

std::multimap<string, std::map<string, std::pair<int, int>>>::iterator itr1 = ret.first;
std::cout <<  " " << itr1->first << std::endl;

but I can't access any other elements of the multimap. If you look at my multimap declaration, I not only need to access first string, but also second string and a pair of ints that are associated with the trader returned by.

I was trying may different things but none of them worked and my head is melted now. I hope you can help guys. Thanks.

有帮助吗?

解决方案

Maybe this will help. I haven't tested it.

typedef std::map<string, std::pair<int, int> > TraderProductMap;
typedef std::multimap<string, TraderProductMap> TraderMap;

typedef TraderProductMap::iterator TraderProductMapIter;
typedef TraderMap::iterator TraderMapIter;

std::pair<TraderMapIter, TraderMapIter> range;
range = traders.equal_range(stringKeyValue);

for(TraderMapIter itTrader = range.first;itTrader != range.second;++itTrader) {

    std::cout <<  " " << itTrader->first << std::endl;

    for(TraderProductMapIter itProduct = itTrader->second.begin();itProduct != itTrader->second.end();++itProduct) {
        std::cout <<  "  " << itProduct->first << " " itProduct->second->first << " " << itProduct->second->second << std::endl;
    }

    std::cout << std::endl;

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top