1

If I input "110110" in to the application, the first chunk prints out "1" while the second chunk prints out "2".

Why are the results different?

How can I construct the regex pattern in the function call?

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    cin >> s;

    auto begin = sregex_iterator(s.begin(),s.end(),regex{R"(110)"});
    auto end = sregex_iterator();
    cout << distance(begin,end) << endl;

    const regex r(R"(110)");
    begin = sregex_iterator(s.begin(),s.end(),r);
    end = sregex_iterator();
    cout << distance(begin,end) << endl;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
forrest
  • 298
  • 2
  • 6
  • 2
    [`#include `](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – πάντα ῥεῖ Aug 30 '16 at 18:15
  • 1
    pretty sure it is related to [this](http://stackoverflow.com/questions/33154890/simple-stdregex-search-code-wont-compile-with-apple-clang-std-c14) – NathanOliver Aug 30 '16 at 18:20
  • Yes, bits/stdc++.h... bad habit from quick typing code for comps. Feel free to substitute iostream and regex includes :) – forrest Aug 30 '16 at 19:09
  • Found this in the documentation for regex_iterator: Notes It is the programmer's responsibility to ensure that the std::basic_regex object passed to the iterator's constructor outlives the iterator. Because the iterator stores a pointer to the regex, incrementing the iterator after the regex was destroyed accesses a dangling pointer. So I guess this is just a case where the compiler doesn't care and the programmer must be vigilant about dangling pointers. – forrest Aug 30 '16 at 19:25

1 Answers1

3

C++14 fixed the interface by deleting the constructor:

regex_iterator(BidirIt, BidirIt,
               const regex_type&&,
               std::regex_constants::match_flag_type) = delete;
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Maybe I don't understand the "delete" portion. But I am compiling with std=c++14 and -Wall and get no warnings building the application above. Does delete indicate that it should not build? – forrest Aug 30 '16 at 19:18
  • You should have an error [Demo](http://coliru.stacked-crooked.com/a/9b8abf0a1f3d4997). – Jarod42 Aug 30 '16 at 19:50
  • Thanks.. I double checked with clang and do indeed get the error. Running gcc-4.9 results in no error. I guess the c++14 support in 4.9 isn't all there – forrest Aug 30 '16 at 20:08