I am working on a code where I need to validate a std::vector filled with multiple std::string objects. The logic is that I need to check if all of the objects are valid or not. If yes then display a message saying that input vector is valid, error otherwise. Here is what I have so far.
#include<iostream>
#include<vector>
#include<numeric>
#include<boost/foreach.hpp>
short multiply(short s1,short s2)
{
return s1*s2;
}
bool validate(const std::vector<std::string> &in)
{
std::vector<short>check(in.size(),0);
auto checkitr = check.begin();
BOOST_FOREACH(std::string str,in)
{
for(auto itr = str.begin(); itr != str.end(); ++itr)
{
if(*itr == 'c')
{
*checkitr = 1;
break;
}
}
++checkitr;
}
short product = std::accumulate(check.begin(),check.end(),1,multiply);
return ( (product) ? true : false );
}
int main()
{
std::string s1("abcd");
std::string s2("lncd");
std::vector<std::string>iVec;
iVec.push_back(s1);
iVec.push_back(s2);
bool isValid = validate(iVec);
if(isValid){
std::cout<<"This Vector is valid "<<std::endl;
}
else
{
std::cout<<"This is an invalid vector "<<std::endl;
}
iVec.push_back(std::string("ghkd"));
isValid = validate(iVec);
if(isValid){
std::cout<<"This Vector is valid "<<std::endl;
}
else
{
std::cout<<"This is an invalid vector "<<std::endl;
}
return 0;
}
This runs fine and gives me the result that I need.My question is, Is there any other better/performance efficient approach in standard algorithm or boost library that I can use instead of my current approach?
Aucun commentaire:
Enregistrer un commentaire