首页 > 解决方案 > 如何将函数作为参数传递给 transform() 函数?

问题描述

我正在尝试创建一个程序,该程序使用 transform() 来确定向量中字符串的大小,然后将结果放入单独的向量中。

我不完全理解如何将函数传递给 transform() 并且出现错误,任何帮助将不胜感激!

我的代码:

#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;
}

预期产出

4 2 1 5 8

实际输出

进程返回 -1073741819 (0xC0000005)

标签: c++stringalgorithmiterator

解决方案


您将函数传递给transform. 问题是你的result向量是空的,所以当你从result.begin(). 你需要做:

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

这是一个演示

在这种情况下,您也可以进行迭代,result.begin()因为您确切知道需要多少元素。您需要做的就是在开始时分配足够的空间:

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

这是一个演示


推荐阅读