2016-09-17 6 views
3

私はunordered_mapの遅延読み込みを使用したいと思います。私はキーのためにマップを検索します。それが存在する場合、私は値を使用します。存在しない場合は、値を作成し、キー、値のペアを置き換えます。C++ unordered_map、効率的な遅延ロードと値の使用

私は最後のmap.find()ステートメントを避けたいです - それは不必要な操作(パフォーマンスが重要です)でなければなりません。それは:-(を失敗することがありますし、私はよりよい解決策を期待したい

注:呼び出し元のルーチンにのみ値へのconstの参照を持つべきであるルーチンを呼び出すの値のインスタンス化を避け

を、私はどのように回避することができます。第2のルックアップし、適切にスコープのconst参照では、呼び出し元に戻ってきた?

時間ファイル

 
` typedef std::vector DataPtrListVector; 
    struct DataCacheStruct 
    { 
     DataPtrListVector dataItemOne; 
    }; 
    typedef boost::unordered_map DataCacheMap; 
    // declare instance variable 
    DataCacheMap dataCacheMap; 
    // declare function 
    const DataCacheStruct& getOrCreateData(const std::string& dataKey,...);` 

のcppファイル

 
` // Lazy Load of DataStruct unordered_map 
    std::string key = someString; 
    const DataCacheStruct& dataStruct = getOrCreateData(key, ...); 


    // 
    const DataCacheStruct& class::getOrCreateData(const std::string key, ...) 
    { 
     DataCacheMap::const_iterator itData = dataCacheMap.find(key); 
     if (itData != dataCacheMap.end()) 
     { 
      return itData->second; 
     } 
     DataCacheStruct newData = doSomethingSlow(); 
     dataCacheMap.emplace(std::make_pair(key, newData)); 
     // Now I want to return newData as a const reference, as per unordered_map 
     // but it goes out of scope before the calling routine can use it. 
     DataCacheMap::const_iterator itData = dataCacheMap.find(key); 
     return itData->second; 
    }` 
+0

[ 'emplace'](http://www.cplusplus.com/reference/map/map/emplace/)はイテレータを返します。要素が挿入された場所 –

答えて

2

すでに述べたように、メソッドemplaceは、新たに挿入された要素の反復子のペアとtrueの値を返します。

あなたは、単に参照を取得し、そのイテレータを使用することができます

auto it_new_insertion = dataCacheMap.emplace(std::make_pair(key, newData)); 
if (it_new_insertion.second == false) { 
// something wrong with memory. handle it 
} 
return it_new_insertion.first->second;