C++ 程序:在 STL 向量中使用upper_bound()方法

原文:https://www.studytonight.com/cpp-programs/cpp-program-using-upper_bound-method-in-vector-stl

大家好!

在本教程中,我们将学习 STL 中的 upper_bound()方法的工作原理,以及它在 C++ 编程语言中使用 Vector 的实现。

什么是向量?

向量与动态数组相同,能够在插入或删除元素时自动调整自身大小。这使得它们比普通的固定大小的静态数组更先进。

要了解更多关于 CPP 中的向量,我们将推荐您访问 C++ STL 向量

upper_bound()方法:

upper_bound()方法是一个迭代器,指向第一个元素,该元素的值大于给定值

为了更好地理解,请参考下面给出的注释良好的 C++ 代码。

代号:

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    cout << "\n\nWelcome to Studytonight :-)\n\n\n";
    cout << " =====  Program to demonstrate the working of upper_bound() method of STL, in CPP  ===== \n\n";

    cout << "\n\nDeclaring a Vector and Filling it with integers.\n\n";

    //create an empty vector
    vector<int> v;

    //insert elements into the vector
    v.push_back(10);
    v.push_back(12);
    v.push_back(35);
    v.push_back(65);
    v.push_back(21);
    v.push_back(90);

    //prining the vector
    cout << "The elements of the Vector are: ";

    vector<int>::iterator it;

    //Printing the elements using an iterator
    for (it = v.begin(); it != v.end(); it++)
    {
        cout << *it << " ";
    }

    //Sorting the vector in ascending order
    sort(v.begin(), v.end());

    //prining the Sorted vector
    cout << "\n\nThe elements of the Vector after Sorting are: ";

    //Another way of printing the elements of a vector
    for (int i : v)
    {
        cout << i << " ";
    }

    vector<int>::iterator up;

    up = upper_bound(v.begin(), v.end(), 35);

    cout << "\n\nupper_bound returns an iterator pointing to the first element which has a value greater than the given value.";

    cout << "\n\nThe index (starting from 0) of the upper_bound of 35 is: " << (up - v.begin()) << '\n';

    cout << "\n\nNote that as per the definition, it only considers the numbers greater than it and not itself.\n";

    cout << "\n\n\n";

    return 0;
}

输出:

C++ upper bound

我们希望这篇文章能帮助你更好地理解upper_bound()方法的概念及其在 C++ 中的实现。如有任何疑问,请随时通过下面的评论区联系我们。

继续学习: