Ac1234
Ac1234

Reputation: 77

Generate & transform algorithms doesn't work in c++

Firstly, i used std::generate to initialize with an element that have the value equal with the index:

void Gen(std::vector<int> v)
{
    for (int i = 0; i < v.size(); i++)
        v[i] = i;

}

std::generate(arr.begin(), arr.end(), Gen);
    print(arr);

and is not working the bind function .

Also i tried using std::transform to create a new array with the square of the initial range

std::vector<int> arr1 = { 4, 6, 3, 8, 1 };
    std::vector<int> newVec1;

std::transform(arr1.begin(), arr1.end(), std::back_inserter(newVec1), [](int i) {return i * i; });
    print(arr1);

And this prins the same array

Upvotes: 0

Views: 344

Answers (2)

Bill Lynch
Bill Lynch

Reputation: 81936

That's.... not how generate works. I'm confused how that's even compiling:

 clang++-7 -pthread -std=c++17 -o main main.cpp
In file included from main.cpp:2:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/algorithm:62:
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0/../../../../include/c++/7.5.0/bits/stl_algo.h:4438:19: error: 
      too few arguments to function call, expected 1, have
      0
        *__first = __gen();
                   ~~~~~ ^
main.cpp:19:8: note: in instantiation of function template
      specialization
      'std::generate<__gnu_cxx::__normal_iterator<int *,
      std::vector<int, std::allocator<int> > >, void
      (*)(std::vector<int, std::allocator<int> >)>'
      requested here
  std::generate(arr.begin(), arr.end(), Gen);
       ^
1 error generated.

Your generator function (or functor) needs to take no arguments. Here's a mechanism to do what you're suggesting:

#include <iostream>
#include <algorithm>
#include <vector>

struct Generator {
  int counter = 0;
  int operator()() {
    return counter++;
  }
};

void print(const std::vector<int> &v) {
  for (int elem : v)
    std::cout << elem << " ";
  std::cout << "\n";
}

int main() {
  std::vector<int> arr{0,0,0,0};
  std::generate(arr.begin(), arr.end(), Generator());
  print(arr);
}

Which outputs:

0 1 2 3

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490178

For your first one, I'd probably advise using std::iota, which is defined specifically for cases like yours.

std::iota(v.begin(), v.end(), 0);

The second problem seems to be that you're printing out arr1 (your input) instead of newVec1 (the result).

Upvotes: 1

Related Questions