2
\$\begingroup\$

I have a task to search regex in many files.

How do you think is this code optimal by performance and complexity?

#include <regex>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>

int main(int args, char *argv[])
{
 std::ifstream input;
 std::string line;
 input.open("test.ws");
 std::getline(input,line);
 line.erase(std::remove_if(line.begin(),line.end(),ispunct),line.end());
 std::regex reg(argv[1]);
 std::ptrdiff_t const matchCn (std::distance(std::sregex_iterator(line.begin(),line.end(),reg),std::sregex_iterator()));
 std::cout << matchCn;
}

I'm trying to use STL for count number of regex in string getting from file.

\$\endgroup\$
1
\$\begingroup\$
  std::ifstream input;
  input.open("test.ws");

Prefer to acquire resources/responsibilities on initialization (see RAII) instead of lazy initialization. Constructors exist to define the class invariants, so use them to create fully initialized objects.

If the file cannot be opened for whatever reason, you should notify the user that an error occurred. Validate your post-conditions.


  line.erase(std::remove_if(line.begin(),line.end(),ispunct),line.end());

If you are simply searching, is there a reason for stripping away punctuation?

ispunct requires <cctype>.


  std::regex reg(argv[1]);

Did the user provide argv[1]? Validate your preconditions.

Was the regex pattern a valid expression? std::regex throws std::regex_error if the provided expression is invalid. You should catch it and notify the user failure occurred.


I have a task to search regex in many files.

The code you have provided will not accomplish this task. I was going to report it as not ready to be reviewed, but it has up-votes.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.