Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

?
Lv 5

Is there a better way to do this?

This is a sample of an array. I want to condense it, and load everything back into the original array with the empty slots at the end. Maybe a class instead of an array, or another suggestion?

#include <cstdlib>

#include <iostream>

#include <string>

using namespace std;

int itembackup[12];

string itemsbackup[12];

int main(int argc, char *argv[])

{

int item[12]={5,3,0,19,0,4,0,10,9,0,0,0};

string items[12]={"rue","ama","nothing in this slot","cloak","nothing in this slot","sceptre of death","nothing in this slot","zar","staff","nothing in this slot","nothing in this slot","nothing in this slot"};

int itembackup[12]={0,0,0,0,0,0,0,0,0,0,0,0}…

string itemsbackup[12]={"","","","","","","",""…

cout << "Initial list for 12 slots.\n\nSlot number\tItem value\t\tItem name" << endl;

for (int x=0;x<11;x++){cout << x <<"\t\t"<< item[x] << "\t\t\t" << items[x] << endl;}

cout << "\n" << endl;

//copy list to backup, and clear original

for (int x=0;x<11;x++){itembackup[x]=item[x];item…

//Reload original array, placing all items to brginning, no blanks.

int y=0;

for (int x=0;x<11;x++){

if (itembackup[x]>0){

item[y]=itembackup[x];items[y]=itemsback…

y++;}

for (int con=y;con<11;con++){item[con]=0;items[co… here.";}}

cout << "Final list for 12 slots.\n\nSlot number\tItem Value\t\tItem name" << endl;

for (int x=0;x<11;x++){cout << x <<"\t\t"<< item[x] << "\t\t\t" << items[x] << endl;}

system("PAUSE");

return EXIT_SUCCESS;

}

2 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    First: You're off by 1 in your loops. You want x < 12, not 11. A loop from 0 to < 11 will only execute 11 times, not 12.

    Second: Yahoo mangled your code. It's a bit hard to figure out exactly what you are trying to do, but...

    Third: Yes, a class or even a structure would be better. You are using parallel arrays here, which is very 1970's ish.

    Fourth: If I get the gist of what you are doing, despite the cut off code, You should be able to do it in place, rather than using a backup array.

    Just work through item, and when you find a 0, move it up the item array, and move the parallel items at the same time:

    int count = 0

    for(int i=0;i<12;i++)

    {

     if(item[i]>0)

     {

      item[count] = item[i];

      items[count] = items[i];

      count++;

     }

    }

    for(int i=0;i<count;i++)

     cout << i << "\t" << item[i] << "\t" << items[i] << endl;

  • 1 decade ago

    Yes.

Still have questions? Get your answers by asking now.