This *should* sort my vector

Oct 10, 2010 at 3:42pm
This is for a little database program i'm writing.
It should sort the vector from highest price ( getPrijs() ) to lowest and show it.
But for some reason it just shows them backwards (on ID)
For example:

ID name price
1 football 50
2 game 75
3 cards 15

After I call the function, it shows:

ID name price
3 cards 15
2 game 75
1 football 50

this is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 cout<<setw(10)<<left<<"ID"<<setw(15)<<"Product: "<<setw(15)<<"Price"<<"Amount in stock\n";
    int high;
    int size = data.size();

    for(int j = 0; j != size; j++)
    {

    for(int i = 0; i != data.size(); i++)
    {
        int maxi = -1;
        {
            if (data[i].getPrijs() > maxi)
            {
            high = i;
            maxi = data[i].getPrijs();
            }
        }
    }

    cout<<"\n"<<setw(10)<<data[high].getId()<<setw(15)<<data[high].getNaam()<<setw(15)<<data[high].getPrijs()<<data[high].getAantal();
    vector<item>::iterator pos = data.begin() + high;
    data.erase(pos);
    }
Oct 10, 2010 at 3:44pm
Oct 10, 2010 at 3:50pm
Wouldn't work...I need to keep the vectors as they are...
Unless I'm understanding it wrong. What I understand:
It switches integers so that vector[0] would contain the highest?
Oct 10, 2010 at 3:56pm
Well, you can either operate on a copy of the vector or on a (temporary) vector of pointers to the original elements.
Besides, data.erase(pos); isn't exactly "keeping the vectors as they are", is it?
Oct 10, 2010 at 4:50pm
wait, I'll try the first you said...
Oct 10, 2010 at 5:18pm
Doesn't work, it can't sort objects, even with the example...
But why doesn't my way work?
Oct 10, 2010 at 7:03pm
Doesn't work, it can't sort objects, even with the example...

It can sort anything you want it to. You should post your modified code.

But why doesn't my way work?

You declared maxi at the wrong place.
Oct 10, 2010 at 7:16pm
Found out and hour ago, just came here to post it was fixed.
It indeed was maxi declarationat the wrong place :)

Fixd!


PS: for those who want to see:

modified code;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void ordenPrijs(vector<item> data)
{
    system("CLS");
    cout<<setw(10)<<left<<"ID"<<setw(15)<<"Product: "<<setw(15)<<"Price"<<"Amount in stock\n";
    int high;
    int size = data.size()-1;


    for(int j = 0; j != size; j++)
    {
        int maxi = -1;

    for(int i = 0; i != data.size(); i++)
    {

        {
            if (data[i].getPrijs() > maxi)
            {
            high = i;
            maxi = data[i].getPrijs();
            }
        }
    }

    cout<<"\n"<<setw(10)<<data[high].getId()<<setw(15)<<data[high].getNaam()<<setw(15)<<data[high].getPrijs()<<data[high].getAantal();
    vector<item>::iterator pos = data.begin() + high;
    data.erase(pos);
    }
    Sleep(7000);
}
Topic archived. No new replies allowed.