My project deals with divide-n-conquer strategy to parralelize an existing algorithm.
The algoritm returns a std::multimap<int, std::pair<int, int>>
. Above is a sketch of a premilinary (single_thread) version.
typedef std::multimap<int, std::pair<int, int>> Map ;
struct Box
{
std::pair<int, int> top_left, bottom_right ;
}
Map my_algo(Box, a_box)
{
Map final_m ;
if (not is_small(a_box))
{
box b1, b2 ;
split_box(a_box, &b1, &b2) ; // this function divides the box in two halves
Map m1 = my_algo(b1) ;
Map m2 = my_algo(b2) ;
// this line will not compile. final_m.begin() is not accepted.
std::merge (m1.begin(), m1.end(), m2.begin(), m2.end(), final_m.begin()) ;
}
return final_m ;
}
I know I could use insert instead or merge to do the merging (as explained here). But insert is in O(N.Log(n)) while merge is in O((N)). Because of the number of merging operations involved in the algorithm, time-complexity matters.
Thanks for helping, Olivier
EDIT:
Thanks to jogojapan (see answer below), this is a working demo of the corrected code:
#include <iostream>
#include <map>
#include <iterator>
#include <algorithm>
typedef std::pair<int, int> Cell ;
typedef std::multimap<int, Cell> Border_map ;
void test_merge_maps_1()
{
Border_map a, b, c ;
std::cout << std::endl << "a" << std::endl ;
for (int i=1; i<10; i+=2)
{
a.insert(std::pair<int, Cell>(i, Cell(i,i))) ;
std::cout << i << " " ;
}
std::cout << std::endl << "b" << std::endl ;
for (int i=2; i<11; i+=2)
{
b.insert(std::pair<int, Cell>(i, Cell(i,i))) ;
std::cout << i << " " ;
}
std::cout << std::endl << "merge" << std::endl ;
std::merge(a.begin(), a.end(), b.begin(), b.end(), inserter(c,end(c))) ;
std::cout << "result" << std::endl ;
for(auto x: c)
std::cout << x.first << " " ;
std::cout << std::endl ;
}
int main(void)
{
test_merge_maps_1() ;
return 0 ;
}