| | |
vector<string> - way to find longest string?
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
If I've got a vector of strings, is there a quick one liner that gets me the longest (ie .size() ) of the string inside (or conversely, the shortest?)
The alternatives I've thought of are as follows, but they all seem inefficient:
- Keep a variable of the longest size as I insert each element and compare
- Iterate through the vector and compare
Any other ideas would be appreciated.
The alternatives I've thought of are as follows, but they all seem inefficient:
- Keep a variable of the longest size as I insert each element and compare
- Iterate through the vector and compare
Any other ideas would be appreciated.
Last edited by winbatch; Dec 22nd, 2005 at 6:10 pm. Reason: (removed dumb alternative...)
>As long as there is no built in function that I'm not aware of, I'll iterate through...
Don't confuse my comment with there not being another solution. However, you'll find that the pretty abstractions that you might use do exactly the same thing internally, so your concern about performance is pretty much moot.
Don't confuse my comment with there not being another solution. However, you'll find that the pretty abstractions that you might use do exactly the same thing internally, so your concern about performance is pretty much moot.
I'm here to prove you wrong.
•
•
Join Date: Jun 2004
Posts: 2,108
Reputation:
Solved Threads: 18
This is my try at it. It may not be very good, but it works.
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <algorithm> #include <string> #include <set> using std::cout; using std::endl; class Sort_By_Length { public: enum sort_mode {ascending, descending}; //constructor for sorting criterion //-default criterion uses value descending Sort_By_Length(sort_mode m=descending): mode(m) { } //comparison of the elements bool operator() (const string& s1, const string& s2) const { return (mode == descending ? s1.length() > s2.length() : s2.length() > s2.length()); } //comparison of the sorting criterion bool operator== (const Sort_By_Length& sbl) { return mode == sbl.mode; } private: sort_mode mode; }; typedef set<string, Sort_By_Length> String_Set; void fill_set(String_Set& set); int main() { //create, fill, and print set with normal element order //-uses default sorting criterion String_Set coll; fill_set(coll); copy(coll.begin(), coll.end(), //range ostream_iterator<string>(cout, "\n")); //destination cout << endl; } void fill_set(String_Set& set) { set.insert("reallylarge"); set.insert("small"); set.insert("medium"); }
>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:
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:
If you're doing more searching than anything else, a vector might not be an appropriate data structure to begin with.
If you have to use a vector, you can sort by length and then take the last string as your longest:
C++ Syntax (Toggle Plain Text)
#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'; }
C++ Syntax (Toggle Plain Text)
#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'; }
I'm here to prove you wrong.
Thanks for your attempts Narue and SC. In the end though, it looks like the solutions still iterate through each element and see if it's the largest or not. I guess the only way this would not have been in the case was if vector automatically had already stored the longest and shortest values as they were inserted. (Although I guess that's not likely/practical given that the container might be used to store data of any kind and therefore longest/shortest may not have any meaning in all contexts).
thanks again guys.
Winbatch
This is what I ended up using/writing:
thanks again guys.
Winbatch
This is what I ended up using/writing:
•
•
•
•
void General::getMinimumAndMaximumLengths( vector<string> & vec, int & min, int & max, string & minStr, string & maxStr )
{
if ( vec.empty() )
{
min=max=0;
minStr.clear();
maxStr.clear();
}
else
{
for (unsigned int i=0;i< vec.size();i++)
{
unsigned int current = vec[i].size();
if ( i==0 )
{
min=max=current;
minStr=maxStr = vec[i];
}
if ( current <=min )
{
min = current;
minStr = vec[i];
}
if ( current >=max )
{
max = current;
maxStr = vec[i];
}
}
}
}
![]() |
Similar Threads
- How do I convert a vector to a String array ? (Java)
- File operations (C)
- how to find length of a string (C++)
- need to find occurances in a string (C++)
Other Threads in the C++ Forum
- Previous Thread: File array question
- Next Thread: Windows Sockets
| Thread Tools | Search this Thread |
api array arrays based beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete deploy developer dll download dynamiccharacterarray email encryption error file forms fstream function functions game generator getline givemetehcodez graph gui homeworkhelp homeworkhelper iamthwee ifstream input int java lib list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference rpg sorting string strings temperature template text text-file tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






