Skip to content

Commit 9124e2c

Browse files
committed
Finish bsearch functions.
1 parent b6e5dff commit 9124e2c

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

STL_examples.cpp

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -644,19 +644,39 @@ TEST(nth_element, ExampleOne) {
644644

645645
// Binary search operations (on sorted ranges).
646646
TEST(lower_bound, ExampleOne) {
647-
647+
const std::vector<int> data{1,2,3,4,5,6,7,8,9,9,10};
648+
const auto lower = std::lower_bound(data.cbegin(), data.cend(), 4);
649+
EXPECT_EQ(*lower, 4);
650+
// Lower bound includes the current element.
651+
EXPECT_EQ(lower - data.cbegin(), 3);
648652
}
649653

650654
TEST(upper_bound, ExampleOne) {
651-
655+
const std::vector<int> data{1,2,3,4,5,6,7,8,9,9,10};
656+
const auto upper = std::upper_bound(data.cbegin(), data.cend(), 9);
657+
EXPECT_EQ(*upper, 10);
658+
// Upper bound goes one past the current element.
659+
EXPECT_EQ(upper - data.cbegin(), 10);
652660
}
653661

654662
TEST(binary_search, ExampleOne) {
663+
const std::vector<int> data{1,2,3,4,5,6,7,8,9,9,10};
664+
const bool found = std::binary_search(data.cbegin(), data.cend(), 3);
665+
EXPECT_TRUE(found);
655666

667+
const bool not_found = std::binary_search(data.cbegin(), data.cend(), 11);
668+
EXPECT_FALSE(not_found);
656669
}
657670

658671
TEST(equal_range, ExampleOne) {
659-
672+
// This is useful when you want an upper and a lower bound.
673+
const std::vector<int> data{1,2,3,3,4,4,5,5,5,6,7,8};
674+
const auto [lower, upper] = std::equal_range(data.cbegin(), data.cend(), 5);
675+
EXPECT_EQ(*lower, 5);
676+
EXPECT_EQ(lower - data.cbegin(), 6);
677+
678+
EXPECT_EQ(*upper, 6);
679+
EXPECT_EQ(upper - data.cbegin(), 9);
660680
}
661681

662682
// Other operations (on sorted ranges).

0 commit comments

Comments
 (0)