c++ - Can an iterator be turned into a pointer? -


in "13.7.3 async()" of "a tour of c++" (first print), following provided example:

double comp4(vector<double>& v) {   if (v.size() < 10000)     return accum(v.begin(), v.end(), 0.0);    auto v0 = &v[0];   auto sz = v.size();    auto f0 = async(accum, v0, v0 + sz/4, 0.0);   auto f1 = async(accum, v0 + sz/4, v0 + sz/2, 0.0);   auto f2 = async(accum, v0 + sz/2, v0 + sz*3/4, 0.0);   auto f3 = async(accum, v0 + sz*3/4, v0 + sz, 0.0);    return f0.get() + f1.get() + f2.get() + f3.get(); } 

where accum defined follows:

double accum(double* beg, double* end, double init) {   return accumulate(beg, end, init); } 

vector, async , accumulate standard library versions.

running produces following error:

error: cannot convert ‘std::vector<double>::iterator {aka __gnu_cxx::__normal_iterator<double*, std::vector<double> >}’ ‘double*’ argument ‘1’ ‘double accum(double*, double*, double)’      return accum(v.begin(), v.end(), 0.0); 

i can work if use return accum(&v[0], &v[0] + v.size(), 0.0); instead. have done wrong in original formulation? should vector<double>::iterator able convert double* or mistake book? issue doesn't seem mentioned in errata both first , second printings of book.

the way std::vector specified, it's entirely possible implement having vector<t>::iterator typedef of t*.

odds whoever wrote code happened have version of vector implemented way , got lucky.

your workaround correct way this, assuming definition of accum() doesn't change.

in opinion, accum should have been declared so:

template<typename t, typename ite> t accum(ite beg, ite end, t init); 

but that's std::accumulate, it'd redundant.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -