0

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);
}
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
Xavi
  • 57
  • 8
  • what is the desired effect of `ins=std::make_pair(*beg1,*beg2);` ? that `*beg1` is inserted into `l1` and `*beg2` into `l2` ? Where did you get that idea of an `inserter` from? – 463035818_is_not_an_ai Dec 28 '22 at 18:52
  • this is a homework assignment, we need to write generic function that will compare the elements of two containers and if they are not equal make pairs and assign them to a new collection – Xavi Dec 28 '22 at 18:56
  • 1
    Also use of boost::zip_iterator makes this trivial: http://coliru.stacked-crooked.com/a/b1cdd3233446bd90 – Mooing Duck Dec 28 '22 at 19:12
  • thank you, but to be honest, that way is too complicated for me, I'm a newbie – Xavi Dec 28 '22 at 19:18

1 Answers1

0

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);
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158