2016-09-25 70 views
-1

我想从文件中整理和填充对象的整体向量。 int fileSize读取第一行以确定在此之后应该读取多少个数字。我有点难以理解指针,所以至少有人能帮助我做到这一点?向量,对象和排序

我得到它的工作时,我的向量类型是< int>但我似乎无法填充类IPRecord作为对象的向量。

#include <iostream> 
#include <vector> 
#include <fstream> 
#include <algorithm> 
#include "IPRecord.hpp" 

using namespace std; 

int main() 
{ 
vector<IPRecord*> v; 

ifstream inputFile("input.txt"); 

int fileSize; 

inputFile >> fileSize; 

//populate vector and sort 
for (int i = 0; i < fileSize; i++) 
{ 
    int val; 
    inputFile >> val; 
    v.insert(lower_bound(v.begin(), v.end(), val), val); 
} 

//print 
for (int i = 0; i < v.size(); i++) 
{ 
    cout << v[i] << endl; 
} 




inputFile.close(); 

return 0; 
} 
+1

您没有创建任何“IPRecord”类型的对象。这个问题与指针无关。你还没有解释这个问题到底是什么。编译错误?运行?工作错了?怎么样? –

+0

对不起,对,错误在汇编中。我对使用类对象作为向量的概念也很陌生。我习惯于使用int和double。所以我甚至不知道应该如何创建IPRecord对象。 –

+0

然后你需要任何C++教程来开始。他们都会穿过物体。 –

回答

-2

这只是一个代码片段,未经测试。代码被评论,因此是自我解释。

int main() 
{ 
    vector<int*> v; // pointer of object means you have to destroy yourself. Better replace with smart pointers later 

    ifstream inputFile("input.txt"); 

    char buf[8]; 
    int filesize; 

    int* storage; 

    if (inputFile) 
    { 
     inputFile.getline(buf, 8, '\n'); // assuming numbers on separate lines 
     filesize = atoi(buf); 

     //allocating for filesize objects. This need to exist since you are storing pointer 
     storage = (int*)malloc(filesize * sizeof(int)); 
     //populate vector and sort 
     int count = 0; 

     while (!inputFile.eof()) 
     { 
      int val; 
      inputFile.getline(buf, 8, '\n'); // assuming numbers on separate lines 
      storage[count] = atoi(buf); 
      v.push_back(storage+count); 
      count++; 
     } 
     inputFile.close(); 


     //print 
     for (auto i = v.begin(); i != v.end(); i++) 
     { 
      cout << (*i) << endl; 
     } 

     free(storage); 


    } 

    return 0; 
} 
+2

这个:'storage =(int *)malloc(filesize * sizeof(int));'应该替换为'storage = new int [filesize];',为什么你会推荐一个不受保护的指针来代替向量,这个'while(!inputFile.eof())'将总是读取超过文件末尾,给出一行未定义的行为,遗忘程序并错过所有非EOF错误事件,可能导致无限循环。更多关于这里:http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong。是的,这是未经测试的代码,但这也是非常糟糕的建议。 – user4581301