Path: blob/master/thirdparty/embree/common/algorithms/parallel_map.h
9912 views
// Copyright 2009-2021 Intel Corporation1// SPDX-License-Identifier: Apache-2.023#pragma once45#include "parallel_sort.h"67namespace embree8{9/*! implementation of a key/value map with parallel construction */10template<typename Key, typename Val>11class parallel_map12{13/* key/value pair to build the map */14struct KeyValue15{16__forceinline KeyValue () {}1718__forceinline KeyValue (const Key key, const Val val)19: key(key), val(val) {}2021__forceinline operator Key() const {22return key;23}2425public:26Key key;27Val val;28};2930public:3132/*! parallel map constructors */33parallel_map () {}3435/*! construction from pair of vectors */36template<typename KeyVector, typename ValVector>37parallel_map (const KeyVector& keys, const ValVector& values) { init(keys,values); }3839/*! initialized the parallel map from a vector with keys and values */40template<typename KeyVector, typename ValVector>41void init(const KeyVector& keys, const ValVector& values)42{43/* reserve sufficient space for all data */44assert(keys.size() == values.size());45vec.resize(keys.size());4647/* generate key/value pairs */48parallel_for( size_t(0), keys.size(), size_t(4*4096), [&](const range<size_t>& r) {49for (size_t i=r.begin(); i<r.end(); i++)50vec[i] = KeyValue((Key)keys[i],values[i]);51});5253/* perform parallel radix sort of the key/value pairs */54std::vector<KeyValue> temp(keys.size());55radix_sort<KeyValue,Key>(vec.data(),temp.data(),keys.size());56}5758/*! Returns a pointer to the value associated with the specified key. The pointer will be nullptr of the key is not contained in the map. */59__forceinline const Val* lookup(const Key& key) const60{61typename std::vector<KeyValue>::const_iterator i = std::lower_bound(vec.begin(), vec.end(), key);62if (i == vec.end()) return nullptr;63if (i->key != key) return nullptr;64return &i->val;65}6667/*! If the key is in the map, the function returns the value associated with the key, otherwise it returns the default value. */68__forceinline Val lookup(const Key& key, const Val& def) const69{70typename std::vector<KeyValue>::const_iterator i = std::lower_bound(vec.begin(), vec.end(), key);71if (i == vec.end()) return def;72if (i->key != key) return def;73return i->val;74}7576/*! clears all state */77void clear() {78vec.clear();79}8081private:82std::vector<KeyValue> vec; //!< vector containing sorted elements83};84}858687