npos

Syntax:

 static const size_type npos = -1;

string::npos is a special value that indicates one of the following:

Example code:

 #include <set>
 #include <iostream>
 #include <iterator>
 #include <algorithm>
 #include <string>
 
 int main()
 {
   const std::string text("Vectors contain contiguous elements stored as an array.\n\n"
                          "Accessing members of a vector can be done in constant time, "
                          "appending elements to a vector can be done in amortized constant time, "
                          "whereas locating a specific value "
                          "or inserting elements into the vector takes linear time.");
 
   const std::string delims(" \t\n.,?!;:\"");
 
   std::set<std::string> words;
   std::string::size_type end_pos;
 
   // find beginning of the first word
   std::string::size_type beg_pos = text.find_first_not_of(delims);
 
   // while beg_pos is not "not found" (i.e. beginning of a word is found)
   while (beg_pos != std::string::npos)
   {
     // find delimiter (end of the word)
     end_pos = text.find_first_of(delims, beg_pos);
 
     // insert substring into set
     words.insert(text.substr(beg_pos,
                              end_pos == std::string::npos // if end_pos is "not found"
                              ? std::string::npos          // then "all remaining characters"
                              : end_pos - beg_pos));
 
     // find beginning of the next word
     beg_pos = text.find_first_not_of(delims, end_pos);
   }
 
   // display words
   std::copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
 
   return 0;
 }

Related Topics: find, find_first_not_of, find_first_of, find_last_not_of, find_last_of, rfind, substr