ifstream offers an overload of operator>> to extract values from the next line of the stream. However, I tend to find myself doing this often:
int index;
input >> index;
arr[index] = <something>;
Is there any way to get this data into the [index] without having to create this temporary variable?
Sure, you can do this by just constructing a temporary istream_iterator for example:
arr[*istream_iterator<int>(input)] = something
                        You can write a function to extract the next value from an istream:
template <typename T> // T must be DefaultConstructible
T read(std::istream& input) {
    T result;
    input >> result;
    return result;
}
Then, you could just write:
arr[read<int>(input)] = <something>;
Although you should probably write
arr.at(read<int>(input)) = <something>;
Because otherwise you open yourself up to a buffer-overflow vulnerability. If the input file had an integer out of range, you'd be writing out of bounds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With