矢量,对象和排序

时间:2016-09-25 03:44:56

标签: c++ class sorting pointers vector

我正在尝试使用文件中的整数对对象矢量进行排序和填充。 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 个答案:

答案 0 :(得分:-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;
}