📌  相关文章
📜  C ++中的Pairs Map上的lower_bound()和upper_bound()的实现

📅  最后修改于: 2021-05-31 22:12:09             🧑  作者: Mango

先决条件:在C++ STL中映射lower_bound()函数,在C++ STL中映射upper_bound()函数

在本文中,我们将讨论成对映射中lower_bound()和upper_bound()的实现。

  • lower_bound():它返回一个迭代器,该迭代器指向[first,last)范围内的第一个元素,该元素的值大于或等于给定值“ val” 。但是在成对映射中,对pair(x,y)的Lower_bound()将返回一个迭代器,该迭代器指向第一个值大于或等于x且第二个值大于等于y的对
    如果不满足上述条件,则返回指向{Map.size(),0}对的迭代器。

    句法:

    mp.lower_bound({a, b})
    
    where,
    mp is the map of pairs
    and {a, b} whose lower_bound
    is to be found
    
  • upper_bound():它返回一个迭代器,该迭代器指向[first,last)范围内的第一个元素,该元素的值大于给定值“ val” 。但是在成对映射中,对pair(x,y)的upper_bound()将返回一个迭代器,该迭代器指向第一个值大于x且第二个值大于y的对
    如果不满足上述条件,则返回指向{Map.size(),0}对的迭代器。

    句法:

    mp.upper_bound({a, b})
    
    where,
    mp is the map of pairs
    and {a, b} whose upper_bound
    is to be found
    

以下是在成对映射中演示lower_bound()和upper_bound()的程序:

程序1:

// C++ program to demonstrate lower_bound()
// and upper_bound() in Map of Pairs
  
#include 
using namespace std;
  
// Function to implement lower_bound()
void findLowerBound(
    map, int>& mp,
    pair& p)
{
  
    // This iterator points to the
    // lower_bound() of given pair
    auto low = mp.lower_bound(p);
  
    cout << "lower_bound() for {2, 5}"
         << " is: {"
         << (*low).first.first << ", "
         << (*low).first.second
         << "}" << endl;
}
  
// Function to implement upper_bound()
void findUpperBound(
    map, int>& mp,
    pair& p)
{
  
    // This iterator points to the
    // upper_bound() of given pair
    auto up = mp.upper_bound(p);
  
    cout << "upper_bound() for {2, 5}"
         << " is: {"
         << (*up).first.first << ", "
         << (*up).first.second
         << "}" << endl;
}
  
// Driver Code
int main()
{
    // Declare map of Pairs
    map, int> mp;
  
    // Insert Pairs in Map
    mp.insert({ { 2, 3 }, 8 });
    mp.insert({ { 4, 1 }, 5 });
    mp.insert({ { 7, 1 }, 3 });
    mp.insert({ { 9, 3 }, 1 });
    mp.insert({ { 5, 0 }, 3 });
  
    // Given pair {2, 5}
    pair p = { 2, 5 };
  
    // Function Call to find lower_bound
    // of pair p in map mp
    findLowerBound(mp, p);
  
    // Function Call to find upper_bound
    // of pair p in map mp
    findUpperBound(mp, p);
  
    return 0;
}
输出:
lower_bound() for {2, 5} is: {4, 1}
upper_bound() for {2, 5} is: {4, 1}
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”