I realized you can get the length of a string in a vector by using something like:
1 2 3 4 5 6
vector<string> words;
words.push_back("cat");
words.push_back("dog");
words.push_back("mouse")
for (unsignedint i = 0; i < words.size(); ++i)
cout << word[i].length() << endl;
I tried writing a MAX function, but I can't seem to figure out which data types I should be using. I assumed at first that string.length() would yield an int, but when I wrote a function like:
1 2 3 4 5 6
int max(int w1, int w2) {
if(w1 > w2)
return w1;
elsereturn w2;
}
I couldn't call it with max(words[i].length(),words[i+1].length())
I've tried a few other formats and can't seem to get any to work. Is there a way to call a function to compare the lengths of different strings?
string::size_type is the type you're looking for.
While this is not required, the container size_types are usually equivalent to size_t (they are equivalent for standard containers used with standard allocators).
Well I got the function to work, but for some reason my program terminates without error after my for loop when I use the function. Anybody know why this is happening? (When I comment out line 40, it runs to the end)
Let's do this with an array to make it a bit simpler so that I can show you your problem:
1 2 3
int a[3] = { 1, 10, 100 };
for (int i = 0; i < 3; ++i)
cout << a[i] << " , " << a[i+1] << endl;
1 , 10
10 , 100
100 , CRASH!
We're crashing because we're stepping outside of the bounds of the array.
The same thing is happening with your vector:
1 2 3 4
for (unsignedint i = 0; i < word.size(); ++i){
if (isMax(word[i].length(), word[i+1].length())
...
}
If you're going to reference word[i+1], then you need to ensure that you don't overstep the limits of the array. Change your for loop to this: for (unsignedint i = 0; i < word.size()-1; ++i){
Also, regarding your Max function. If you use a template function, then the type is completely irrelevant:
1 2 3 4 5
template <class T>
T isMax(T a, T b)
{
return (a < b) ? b : a;
}
By using template<class T>, you've now defined a template. In the function following it, you can use T to represent any datatype, even custom classes!
The C version of this is to use macros like so: but those aren't really safe. #define isMax(a,b) (((a)<(b))?(b):(a))
Stewbond, thank you so much for explaining that to me! I was at a total loss for what to do b/c I wasn't getting any compiler errors. Thanks to your detailed explanation, I totally understand now. I can't thank you enough.
Also, thank you cpp forums, you have aided my cpp learning tremendously!
I will be a great programmer one day so I can give back.