c++ - 如何将函数作为参数传递给 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++ - 尝试使用 boost::variant 时出错 - “没有匹配的调用函数”
- git - 重写 git 历史来压缩一堆旧的提交
- c++ - 如何从指向 ACCESS_ALLOWED_ACE 结构的指针中的 SidStart 成员获取完整的 SID?
- c# - 在 EF Core 中为新创建的实体应用自引用 ID
- salesforce - Salesforce Einstein 聊天机器人关闭操作
- javascript - 为什么我用javascript做跑马灯效果,运行时会晃动?
- apache - Apache打开的连接太多导致站点加载缓慢
- jestjs - Jest React Hooks Form 提交到 redux 调用失败
- node.js - 您好,我有 3 个集合如何通过单个请求进行连接以选择数据?
- python-3.x - 根据复合逻辑条件从数据框中选择行