2012-08-03 12 views
2

在C++中使用STL,我將如何應用函數來獲取std::string(值的打印表示)並將std::string(s)應用到按浮點鍵排序的集合中的每個值它來自應用於地圖中每個對應值的另一個函數?如何將函數應用於地圖的每個值以創建排序序列?

換言之,我想迭代映射中的鍵值對,並創建一組新的鍵值對,其中新鍵和值是舊值的函數。

double getNewKey(origValue value); 
std::string getNewValue(origValue value); 
// Or is it better to map both at once in a pair? 
std::pair<double, std::string> getNewPair(origValue value); 

std::map<origKey, origValue> origMap; 

// Perform some transformation on each value of origMap to get a new map: 
std::map<double, std::string> transformedMap = 
    /* What goes here to use getNewKey() and getNewValue() or use getNewPair()? */ 
    ; 

但是,請不要使用C++ 11。

+2

查找到'的std :: transform'和'的std :: back_inserter' – 2012-08-03 18:55:45

+0

雖然我認爲如果輸出也是一張地圖,你需要'std :: inserter' – Useless 2012-08-03 18:57:02

回答

3

std::transform是你所需要的:

#include <map> 
#include <algorithm> 
#include <iterator> 
#include <iostream> 

// using a few C++11 features to make life easier 
int main(){ 
    std::map<int, int> src, dst; // example KV pair 
    for(unsigned i=0; i < 10; ++i) 
    src[i] = i; 
    typedef std::map<int, int>::value_type kv_pair; 
    std::transform(src.begin(), src.end(), std::inserter(dst, dst.begin()), 
     [](kv_pair const& p){ 
     return kv_pair(p.first, p.second * 2); 
     }); 
    for(auto& p : dst) 
    std::cout << p.first << " : " << p.second << "\n"; 
} 

Live example.

+0

沒有C++ 11特性怎麼樣? – WilliamKF 2012-08-03 18:59:24

+0

@WilliamKF:您需要將lambda更改爲函數/函子。 – 2012-08-03 19:00:53

+1

@WilliamKF:正如David所說,用函數/函數替換lambda表達式,顯然你不能使用ranged-for循環。 – Xeo 2012-08-03 19:01:31

1

[免責聲明,未經測試]:

std::pair<NewKey,NewValue> transform(std::pair<const OldKey,OldValue> const & x) { 
    return std::make_pair(getNewKey(x.first), getNewValue(x.second)); 
} 
... 
std::transfom(m.begin(), m.end(), 
       std::inserter(newmap, m.end()), 
       transform); 
相關問題