How do you pass a function as an argument into the transform() function?


I am trying to create a program that uses transform() to determine the size of strings in a vector and then put the results into a separate vector.

I do not fully understand how to pass a function into transform() and I am getting an error, any help would be much appreciated!

My code:

#include <vector>
#include <string>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

 // returns the size of a string
int stringLength(string str)
    return str.size();

int main()
    auto words = vector<string>{"This", "is", "a", "short", "sentence"};
    // vector to store number of characters in each string from 'words'
    auto result = vector<int>{};

    transform( words.begin(), words.end(), result.begin(), stringLength );

    for(auto answer : result)
    cout << answer << " ";

    return 0;

Expected Output

4 2 1 5 8

Actual Output

Process returned -1073741819 (0xC0000005)

asked on Stack Overflow Aug 29, 2020 by John

2 Answers


There's nothing wrong with how you're passing a function to transform. The issue is your result vector is empty, so you invoke undefined behavior when you iterate from result.begin(). You need to do:

std::transform(words.begin(), words.end(), 
               std::back_inserter(result), stringLength);

Here's a demo.

You can also iterate from result.begin() in this case because you know exactly how many elements are going to be needed. All you need to do is allocate enough space at the beginning:

auto result = vector<int>(words.size());

Here's a demo.

answered on Stack Overflow Aug 29, 2020 by cigien • edited Aug 29, 2020 by cigien

You must allocate buffer to be written via transform() before calling that.

In this case, you should use

auto result = vector<int>(words.size());

instead of

auto result = vector<int>{};
answered on Stack Overflow Aug 29, 2020 by MikeCAT

User contributions licensed under CC BY-SA 3.0