1

所以我实现了一个基于数组的列表来存储一堆 (x,y) 对。这是我所拥有的

列表.h

#ifndef LIST
#define LIST
class list{
    float * values;
    int size,last;
public:
    float getValue(int);
    int getSize();

    void setValue(int,float);
    bool insert(const float);

    void resize(int);

    list();
    ~list();
};    
#endif

列表.cpp

#include <iostream>
#include "list.h"

using namespace std;

int list::getSize()
{
    return size;
}
float list::getValue(int a)
{
    if (a<size && a >=0)
    return values[a];
}
void list::setValue(int a ,float b)
{
    if (a<size && a >=0)
        values[a]=b;
}   
bool list::insert(const float a)
{
    if (a==NULL || a==EOF){
        return false;
    }           
    if(last+1<size && last+1>=0)
    {
        values[last+1]=a;
        last++;
        return true;
    }
    else if (last+1>=size)
    {
        resize(size+1+((last+1)-size));
        values[last+1]=a;
        last++;
        return true;
    }
    return false;

}
void list::resize(int dim){
    float *temp=new float[size];

    for (int i=0;i<size;i++)
        temp[i]=values[i];

    delete [] values;
    values=new float [dim];

     for (int b=0;b<dim;b++)
     {
         if (b<size)
             values[b]=temp[b];
         else
             values[b]=NULL;
     }   
     size=dim;
     delete []temp;
}


list::list(){
    //The expected input is always >2000.
    values=new float[2000];
    size=2000;
    last=-1;
}
list::~list()
{
    delete[]values;
}

主.cpp`

#include <fstream>
#include <iostream>
#include "list.h"
using namespace std;

int main()
{

ifstream file("test.txt");
list X,Y;
float x,y;
if (file)

    {
        while(file>>x)
        {
            X.insert(x);
            file>>y;
            Y.insert(y);
        }
    }
    ofstream outfile("out.txt");
    for(int i=0;i<X.getSize();i++)
        outfile<<i+1<<" "<<X.getValue(i)<<"  "<<Y.getValue(i)<<endl;

    system("notepad.exe out.txt");

    //system("pause");

    return 0;
}

输入流似乎跳过了任何等于 -1 的值。我的问题是:跳过 -1 是否有特殊原因?另外:我知道我可以使用 STL 或更有效的列表,这只是为了练习。

4

1 回答 1

2

EOF适用-1大多数实现,因此if (a==NULL || a==EOF){过滤-1您的实现中是否属于这种情况。

于 2013-10-09T05:41:42.937 回答