i am having a problem with this attach function, it is supposed to attach a new number to the end of a list of numbers. It is actually putting the new number at the front of the list. I have tried everything and cant figure it out. I need a second opinion or at least a new idea to try. thanx...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void sequence::attach(const value_type& entry)
{
size_type i;
assert(size()< CAPACITY);
if(!is_item())
current_index = 0;
for (i = used; i > current_index; --i)
data[i]= data[i+1];
data[current_index] = entry;
++used;
ya i am prety sure its a logic error in the code since i pieced it together from my book,
size_type is a sort of int for container classes
make sure size is less than capacity
if is_item returns false set current_index to 0
set i to used and for i greater than current de-increment i (controls the for loop)
data[i]=data[i+1] moves the cursor to the new position (hopefully to the end)
data[current_index]=entry inserts the new number to the current location
++used increment used till the for loop stops
did i get that right?
edit// data is stored in index locations i through i - 1 . which works fine in my insert function but i was thinking i + 1 should go to the end but thats too far.
set i to used and for i greater than current de-increment i (controls the for loop)
data[i]=data[i+1] moves the cursor to the new position (hopefully to the end)
This is what the loop is, but what does the loop do? How does it change data? For example, if data is {1,2,3,4} before the loop, what will it be after the loop?
data[current_index]=entry inserts the new number to the current location
Where is the current location? The beginning or the end? Where do you want to put the new item?
the loop adds new numbers to the end of a list of numbers so after the loop it should be {1,2,3,4,5}. if no numbers are in the list then it should put the new number at the beginning.
I would like to put the new item at the end of the list
the loop adds new numbers to the end of a list of numbers so after the loop it should be {1,2,3,4,5}
Nope. If the loop was correctly written, it would shift all the elements forward, giving {1,1,2,3,4} (it would be of no use in this particular function, but it would be correct). Since it goes from back to front, it will actually give {1,?,?,?}, "?" being whatever garbage was just after the 4. This is assuming current_index is always 0 just before the loop, which actually I'm not sure is true
is data[current_index]=entry where my problem is?
There isn't just one thing that's wrong with the function. You need to rethink the whole thing.