运行时程序崩溃在向量中创建新的类实例[关闭]

问题描述 投票:-5回答:1

下午好,我的程序有问题,运行时崩溃。我使用this code在向量中创建新的实例类。

main.cpp:

#include <QCoreApplication>
#include <iostream>
#include <vector> //header file where std::vector is defined
#include <myclass.h>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    for(unsigned long long i = 0 ; i<=10;i++){
        std::vector<MyClass>  arr(i, MyClass(10,20+i));
        std::cout << arr[i].ggg;
    }

    return a.exec();
}

myclass.cpp:

#include "myclass.h"

MyClass::MyClass(){}
MyClass::MyClass(unsigned long long g, unsigned long long gg){
    ggg = gg;
}

myclass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
public:
    MyClass();
    MyClass(unsigned long long g, unsigned long long gg);
    unsigned long long ggg;
};

#endif // MYCLASS_H

我在控制台中有这个错误:退出代码-1073741819,我认为问题来自std :: vector <MyClass> arr (i, MyClass (10,20 + i));但我不知道该怎么办。

我不知道问题出在哪里,我是C ++的初学者。预先感谢您的帮助,

c++ windows qt c++11 qt-creator
1个回答
2
投票

你正在循环中重新创建arr 11次我认为你打算这样做:

//the error is generated because you are trying to access an element out of bounds because your declaration is wrong 
std::vector<MyClass>  arr;
for(unsigned long long i = 0 ; i<=10;i++){
       arr.emplace_back( 10,20+i);
        std::cout << arr[i].ggg;
    }
© www.soinside.com 2019 - 2024. All rights reserved.