c ++未处理的异常

时间:2014-07-12 06:15:22

标签: c++ c++11

你好我是c ​​++的新用户,我有一个问题 我想将文本文件读入矢量。这个文件有57 000行,我遇到了这个问题

  

项目2.exe中0x764d4dbd处的未处理异常:Microsoft C ++异常:内存位置为0x007ceb48的std :: bad_alloc ..

这是我的编码

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <vector>
#include <string>
#include <malloc.h>
using namespace std;

const int m = 17000;
const int n = 2;

std::vector< vector<long double> > student (m, vector<long double>(m,n));

ifstream inpStud("Carleton91.stu");
ofstream outData ("output.txt");

void readstudent(){

    long double k, numline;
        //assign all data to an array
    for (int i= 0; i<m; i++)
    {
        for (int j= 0; j<n; j++)
        {
            inpStud >> student[i][j];   
            k=student[i][j];    
        }

        //count number of exam
        if ((k==2) && (i>100)){
                numline = i;
                break;

        }
    }

    //print data
    for (int i= 0; i<numline; i++)
    {
        for (int j= 0; j<n; j++)
        {
            outData << student[i][j] << "    ";
        }
        outData << endl;
    }
}

int main() 
{

    readstudent();

    inpStud.close();
    outData.close();
    return 0;

我知道实际问题是什么...请有人帮助我...谢谢

这是文件enter link description here

2 个答案:

答案 0 :(得分:1)

const int m = 17000;
const int n = 2;

std::vector< vector<long double> > student (m, vector<long double>(m,n));

这会创建一个vectorvector<long double>个包含17000个向量,每个向量依次包含17000个long double个,每个向量初始化为2个。

long double每个通常至少8个字节,具体取决于系统。我们现在采取下限。忽略vector的所有开销,您将分配空间来存储17000 * 17000 = 2.89亿long double个值;假设每long double个8字节,即23.12亿字节,或大约2.15GB。

Windows上32位程序的用户模式地址空间通常为2GB(32位指针只能处理4GB,其中一半用于操作系统使用),这意味着该程序不能可能会分配所有内存。其中一个分配失败,抛出std::bad_alloc异常,导致您得到错误。

答案 1 :(得分:1)

假设您要做的是为每个学生存储多个值,那么更好的选择是使用std::map<int, std::vector<int>>。这样,您就可以将一名学生映射到与学生相关的所有数据的向量。

由于数据似乎只是一个int,因此vector<int>是地图中需要表示的所有数据项。

以下代码与您的文件一起使用没有问题(如果文件URL链接断开,文件由两个整数的行组成 - 第一个是学号,第二个整数是课程号):

#include <vector>
#include <map>
#include <fstream>
#include <iterator>
#include <iostream>
#include <algorithm>

typedef std::map<int, std::vector<int>> MapIntToVector;

using namespace std;
int main()
{
    MapIntToVector m_mapIntVect;
    ifstream ifs("Carleton91.stu");
    int studentNumber, studentCourse;
    while (ifs)
    {
        ifs >> studentNumber >> studentCourse;
        m_mapIntVect[studentNumber].push_back(studentCourse);
    }
    // output data
    MapIntToVector::iterator it = m_mapIntVect.begin();
    while (it != m_mapVect.end())
    {
        cout << "Here is student " << it->first << " course(s) taken: ";
        std::copy(it->second.begin(), it->second.end(), ostream_iterator<int>(cout, " "));
        cout << "\n";
        ++it;
    }
}

输入和输出从文件中读入的学生。

只要遇到新的学号,输入部分就会在地图中创建一个新条目。无论学生条目是否为新条目,数据项都会被推送到与学生相关的向量上。

我留给你研究std::map等容器。

相关问题