Search code examples
c++vectorbinary-operators

can't assign iterator to constant input vector in a binary function


I am trying to write a binary function that takes two vectors(of the same length) and adds them by value. For some reason the following code does not work:

struct Plusval : binary_function <std::vector<int>,std::vector<int>,std::vector<int> > 
{
  std::vector<int> operator() (const std::vector<int>& x, const std::vector<int>& y) const
{
    std::vector<int> ret(x);
    std::vector<int>::iterator itx,ity;
    ity=y.begin();
    for (itx=ret.begin();itx<ret.end();++itx)
    {
        ret[*itx]+=y[*ity];
        ++ity;
    }
    return ret;
  }
};

I get an error that I can't do ity=y.begin() However, the following code does work

struct Plusval : binary_function <std::vector<int>,std::vector<int>,std::vector<int> > 
{
  std::vector<int> operator() (const std::vector<int>& x, const std::vector<int>& y) const
{
    std::vector<int> ret(x);
    std::vector<int> yloc(y);
    std::vector<int>::iterator itx,ity;
    ity=yloc.begin();
    for (itx=ret.begin();itx<ret.end();++itx)
    {
        ret[*itx]+=yloc[*ity];
        ++ity;
    }
    return ret;
  }
};

Obviously, the second version will take longer (since it has to copy an additional vector). Is it because the input is a const vector? If it is, is there any reason it needs to be? Note that I am planning on using this function as an input to the allreduce() function in boost::mpi if that makes any difference


Solution

  • You define ity as vector::iterator y is const and returns a const_iterator.

    What is more important is: Don't use binary_function. The adapters have been deprecated.

    Also, your function does not do what you want. *itx returns the value stored at the position pointed to by itx and you use it to index into the you intend to return vector.

    I would write this with a binary transform.

    std::vector<int> res;
    std::transform(begin(x), end(x), begin(y), 
                   std::back_inserter(res), std::plus<int>());