#Need help returning a vector from a function

20 messages · Page 1 of 1 (latest)

wispy socket
#
/*splits string by every ' ' char and makes it a vector
sorts the vector and returns a pointer to sorted vector*/
std::vector<int> *splitAndSort(std::string nums)
{
    std::vector<int> newNums;
    std::vector<int> sortedNums;
    std::string number = "";
    for(int i = 0; 0 < nums.length(); i++)
    {
        //splitting algorithm
        if(nums[i] == ' ')
        {
            newNums.push_back(std::stoi(number));
            number = "";
        }
        else
        {
            number = number + nums[i];
        }
    }
    int highest = 0;
    while(newNums.size() != sortedNums.size())
    {
        for(int i = 0; i < newNums.size(); i++)
        {
            if(newNums[i] > highest)
            {
                highest = newNums[i];
                sortedNums.emplace_back(highest);
            }
        }

    }

    return &sortedNums;
}

So i know that you need to return arrays with a pointer, but i didn't know if you need to return vectors with a pointer so I used a pointer, is that not what I should do?

edgy galeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

true jewel
wispy socket
#

Okay

I try that and then when I try running the program

std::vector<int> sorted = splitAndSort(nums);
        for(int i = 0; i < sorted.size(); i++)
        {
            std::cout << sorted[i] << " ";
        }

This block of code in the main function does not run

vagrant bison
wispy socket
#

Shouldn't it have numbers in it?
I have the string "1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1" passing into the splitAndSort fundtion

wispy socket
#

it should because after the numbers are added to newNums, they're added by size into sortedNums

vagrant bison
true jewel
#

Step through with a debugger

#

Essential skill to have

wispy socket
#
Line 63 2
Line 63 3
Line 63 4
Line 63 5
Line 63 6
Line 63 7
Line 63 8╦▼@0 aÉ$P aê↕@♀ a`↑≡oÉ$ê↕@☺
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi```
Then I use cout after ``newNums.push_back(std::stoi(number));`` this is the output
#

it gets to the end of the string, shouldn't the for loop terminate?

vagrant bison
#

stoi threw an exception and you didn't catch it

wispy socket
#

I use try and catch to fix that right?

vagrant bison
#

at line 63 junk data is printed, you corrupted the memory somewhere

mortal osprey
#

That doesn't sound good

vagrant bison