#include<iostream>
#include<string>
#include<vector>
#include<numeric>
using namespace std;
class solution {
public:
int func(vector<string>& words, int left, int right) {
auto get = [](char x) -> int { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); }; //Lambda函数判断x是否为元音字母
auto getfunc = [&get](string& x) -> int {return get(x[0]) & get(x.back()); }; //Lambda函数调用上面的Lambda函数来判断x是否首尾都为元音字母
return accumulate(words.begin() + left, words.end() + right + 1, 0, [&getfunc](int sum, string& x) {return sum + getfunc(x); });//求和器
}
};
int main() {
solution s;
vector<string> words = {"are", "amy", "u"};
int left = 0, right = 2;
cout << s.func(words, left, right) << endl;
return 0;
}
1.vector
vector可以像容器一样存储数据,也就是说vector可以存放动态数组、增加并压缩数据。
所需头文件:
#include<vector>
基本语法:
vector<int> v1;
vector<string>& words
v1中的是int型的vector变量,words中的是string型的vector变量。
2.C++中的Lambda函数(匿名函数)
语法:[] () -> {}
例如:
auto add = [](int x,int y)->int{return x+y;};
这就是一个实现x+y的Lambda函数。
3.accumulate函数
一个求和函数。所需头文件为:
#include<numeric>
accumulate()基本语法为:
accumulate(初始迭代器,终止迭代器,初始数值,对数值的操作(函数))
例如:
vector<int> arr[5] = {1,2,3,4,5};
int sum = accumulate(arr.begin(),arr.end(),0};
这得到的就是初始值0+ (1+2+3+4+5) .