你能告诉我为什么我要向后显示吗?

时间:2016-07-24 13:37:33

标签: c++

#include <iostream>
#include <fstream>
using namespace std;

#include "IList.h"

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


//how to open a file
ifstream inf(argv[1]);
IList t;
int integer;



//reading integer from text file.
inf >> integer;

//Up untill the end of file, it is going to insert integer to the
 list and read integer from text file again.

while(!inf.eof())
{
    t.insert(integer, 0);
    inf >> integer;
}
//displaying the list
t.display(cout);




return 0;
}

******参考************

List.h

void display(ostream & out) const;
//Display a list.

//Precondition: The ostream out is open.

//Postcondition: The list represented by this List object has been
//inserted into out.


void insert(ElementType item, int pos);
//Insert a value into the list at a given position.

//Precondition: item is the value to be inserted; there is room in 
//the array (mySize < CAPACITY); and the position satisfies
//0 <= pos <= mySize.

//Postcondition: item has been inserted into the list at the position 
//determined by pos (provided there is room and pos is a legal 
//position).



List.cpp



void IList::display(ostream & out) const
{
for (int i = 0; i < mySize; i++)
 out << myArray[i] << "  ";
}




void IList::insert(ElementType item, int pos)
{
if (mySize == myCapacity)
{
  cerr << "*** No space for list element -- terminating "
          "execution ***\n";
  exit(1);
}
if (pos < 0 || pos > mySize)
{
  cerr << "*** Illegal location to insert -- " << pos 
       << ".  List unchanged. ***\n";
  return;
}

// First shift array elements right to make room for item

for(int i = mySize; i > pos; i--)
  myArray[i] = myArray[i - 1];

// Now insert item at position pos and increase list size  
myArray[pos] = item;
mySize++;
}

作为参考,我添加了显示/插入的顺序。

在IList.h中显示/插入

在IList.cpp中显示/插入

我不知道向后打印或向后插入的位置。

你能告诉我我是怎么做的吗?

1 个答案:

答案 0 :(得分:3)

您总是插入列表的开头:

t.insert(integer, 0);

我们假设您有数字1和2.您先插入1,您的列表将变为{1}。然后在开头插入2,现在您的列表包含{2,1}。你明白了吗?