lower_bound(), upper_bound(), and equal_range()

Why use these functions? I looked at the reference on this site, I read about it in my book, looked at it on msdn and I still dont get it. I got it's for searching a multimap because find() cannot find more then one key.

Can anyone please explain with a example or give a good link.

Thanks!
Last edited on
Your imagination is seriously lacking.

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
54
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>

const char* words[] =
{
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "six",
    "six",
    "seven",
    "eight",
    "nine",
    "ten"
};

template <typename T>
void print( T begin, T end )
{
    auto cur = begin ;

    while ( cur != end )
        std::cout << '\t' << *cur++ << '\n' ;
}

int main()
{
    std::sort(std::begin(words), std::end(words), 
        [](const char*a, const char*b){ return std::strcmp(a,b) < 0 ; }) ;
    print(std::begin(words), std::end(words)) ;


    std::string input ;
    while ( std::cout << "Enter a word: "  &&  std::cin >> input  &&  input  != "quit" )
    {
        auto it = std::lower_bound(std::begin(words), std::end(words), input) ;
        std::cout << "Words before '" << input << "':\n" ;
        print(std::begin(words), it) ;

        it = std::upper_bound(std::begin(words), std::end(words), input) ;
        std::cout << "Words after '" << input << "'\n" ;
        print(it, std::end(words)) ;

        auto range = std::equal_range(std::begin(words), std::end(words), input, 
            [](const std::string&a, const std::string&b){return a<b;}) ;
        std::cout << '\'' << input << "' occurs " << range.second - range.first << " times.\n" ;
    }
}
Thank you cire.

I wont be asking any more questions in this forum now, at least this section lol.

I got all the basics of OOP and everything done. Almost done the introduction to STL and then I am moving on to GUI Programming.

Thanks for all your help! You answered almost all of my questions, even though alot of them were the obvious. You are definitely the most helpful person on this forum! Also thanks to everyone else who helped as well :D

Thank you so much!

edit: ok maybe just one more :D
Last edited on
Topic archived. No new replies allowed.