In: Computer Science
(32%) Create a class of function objects called StartsWith that satisfies the following specification: when initialized with character c, an object of this class behaves as a unary predicate that determines if its string argument starts with c. For example, StartsWith(’a’) is a function object that can be used as a unary predicate to determine if a string starts with an a. So StartsWith(’a’)("alice") would return true but StartsWith(’a’)("bob") would return false. The function objects should return false when called on an empty string. Test your function objects by using one of them together with the STL algorithm count_if to count the number of strings that start with some letter in some vector of strings.
in C++ please
ANS:
#include<cstring>
#include<cmath>
#include<vector>
#include<iostream>
using namespace std;
class StartsWith
{
private:
char first;
string str;
public:
StartsWith(char fir, string st) //Parameterised
constructor
{
first = fir;
str = st;
}
bool checkString()
{
int i = 0;
if (first == str[i])
{
return
true;
}
else
{
return
false;
}
}
};
int count_if(vector<string> obj)
{
int count = 0;
for (int i = 0; i < obj.size(); i++)
{
string objS = obj[i];
StartsWith sw('c', objS);
if ( sw.checkString()==
true)
{
count++;
}
}
return count; // counting number of char and string first letter matches in vector
}
int main()
{
vector<string> test;
test.push_back("cat");
test.push_back("bob");
test.push_back("counting");
test.push_back("Alice");
cout<<"COUNT:"<<count_if(test)<<endl;
}
COMMENT DOWN BELOW FOR ANY QUERIES AND,
LEAVE A THUMBS UP IF THIS ANSWER HELPS
YOU.