在这个转换为向量C++中<string>,我如何编写这个 lambda 函数来计算任何句子中的最大单词数?



http://cpp.sh/6qn6jh:通过创建附加矢量的工作解决方案。

我正在寻找一个在向量上使用C++STL变换的1行解决方案找出任何句子中最多的单词。期望答案为6。

如何在不创建额外向量作为转换函数中的back_inserter的情况下构造此lambda?

#include <iostream>
using namespace std;
int mostWordsFoundInASentence(vector<string>& sentences) {
int longest = 0;

transform(sentences.begin(), sentences.end(), sentences.begin(), [](string& line){
int c = count(line.begin(), line.end(), ' '); // count spaces in each sentence
longest = c>longest ? c : longest;
});


return longest+1;
}

int main() {
vector<string> sentences = {
{"alice and bob love leetcode"},
{"i think so too"},
{"this is great thanks very much"}
};

cout << mostWordsFoundInASentence(sentences) << endl;

return 0;

}

错误:行9:字符13:错误:变量"最长"不能在没有指定捕获默认的lambda中隐式捕获

您可以使用C++20的范围库作为一个线性函数来实现这一点

#include <iostream>
#include <vector>
#include <string>
#include <ranges>
#include <algorithm>
int mostWordsFoundInASentence(const std::vector<std::string>& sentences) {
return std::ranges::max(
sentences |
std::ranges::views::transform(
[](const auto& sentence) -> int {
return std::count(sentence.begin(), sentence.end(), ' ') + 1;
}
)
);
}
int main() {
std::vector<std::string> sentences = {
"alice and bob love leetcode",
"i think so too",
"this is great thanks very much"
};
std::cout << mostWordsFoundInASentence(sentences) << "n";
return 0;
} 

相关内容

最新更新