Joh*_*ohn 1 c++ string algorithm iterator
我正在尝试创建一个程序,该程序使用 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;
}
Run Code Online (Sandbox Code Playgroud)
4 2 1 5 8
进程返回-1073741819 (0xC0000005)
您将函数传递给transform. 问题是你的result向量是空的,所以当你从result.begin(). 你需要做:
std::transform(words.begin(), words.end(),
std::back_inserter(result), stringLength);
Run Code Online (Sandbox Code Playgroud)
这是一个演示。
您也可以result.begin()在这种情况下进行迭代,因为您确切知道将需要多少个元素。您需要做的就是在开始时分配足够的空间:
auto result = vector<int>(words.size());
Run Code Online (Sandbox Code Playgroud)
这是一个演示。