What does string::npos mean in this code?

后端 未结 12 1252
傲寒
傲寒 2020-11-30 18:50

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

found = str.find(str2);

if (found != std::string::npos)
    std::         


        
12条回答
  •  执笔经年
    2020-11-30 19:26

    we have to use string::size_type for the return type of the find function otherwise the comparison with string::npos might not work. size_type, which is defined by the allocator of the string, must be an unsigned integral type. The default allocator, allocator, uses type size_t as size_type. Because -1 is converted into an unsigned integral type, npos is the maximum unsigned value of its type. However, the exact value depends on the exact definition of type size_type. Unfortunately, these maximum values differ. In fact, (unsigned long)-1 differs from (unsigned short)-1 if the size of the types differs. Thus, the comparison

    idx == std::string::npos
    

    might yield false if idx has the value -1 and idx and string::npos have different types:

    std::string s;
    ...
    int idx = s.find("not found"); // assume it returns npos
    if (idx == std::string::npos) { // ERROR: comparison might not work
    ...
    }
    

    One way to avoid this error is to check whether the search fails directly:

    if (s.find("hi") == std::string::npos) {
    ...
    }
    

    However, often you need the index of the matching character position. Thus, another simple solution is to define your own signed value for npos:

    const int NPOS = -1;
    

    Now the comparison looks a bit different and even more convenient:

    if (idx == NPOS) { // works almost always
    ...
    }
    

提交回复
热议问题