Search code examples
c++returnreturn-value

How to return the content of std::pair?


I am trying to return content of std::pair which has int and string values. What return type for function should I keep?

I tried with both int and char return type but gives error for both. I have given error below:

#include<iostream>
#include<algorithm>
#include<map>
#include<vector>

    std::pair<int,std::string>client()  
{

std::vector<std::string> most { "lion","tiger","kangaroo",
                                 "donkey","lion","tiger",
                                 "lion","donkey","tiger"
                                 };
std::map<std::string, int> src;
for(auto x:most)
    ++src[x];

std::multimap<int,std::string,std::greater<int> > dst;

std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), 
                   [] (const std::pair<std::string,int> &p) {
                   return std::pair<int,std::string>(p.second, p.first);
                   }
                 );

std::multimap<int,std::string>::iterator it = dst.begin();

 for(int count = 0;count<3 && it !=dst.end();++it,++count)
   std::cout<<it->second<<":"<<it->first<<std::endl;

 return *it;  
}

int main()
{
std::multimap<int,std::string>::const_iterator rec;
rec= client();  // Error  no match for ‘operator=’ in ‘rec = client()()’
std::multimap<int,std::string>::iterator it = rec.begin();  //error: ‘std::multimap<int, std::basic_string<char> >::const_iterator’ has no member named ‘begin’

 for(int count = 0;count<3 && rec !=it.end();++it,++count) // error: has no member named 'end' 
   std::cout<<rec->second<<":"<<rec->first<<std::endl;

}

Solution

  • Just return the pair of int & std::string itself as the multimap contains that as its element

    std::pair<int,std::string> client(){
    //...  
    }