【发布时间】: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