我正在尝试创建一个使用transform()确定 vector 中字符串大小的程序,然后将结果放入单独的 vector 中。
我不完全了解如何将函数传递给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)
最佳答案
将函数传递给transform
并没有错。问题是您的result
vector 为空,因此从result.begin()
进行迭代时会调用未定义的行为。您需要做:
std::transform(words.begin(), words.end(),
std::back_inserter(result), stringLength);
这是demo。在这种情况下,您也可以从
result.begin()
进行迭代,因为您确切知道将需要多少个元素。您需要做的就是在开始时分配足够的空间:auto result = vector<int>(words.size());
这是demo。
关于c++ - 如何将函数作为参数传递给transform()函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63649684/