Search code examples
c++stringalgorithmiterator

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)


Solution

  • 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.