Skip to content

Commit d00f4c2

Browse files
committedMar 20, 2021
lower_bound and upper_bound operations for set
1 parent 88d14aa commit d00f4c2

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed
 

‎README.md

+2
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ step x x x x x x
181181
range x x x x x x
182182
find x x x x x x
183183
count x x x
184+
lower_bound x
185+
upper_bound x
184186
erase x x x x x x
185187
copy x x x x x x
186188
begin x x x x x x

‎ctl/set.h

+38
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,44 @@ JOIN(B, init)(T key, int color)
244244
return self;
245245
}
246246

247+
static inline B*
248+
JOIN(A, lower_bound)(A* self, T key)
249+
{
250+
B* node = self->root;
251+
B* result = NULL;
252+
while(node)
253+
{
254+
int diff = self->compare(&key, &node->key);
255+
if(diff <= 0)
256+
{
257+
result = node;
258+
node = node->l;
259+
}
260+
else
261+
node = node->r;
262+
}
263+
return result;
264+
}
265+
266+
static inline B*
267+
JOIN(A, upper_bound)(A* self, T key)
268+
{
269+
B* node = self->root;
270+
B* result = NULL;
271+
while(node)
272+
{
273+
int diff = self->compare(&key, &node->key);
274+
if(diff < 0)
275+
{
276+
result = node;
277+
node = node->l;
278+
}
279+
else
280+
node = node->r;
281+
}
282+
return result;
283+
}
284+
247285
static inline B*
248286
JOIN(A, find)(A* self, T key)
249287
{

‎tests/func/test_set.cc

+30
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ main(void)
6363
TEST_SWAP,
6464
TEST_COUNT,
6565
TEST_FIND,
66+
TEST_LOWER_BOUND,
67+
TEST_UPPER_BOUND,
6668
TEST_COPY,
6769
TEST_EQUAL,
6870
TEST_UNION,
@@ -177,6 +179,34 @@ main(void)
177179
digi_free(&kd);
178180
break;
179181
}
182+
case TEST_LOWER_BOUND:
183+
{
184+
int key = TEST_RAND(TEST_MAX_SIZE);
185+
digi kd = digi_init(key);
186+
set_digi_node* aa = set_digi_lower_bound(&a, kd);
187+
auto bb = b.lower_bound(DIGI(key));
188+
if(bb == b.end())
189+
assert(set_digi_end(&a) == aa);
190+
else
191+
assert(*bb->value == *aa->key.value);
192+
CHECK(a, b);
193+
digi_free(&kd);
194+
break;
195+
}
196+
case TEST_UPPER_BOUND:
197+
{
198+
int key = TEST_RAND(TEST_MAX_SIZE);
199+
digi kd = digi_init(key);
200+
set_digi_node* aa = set_digi_upper_bound(&a, kd);
201+
auto bb = b.upper_bound(DIGI(key));
202+
if(bb == b.end())
203+
assert(set_digi_end(&a) == aa);
204+
else
205+
assert(*bb->value == *aa->key.value);
206+
CHECK(a, b);
207+
digi_free(&kd);
208+
break;
209+
}
180210
case TEST_COPY:
181211
{
182212
set_digi aa = set_digi_copy(&a);

0 commit comments

Comments
 (0)