BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bdlb_cstringless

Detailed Description

Outline

Purpose

Provide a standard compatible less-than predicate for C-strings.

Classes

See also
bsl_map, bsl_set

Description

This component provides a struct, bdlb::CStringLess, that defines a functor that compares two null-terminated strings using a case-sensitive string comparison, rather than simply comparing the two addresses (as the std::less functor would do). This lexicographical ordering makes CStringLess suitable for supporting C-strings as keys in associative containers. Note that the container behavior would be undefined if the strings referenced by such pointers were to change value.

Usage

This section illustrates intended use of this component.

Example 1: Basic Use of bdlb::CStringLess

Suppose we need a container to store set of unique C-strings. The following code illustrates how to use bdlb::CStringLess as a comparator for the standard container set, to create a set of unique C-string values.

Note that the default comparator for const char * (i.e., bsl::less<const char *>) compares the supplied addresses, rather than the contents of the C-strings to which those address typically refer. As a result, when using the default comparator, identical C-string values located at different addresses, will be successfully added to a set container. bdlb::CStringLess compares the values of the C-strings ensuring that a set, using CstringLess as a comparator, is a set of unique string values.

First, we create several C-strings:

const char newYork[] = "NY";
const char losAngeles[] = "LA";
const char newJersey[] = "NJ";
const char sanFrancisco[] = "SF";
const char anotherNewYork[] = "NY";

Next, we create two containers, one with default comparator and another using bdlb::CstringLess as a comparator:

bsl::set<const char *> defaultComparatorContainer;
Definition bslstl_set.h:657

Now, we fill containers with the same contents:

defaultComparatorContainer.insert(newYork);
defaultComparatorContainer.insert(losAngeles);
defaultComparatorContainer.insert(newJersey);
defaultComparatorContainer.insert(sanFrancisco);
defaultComparatorContainer.insert(anotherNewYork);
userComparatorContainer.insert(newYork);
userComparatorContainer.insert(losAngeles);
userComparatorContainer.insert(newJersey);
userComparatorContainer.insert(sanFrancisco);
userComparatorContainer.insert(anotherNewYork);
pair< iterator, bool > insert(const value_type &value)
Definition bslstl_set.h:2326

Finally, we observe that the container created with CStringLess (userComparatorContainer) contains the correct number of unique C-string values (4), while the container using the default comparator does not:

assert(5 == defaultComparatorContainer.size());
assert(4 == userComparatorContainer.size());
size_type size() const BSLS_KEYWORD_NOEXCEPT
Return the number of elements in this set.
Definition bslstl_set.h:2725