File: lowerbound.cc

package info (click to toggle)
c%2B%2B-annotations 12.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 13,044 kB
  • sloc: cpp: 24,337; makefile: 1,517; ansic: 165; sh: 121; perl: 90
file content (53 lines) | stat: -rw-r--r-- 2,013 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <vector>
    #include <functional>
    using namespace std;

    int main()
    {
        int     ia[] = { 10, 20, 30 };

        cout << "Sequence: ";
        copy(ia, ia + 3, ostream_iterator<int>(cout, " "));
        cout << "\n"
                "15 can be inserted before " <<
                *lower_bound(ia, ia + 3, 15) << "\n"
                "35 can be inserted after " <<
                (lower_bound(ia, ia + 3, 35) == ia + 3 ?
                                    "the last element" : "???") << '\n';

        cout << "Sequence: ";
        copy(ia, ia + 3, ostream_iterator<int>(cout, " "));
        cout << "\n"
                "15 can be inserted before " <<
                *lower_bound(ia, ia + 3, 15, less<int>()) << "\n"
                "35 can be inserted before " <<
                (lower_bound(ia, ia + 3, 35, less<int>()) == ia ?
                                    "the first element " : "???") << '\n';

        vector<int> array{ 5, 10, 20, 20, 20, 30 };
        auto iter = lower_bound(array.begin(), array.end(), 20,
                        [&](int &arrayEl, int value)
                        {
                            cout << "Comparing " << arrayEl <<
                                " (index: " << (&arrayEl - &array[0]) << ")"
                                " to " << value << '\n';
                            return arrayEl < value;
                        }
                    );

        cout << "New 20 to insert at idx " << (iter - array.begin()) << '\n';
    }
    //  Displays:
    //      Sequence: 10 20 30
    //      15 can be inserted before 20
    //      35 can be inserted after the last element
    //      Sequence: 10 20 30
    //      15 can be inserted before 20
    //      35 can be inserted before ???
    //      Comparing 20 (index: 3) to 20
    //      Comparing 10 (index: 1) to 20
    //      Comparing 20 (index: 2) to 20
    //      New 20 to insert at idx 2