简体   繁体   中英

Iterate over lines in std::string without copying it

I have a large string which can be 50-200 MB. I want to iterate over the lines in the string. Most of the solutions I searched use std::getline and some of them required Boost library. I am not using them because, for example, they require me to copy the string to create a stringstream.

Do I really need to use them? Why should I not simply use std::string 's find to search for \\n and read sub-strings? Is it a bad solution?

  1. No, you do not need to use std::getline or Boost.
  2. Yes, you could use string.find() . Or, you could read the string from its source and build a list of substrings as you find the separators.
  3. No, if it gets you to your answer then that is fine. It is not a bad solution unless you have specific performance requirements, RAM limitations or other requirements you have not mentioned.

Also, you can use std::string_view in C++17. Therefore, you can put your entire input into one string then create cheap substring objects that reference the original string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM