如何查找C++ 11中等於或高於KEY_1且低於KEY_2的地圖中的所有鍵?如何在C++ 11中查找等於或高於KEY_1且低於KEY_2的地圖中的所有鍵?
我通常使用Java進行編程,並沒有太多的C++經驗。
如何查找C++ 11中等於或高於KEY_1且低於KEY_2的地圖中的所有鍵?如何在C++ 11中查找等於或高於KEY_1且低於KEY_2的地圖中的所有鍵?
我通常使用Java進行編程,並沒有太多的C++經驗。
請嘗試以下
auto minmax = std::minmax(KEY_1, KEY_2, m.key_comp());
auto first = m.lower_bound(minmax.first);
auto last = m.upper_bound(minmax.second);
下面是一個示範項目:
#include <iostream>
#include <map>
#include <algorithm>
int main()
{
std::map<int, int> m =
{
{ 1, 10 }, { 2, 20 }, { 3, 30 }, {4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
};
int key1 = 5;
int key2 = 3;
auto minmax = std::minmax(key1, key2, m.key_comp());
auto first = m.lower_bound(minmax.first);
auto last = m.upper_bound(minmax.second);
for (auto current = first; current != last; ++current)
{
std::cout << "{ " << current->first
<< ", " << current->second
<< " }" << std::endl;
}
return 0;
}
輸出是
{ 3, 30 }
{ 4, 40 }
{ 5, 50 }
或者一個更有趣的例子
#include <iostream>
#include <map>
#include <algorithm>
#include <functional>
int main()
{
std::map<int, int> m1 =
{
{ 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
};
int key1 = 5;
int key2 = 3;
auto minmax1 = std::minmax(key1, key2, m1.key_comp());
auto first1 = m1.lower_bound(minmax1.first);
auto last1 = m1.upper_bound(minmax1.second);
for (auto current = first1; current != last1; ++current)
{
std::cout << "{ " << current->first
<< ", " << current->second
<< " }" << std::endl;
}
std::cout << std::endl;
std::map<int, int, std::greater<int>> m2 =
{
{ 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 }
};
auto minmax2 = std::minmax(key1, key2, m2.key_comp());
auto first2 = m2.lower_bound(minmax2.first);
auto last2 = m2.upper_bound(minmax2.second);
for (auto current = first2; current != last2; ++current)
{
std::cout << "{ " << current->first
<< ", " << current->second
<< " }" << std::endl;
}
return 0;
}
輸出是
{ 3, 30 }
{ 4, 40 }
{ 5, 50 }
{ 5, 50 }
{ 4, 40 }
{ 3, 30 }
如果你想排除的範圍的上限,那麼你必須方法upper_bound
的號召代替以lower_bound
這是該代碼將包含相應的按鍵lower_bound
兩個呼叫。例如
auto first1 = m1.lower_bound(minmax1.first);
auto last1 = m1.lower_bound(minmax1.second);
如果你想排除的範圍的下限,那麼你可以寫
auto first1 = m1.upper_bound(minmax1.first);
auto last1 = m1.upper_bound(minmax1.second);
// All elements in [KEY1 KEY2)
auto it1 = m.lower_bound (KEY_1 ) ;
auto it2 = m.lower_bound( KEY_2 ) ;
for(auto it = it1 ; it != it2 ; ++it)
{
// it->first , it->second
}
的什麼都鑰匙? – juanchopanza 2014-11-01 09:21:45
@juanchopanza整數是關鍵,我需要找到所有範圍[Key_one,Key_two) – 2014-11-01 09:22:47
@PaolaJ。你試過什麼了? – quamrana 2014-11-01 11:18:52