2013-03-27 85 views
1

我通過鍵向後循環與非重複的特別感興趣:我可以把multimap迭代邏輯到另一個函數嗎?

#include <map> 
#include <iostream> 
std::multimap<int,int> myMap = { 
    {1,2}, {1,2}, {2,2}, {2,2}, {3,2}, 
}; 

int main() { 
    using namespace std; 
    cout << "the keys backwards:" << endl; 
    typedef multimap<int, int> multimap_type; 
    typedef std::reverse_iterator<multimap_type::iterator> reverse_iterator; 
    for (auto it = myMap.rbegin(), end = myMap.rend(); it != end; it = reverse_iterator(myMap.lower_bound(it->first))) 
    { 
    cout << it->first << endl; 
    } 
} 

正如你看到的,我必須三次重複除其他事項外多重映射名稱。我可以編寫自己的函數來處理所有這些,然後簡單地調用while或range for循環嗎?這樣的:

while((auto it = myIterFunc(myMap)) { 
    //... 
} 

for (auto it : myIterFunc(myMap)) { 
    //... 
} 

回答

2
​​

名稱itmyIterFunc意味着你困惑的新的基於範圍的for循環。變量it不是迭代器,它是範圍的一個元素。函數myIterFunc不應該返回迭代器,它應該返回看起來像一個範圍,即有begin()end()成員,允許迭代所需的範圍。

可以在reverse使用Boost.Range適配器來遍歷它:

#include <boost/range/adaptors.hpp> 
for (auto& val : boost::adaptors::reverse(myMap)) 
    cout << val.first << endl; 

你可以結合起來,與一個filter adaptor跳過重複鍵。 (有一個uniqued adaptor,但它使用==來確定唯一性,而不是隻檢查鍵)

相關問題