Last active
November 25, 2019 14:32
-
-
Save SteffenSeckler/91943b881677f3cbe7b2d7d475471ee8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <utility> | |
#include <vector> | |
// template <class maptype> | |
void mapAdd(std::map<size_t, double> &inout, std::map<size_t, double> &in) { | |
for (auto initer = in.begin(), outiter = inout.begin(); initer != in.end(); ++initer, ++outiter) { | |
outiter->second += initer->second; | |
} | |
} | |
template <class vectype, class typevectype> | |
std::map<size_t, double> foo(const vectype &typeDoubleVec, | |
const typevectype &typevec) { | |
std::map<size_t, double> mymap; | |
// ensure that mymap has all elements of myvec. | |
for (auto &elem : typevec) { | |
mymap[elem]; | |
} | |
#pragma omp parallel default(none) shared(typeDoubleVec, mymap) | |
{ | |
// we create a local copy of mymap for each thread! | |
auto localmap = mymap; | |
#pragma omp for | |
// iterate over the vector and add them to the local map | |
for (size_t i = 0; i < typeDoubleVec.size(); ++i) { | |
localmap.at(typeDoubleVec[i].first) += typeDoubleVec[i].second; | |
} | |
#pragma omp critical | |
// sum up the local map to the global map using a critical section | |
mapAdd(mymap, localmap); | |
} | |
return mymap; | |
} | |
int main() { | |
std::vector<std::pair<size_t, double>> myvec{{1, 2.}, {3, 4.}, {1, 3.}, {3, 5.}, {2, 1.}}; | |
std::vector<size_t> types{1, 3, 2}; | |
auto sumMap = foo(myvec, types); | |
for (auto &[type, sum] : sumMap) { | |
std::cout << "type:" << type << "sum:" << sum << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment