0
struct command
{
    char name[20];
    int amount;
};

int main()
{
    command n[10];

    // Im sorting array in ascending order by the amount here
    int temp;
    for(int i=0; i<10; i++) 
    {
        for(int j=0; j<10-1; j++)
        {
            if(n[j].amount>n[j+1].amount)
            {
                temp=n[j].amount;
                n[j].amount=n[j+1].amount;
                n[j+1].amount=temp;
            }
        }
    }
}

Problem is, this code sorts out only n[].amount, but I need to sort out name together with it. For example:

n[1].name="fff", n[1].amount=4, n[2].name="ggg", n[2].amount=1

and after sorting them out in ascending order it should be like this:

n[1].amount=1, n[1].name="ggg", n[2].amount=4, n[2].name="fff"

but my code only sorts out n[].amount. Sorry for the poor explanation, I'm really new to programming

MrPromethee
  • 721
  • 9
  • 18
Mahig Yahok
  • 87
  • 1
  • 2
  • 7

1 Answers1

0

Since this is C++, you should be able to do the following:

command temp = n[j];
n[j] = n[j+1];
n[j+1] = temp;

but since this is 2017, you might as well do the following:

std::swap(n[j], n[j+1]);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • 2
    So.. `std::swap(n[j], n[j+1]];`? – NathanOliver Jun 13 '17 at 15:01
  • @NathanOliver well, if the OP was using `std` I would expect them to use an actual vector. The OP is likely a student learning very basic old-style C++ without `std`, so I do not think it is a good idea to suggest using `std`, nor is it a good idea to close the question as a duplicate of one which was about `std`. – Mike Nakis Jun 13 '17 at 15:05
  • Remember, answers aren't just for the OP, they are for all the others that find this. Why not show how you can do it with both? Or at least say well, you can do this to fix it, but the idiomatic way is and show them that. Also, I didn't close the Q. – NathanOliver Jun 13 '17 at 15:10
  • @NathanOliver well, you are right. I fixed that. – Mike Nakis Jun 13 '17 at 17:47