简体   繁体   中英

Generic constructor using iterators

I have a time series class TimeSeries and I need to be able to construct it from some dates and values. Date is a date class. I currently have this as the constructor:

TimeSeries(std::vector<Date>::const_iterator dates, std::vector<double>::const_iterator values, std::size_t s)

and I call it using TimeSeries(dates.begin(), fixings.begin(), size) where dates is std::vector<Date> and fixings is std::vector<double> .

But I'd like to adjust the constructor so I can use the C++ standard library way of just calling an iterator without reference to the underlying data type: dates , and values do not need to be iterators on std::vector .

Sadly I can't work out the constructor arguments. Is it possible?

Yes it is possible. Why not implement it "the C++ standard library way" too?

template<class DateIt, class ValueIt>
TimeSeries(DateIt dates, ValueIt values, std::size_t s)
{
    /*ToDo - your construction here*/
}

Then you can call it using TimeSeries(dates.begin(), fixings.begin(), size) .

My "inspiration" is taken from the way std::max_element works: http://en.cppreference.com/w/cpp/algorithm/max_element

You can use templates to accept any iterator-like object. To fix the interface, it's usually a good idea to look for analogous behaviour in the standard library.

In this case, you want to iterate over two sequences, having the same number of elements, and do something with each one (namely, insert them into your time series). This sounds a lot like std::transform in its two-sequence form:

template< class InputIt1, class InputIt2, class OutputIt,
          class BinaryOperation >
OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, 
                    OutputIt d_first, BinaryOperation binary_op );

You don't need users to be able to specify a binary operation; your constructor already knows what to do. You also don't want an output iterator, which just leaves the begin,end pair for the first sequence, and the begin iterator for the second sequence:

template <typename DateIterator, typename ValueIterator>
TimeSeries(DateIterator first, DateIterator last, ValueIterator first2);

This form requires only that the value sequence has at least as many elements as the range specified on the date sequence. In particular, the size is not explicitly given, so this form could be used with the more generic input iterator concept, rather than being restricted to forward iterators (see http://en.cppreference.com/w/cpp/iterator for iterator categories).

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