What does string::npos mean in this code?

Viewed 162105

What does the phrase std::string::npos mean in the following snippet of code?

found = str.find(str2);

if (found != std::string::npos)
    std::cout << "first 'needle' found at: " << int(found) << std::endl;
12 Answers

An answer for these days of C++17, when we have std::optional:

If you squint a bit and pretend std::string::find() returns an std::optional<std::string::size_type> (which it sort of should...) - then the condition becomes:

auto position = str.find(str2);

if ( position.has_value() ) {
    std::cout << "first 'needle' found at: " << position.value() << std::endl;
}

Value of string::npos is 18446744073709551615. Its a value returned if there is no string found.

static const size_t npos = -1;

Maximum value for size_t

npos is a static member constant value with the greatest possible value for an element of type size_t.

This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".

As a return value, it is usually used to indicate no matches.

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.

As others have mentioned, string::npos it's the maximum value for size_t.

Here is its definition:

static constexpr auto npos{static_cast<size_type>(-1)};

Puzzled that the wrong answer got the vote.

And here is a quick testing sample:

int main()
{
    string s = "C   :";
    size_t i = s.rfind('?');
    size_t b = size_t (-1);
    size_t c = (size_t) -1;
    cout<< i <<" == " << b << " == " << string::npos << " == " << c;

    return 0;
}

output:

18446744073709551615 == 18446744073709551615 == 18446744073709551615 == 18446744073709551615

...Program finished with exit code 0
Related