Parsing files

suggest change

Parsing files into STL containers

istream_iterators are very useful for reading sequences of numbers or other parsable data into STL containers without explicit loops in the code.

Using explicit container size:

std::vector<int> v(100);
std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(),
    v.begin());

This writes through v.begin(). More than 100 values writes past the end of v, which is undefined. Fewer values leave the remaining elements value-initialized.

or with inserting iterator:

std::vector<int> v;
std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(),
    std::back_inserter(v));

Note that the numbers in the input may be separated by any amount of whitespace, including newlines.

Parsing heterogeneous text tables

As istream::operator>> reads text until a whitespace symbol, it may be used in while condition to parse complex data tables. For example, if we have a file with two real numbers followed by a string (without spaces) on each line:

1.12 3.14 foo
2.1 2.2 barr

it may be parsed like this:

std::string s;
double a, b;
while(ifs >> a >> b >> s) {
    std::cout << a << " " << b << " " << s << std::endl;
}

Transformation

Standard algorithms can operate on iterator ranges delimited by std::istream_iterator. For example, std::transform can read integers, multiply them by 3.14, and store the results in a floating-point container. As with the sized std::copy above, more input than v can hold writes past the end:

std::vector<double> v(100);
std::transform(std::istream_iterator<int>(ifs), std::istream_iterator<int>(),
v.begin(),
[](int val) {
    return val * 3.14;
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents