Skip to content

Commit 964e944

Browse files
committed
Two c functions.
1 parent 89383bd commit 964e944

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

STL_examples.cpp

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,7 +1104,33 @@ TEST(destroy_at, ExampleOne) {}
11041104
TEST(destroy, ExampleOne) {}
11051105

11061106
// C library.
1107-
TEST(qsort, ExampleOne) {}
1107+
TEST(qsort, ExampleOne) {
1108+
int a[] = {-10, 1, 14, 3, 2, 2, 5};
1109+
constexpr std::size_t size = sizeof(a) / sizeof(int);
11081110

1109-
TEST(bsearch, ExampleOne) {}
1111+
const auto compare = [](const void* a, const void* b)->int {
1112+
return ( *(int*)a - *(int*) b);
1113+
};
1114+
std::qsort(a, size, sizeof(int), compare);
1115+
1116+
int expected_a[] = {-10, 1, 2, 2, 3, 5, 14};
1117+
EXPECT_EQ(*a, *expected_a);
1118+
}
1119+
1120+
TEST(bsearch, ExampleOne) {
1121+
int a[] = {-2,-1,1,2,3,4,5};
1122+
constexpr std::size_t size = sizeof(a) / sizeof(int);
1123+
1124+
const auto compare = [](const void* a, const void* b)->int {
1125+
const int* aa = (int *)a;
1126+
const int* bb = (int *)b;
1127+
if (*aa < *bb) return -1;
1128+
else if (*aa > *bb) return 1;
1129+
return 0;
1130+
};
1131+
int key = 4;
1132+
int *find = (int *)std::bsearch(&key, a, size, sizeof(int), compare);
1133+
EXPECT_EQ(*find, 4);
1134+
EXPECT_EQ(find - a, 5);
1135+
}
11101136

0 commit comments

Comments
 (0)