Home >Backend Development >C++ >How to Efficiently Parse Integers from a Text File with Varying Counts into a Vector in C ?
When attempting to read graph adjacency information from a text file, one can encounter lines with varying counts of integers terminated by 'n'. Using the getline() method to retrieve each line individually poses the challenge of accurately parsing each line due to its inconsistent number of integers. Strategies are sought to address this issue and efficiently store these values in a vector.
The conventional approach calls for iterating over each line read by getline() and utilizing an istringstream object to parse each line. As integers are read sequentially, they can be appended to a vector, which can then be further manipulated as desired. The following code exemplifies this approach:
<code class="cpp">#include <fstream> #include <sstream> #include <string> #include <vector> int main() { std::ifstream infile("thefile.txt"); std::string line; while (std::getline(infile, line)) { std::istringstream iss(line); int n; std::vector<int> v; while (iss >> n) { v.push_back(n); } // Do something with v } }</code>
An alternative solution involves a single-line for loop. By utilizing the istream_iterator class, we can read values directly into a vector, reducing the need for intermediary containers. An auxiliary function is also employed to prevent the potential dangling references that could arise from std::move.
<code class="cpp">#include <fstream> #include <string> #include <vector> int main() { std::vector<std::vector<int>> vv; for (std::string line; std::getline(std::cin, line); vv.push_back(std::vector<int>(std::istream_iterator<int>(std::stay(std::istringstream(line))), std::istream_iterator<int>()) ) ) { } }</code>
The above is the detailed content of How to Efficiently Parse Integers from a Text File with Varying Counts into a Vector in C ?. For more information, please follow other related articles on the PHP Chinese website!