Georg Schölly
Georg Schölly

Reputation: 126135

Is it possible to go from istringstream to a vector without specifying the type?

This works:

std::istringstream("1234") >> mystruct.member;

But what if I want to push_back() the values into a vector of unknown type?

A partial solution to it:

decltype(some_vector)::value_type buf;
istringstream("1234") >> buf;
some_vector.push_back(buf);

Is it possible to do this without a buffer variable?

Upvotes: 1

Views: 292

Answers (2)

wally
wally

Reputation: 11012

A partial solution to it:

decltype(some_vector)::value_type buf;
istringstream("1234") >> buf;
some_vector.push_back(buf);

Is it possible to do this without a buffer variable?

Yes, in the program below it is done without a buffer, but it comes at a price.

In the following program an iterator is created that will extract the required values and emplace them into the vector. It does so without overtly creating a buffer variable. It works for a vector of different types.

#include <sstream>
#include <vector>
#include <string>
#include <iostream>
#include <iterator>

struct done_reading {};

template<typename T, typename charT>
T extract(std::basic_istream<charT>& is) {
    std::istream_iterator<T> it{is};
    if(it != decltype(it){}) {
        return *it;
    }
    throw done_reading{};
}

struct mystruct { int member{}; };

template<typename charT>
std::basic_istream<charT>& operator>>(std::basic_istream<charT>& is, mystruct& m) { is >> m.member; return is; }

std::ostream& operator<<(std::ostream& os, mystruct& m) { os << m.member; return os; }

template <typename T, typename S>
S& operator>>(S&& is, std::vector<T>& some_vector)
{
    for(;;)
        try {
        some_vector.emplace_back(extract<T>(is));
    }
    catch(done_reading)
    {
        return is;
    };
}

template<typename T>
void make_and_print()
{
    std::vector<T> some_vector;
    std::istringstream{"1234 5678 9101112"} >> some_vector;
    std::istringstream iss{"43728 754382 69548"};
    iss >> some_vector;
    for(auto&& i : some_vector)
        std::cout << i << '\n';
}

int main()
{
    make_and_print<int>();
    make_and_print<mystruct>();
}

Upvotes: 1

Curious
Curious

Reputation: 21530

If your stringstream is guaranteed to contain elements that are space delimited and correspond to the type of your container then you can do something like this

template <typename Container>
void get_input(std::istream& is, Container& container) {
    auto val = typename std::decay_t<Container>::value_type{};
    while (is >> val) {
        container.push_back(std::move(val));
    }
}

Note that I have not used a template template parameter to deduce the type that the container is templated on because using value_type provides for a stronger contract with the container.

Upvotes: 1

Related Questions