【问题标题】:How do you pass a function as an argument into the transform() function?如何将函数作为参数传递给 transform() 函数?
【发布时间】:2020-12-18 07:49:56
【问题描述】:

我正在尝试创建一个程序,该程序使用 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++ string algorithm iterator


    【解决方案1】:

    您将函数传递给transform 的方式没有任何问题。问题是您的result 向量为空,因此当您从result.begin() 迭代时会调用未定义的行为。你需要做的:

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

    这是demo

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

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

    这是demo

    【讨论】:

      【解决方案2】:

      在调用之前,您必须通过transform() 分配要写入的缓冲区。

      在这种情况下,你应该使用

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

      而不是

      auto result = vector<int>{};
      

      【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 2021-04-13
      • 2021-07-18
      • 2020-03-22
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多