Reputation: 5845
Using C++, I'm trying to put together a for loop that finds the largest word in a vector of strings. I know its possible to do this by comparing word lengths. So this is just wondering about some minutiae and learn a few things about C++, I can't figure out why this won't work:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::string test = "this is a test string for sentence length ranks";
std::vector<std::string> words = {"this", "is", "a", "test", "string",
"for", "sentence", "length", "ranks"};
std::string temp = "";
std::string largest = "";
for (int i = 0; i != words.size(); ++i) {
std::cout << "words[" << i << "]: " << words[i] << " ";
std:: cout << std::endl;
temp = std::max(temp, words[i]);
largest = std::max(temp, largest);
std::cout << "the biggest word is " << largest << std::endl;
}
return 0;
}
It returns this:
Update:
The answers here helped point me in the right direction. As it turns out there is another feature to std::max called 'comp'. I barely understand it, but this seems to work:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::string test = "this is a test string for sentence length ranks";
std::vector<std::string> words = {"this", "is", "a", "test", "string",
"for", "sentence", "length", "ranks"};
std::string tempword;
std::string longword;
int longwordint = 0;
for (int i = 0; i != words.size(); ++i) {
int wordlength = words[i].length();
longwordint = std::max(longwordint, wordlength);
tempword = words[i];
longword = std::max(longword, tempword,
[](std::string longword, std::string tempword)
{ return (longword.size() < tempword.size()); });
std::cout << "the biggest word so far is " << longwordint;
std::cout <<" letters long: " << longword;
std::cout << " | the tempword is: " << tempword << std::endl;
}
return 0;
}
Upvotes: 2
Views: 840
Reputation: 126203
std::max compares things with a normal comparison, which for string, compares their dictionary order, not their length. So all the results in your loop are as expected.
Upvotes: 3
Reputation: 51
You can use std::max_element
to find largest word in a vector string.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::string test = "this is a test string for sentence length ranks";
std::vector<std::string> words = {"this", "is", "a", "test", "string",
"for", "sentence", "length", "ranks"};
auto largest = std::max_element(words.begin(), words.end(), [](const auto& s1, const auto& s2){
return s1.size() < s2.size();
});
std::cout << "the biggest word is " << *largest << std::endl;
return 0;
}
Upvotes: 3