>so are you aware of an existing solution provided by vector or algorithm in general?
If you have to use a vector, you can sort by length and then take the last string as your longest:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct length {
bool operator() ( const string& a, const string& b )
{
return a.size() < b.size();
}
};
int main()
{
string init[] = {
"This","is","a","test","and","aaaaa"
};
vector<string> v ( init, init + 6 );
sort ( v.begin(), v.end(), length() );
cout<< v.back() <<'\n';
}
Alternatively, because you might not need the vector sorted as well and a simple search might be more than enough, you can use max_element with the length predicate:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct length {
bool operator() ( const string& a, const string& b )
{
return a.size() < b.size();
}
};
int main()
{
string init[] = {
"This","is","a","test","and","aaaaa"
};
vector<string> v ( init, init + 6 );
cout<< *max_element ( v.begin(), v.end(), length() ) <<'\n';
}
If you're doing more searching than anything else, a vector might not be an appropriate data structure to begin with.