Home > Enterprise >  How to assign the values ​returned by make_pair to the inserter
How to assign the values ​returned by make_pair to the inserter

Time:12-29

I have to pass an inserter as a function argument, so that I assign the values ​​returned by make_pair to the inserter and store them into a container. Can somebody help me to understand the make_pair and inserter correlation?

#include <iostream>
#include <list>
#include <vector>
#include <exception>
#include <map>
#include <utility>

template<typename T,typename U,typename V,typename K>
void fun(T beg1,T end1, U beg2, U end2,V ins,K fun){
  try{ 
    if(std::distance(beg1,end1)!=std::distance(beg2,end2)){
      {
        throw std::string{"They're not the same size"};
      }
    }
   } catch(std::string& ex){
     std::cout<<ex<<std::endl;
   }

   while(beg1!=beg2){
     if(!(fun(*beg1,*beg2))){
       ins=std::make_pair(*beg1,*beg2);
         beg1;
         beg2;
     }
   }
}

int main(){
  std::vector<std::string> l1{"mel","ana","tim"};
  std::vector<std::string> l2{"ana","mel","tim"};
  std::pair<std::string, std::string> l3; 

  auto l=[](const std::string& a, const std::string& b){
    return a==b;
  };

  fun(begin(l1),end(l1),begin(l2),end(l2),inserter(?),l);
}

CodePudding user response:

make_pair simply makes a pair object. It doesn't do anything tricky.

It sounds like what you want is something like std::back_inserter, which returns an iterator you can write results to:

std::vector<std::pair<std::string, std::string>> results;

fun(begin(l1),end(l1),begin(l2),end(l2),std::back_inserter(results),l);

and then in your fun, you write to the iterator:

*ins = std::make_pair(*beg1,*beg2);
ins  ;

Another option is that you make an inserter function:

std::vector<std::pair<std::string, std::string>> results;
auto ins =[](const std::string& a, const std::string& b){
    results.emplace_back(std::make_pair(a,b));
  };

And then in your fun, you call the function:

ins(*beg1,*beg2);
  • Related