I have the following code that I need to figure out what the output will be. Whenever I try to run it I get an debug error - and it crashes... Somebody else said that it ran fine on their Apple machine. I just need to see what the output will be:

Thanks

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void PlayWithStrings(vector<string> InVec)
{
    static int i = 8;

    if (i != -1)
    {
        if (i == 7 || i == 6)
            cout << InVec[i];
        i--;
        PlayWithStrings(InVec);
    }

    if (i == -1)
    {
        cout << "for Sure! ";
        i = 0;
    }
}

int main(int argc, const char * argv[])
{
    vector<string> ForwardString;
    ForwardString.reserve(8);

    vector<string>::iterator VItr = ForwardString.begin();

    ForwardString.insert(VItr, "This "); VItr++;
    ForwardString.insert(VItr, "is "); VItr++;
    ForwardString.insert(VItr, "the "); VItr++;
    ForwardString.insert(VItr, "way "); VItr++;
    ForwardString.insert(VItr, "to "); VItr++;
    ForwardString.insert(VItr, "an "); VItr++;
    ForwardString.insert(VItr, "A "); VItr++;
    ForwardString.insert(VItr, "Grade ");

    for (VItr = ForwardString.begin(); VItr != ForwardString.end(); VItr++)
    cout << *VItr;
    cout << "- ";

    PlayWithStrings(ForwardString);

    return 0;
}

Recommended Answers

All 5 Replies

That is a poorly written program becuse it passes the vector to PlayWithStrings() by value instead of by reference, causing the program to duplicate the entire vector on each entry to that function.

What compiler and operating system are you using?

Windows 7 and Visual C++ 2010

I did it manually and came up with the following output - agree?

This is the way to an A Grade - Grade A for Sure!

Yeah, the output is

"This is the way to an A Grade - Grade A for Sure"

However, I don't think you'll be getting an A grade with this code ;)!

@Ancient Dragon is right, you need to pass by reference NOT value. Also, you're assume that there are 8 values within this vector, what happens if there is more? The program will just crash. Use .size() instead of defining the vector size. Also why not just push_back the elements for the vector instead of insert? mhmh!

Good luck :)

I confirmed it...
Went into the Visual C++ \Build\Config Manager\ and changed the Configuration column from Debug to Release.
I then rebuilt & ran it with out the debug error and got the same answer as above.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.