Namespaces
Variants

cpp/iterator/default sentinel t: Difference between revisions

From cppreference.com
Ybab321 (talk | contribs)
Example: adapting the regex example, it's a good example of a default constructed iterator as sentinel
Space Mission (talk | contribs)
m fmt.
 
Line 21: Line 21:
#include <regex>
#include <regex>
#include <string>
#include <string>
 
int main()
int main()
{
{
     const std::string s = "Quick brown fox.";
     const std::string s = "Quick brown fox.";
 
     const std::regex words_regex("[^\\s]+");
     const std::regex words_regex("[^\\s]+");
     const std::ranges::subrange words(std::sregex_iterator(s.begin(), s.end(), words_regex), std::default_sentinel);
     const std::ranges::subrange words(
std::sregex_iterator(s.begin(), s.end(), words_regex), std::default_sentinel);
     std::print("Found {} words:\n", std::ranges::distance(words));
 
     std::("Found {} words:", std::ranges::distance(words));
     for (const std::smatch& match : words)
     for (const std::smatch& match : words)
    {
         std::("{}", match.str());
         std::print("{}\n", match.str());
    }
}
}
|output=
|output=

Latest revision as of 16:40, 21 February 2025

 
 
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
Defined in header <iterator>
struct default_sentinel_t {};
(1) (since C++20)
inline constexpr default_sentinel_t default_sentinel{};
(2) (since C++20)
1) default_sentinel_t is an empty class type used to denote the end of a range. It can be used together with iterator types that know the bound of their range (e.g., std::counted_iterator).
2) default_sentinel is a constant of type default_sentinel_t.

Example

#include <print>
#include <regex>
#include <string>

int main()
{
    const std::string s = "Quick brown fox.";

    const std::regex words_regex("[^\\s]+");
    const std::ranges::subrange words(
        std::sregex_iterator(s.begin(), s.end(), words_regex), std::default_sentinel);

    std::println("Found {} words:", std::ranges::distance(words));
    for (const std::smatch& match : words)
        std::println("{}", match.str());
}

Output:

Found 3 words:
Quick
brown
fox.

See also

input iterator that reads from std::basic_istream
(class template) [edit]
input iterator that reads from std::basic_streambuf
(class template) [edit]
iterator adaptor that tracks the distance to the end of the range
(class template) [edit]