I want to define a constructor working with any constructor having begin, end, operator++.
In other words I want to get this behavior (commented, working code):
/*Polyn(std::vector<double> &a) : CalcDerivative(0) , CalcIntegral(0) {
for(std::vector<double>::iterator i = a.begin();i < a.end();++i)
params.push_back(*i);
}*/
with other iterators. (for instance lists too).
template <typename T>
Polyn(const T &a) : CalcDerivative(0) , CalcIntegral(0) {
typename std::vector<T>::iterator iter;
for(iter i = a.begin();i < a.end();++i) //LINEA 18!!
params.push_back(*i);
}
What I get is this compilation error:
polyn.h: In constructor ‘Polyn::Polyn(const T&)’:
polyn.h:18: error: expected ‘;’ before ‘i’
why? How to fix my code?
In addition to Nawaz’s answer, if you want to support any container type supporting begin, end and a forward iterator, you may want to use:
This way it also works for
std::lists andstd::mapsand whatever. Or, when having C++11 support, you should actually use the even more generalstd::begin(a)andstd::end(a), so it will even work for plain arrays or anything else specializingstd::beginandstd::end.Another option, which is a bit more STL-like, would be to directly use iterators as arguments, but then you have to do the begin/end manually in the client code (when calling the constructor):