在免费存储上声明 C++ 向量时抛出超出范围异常

问题描述 投票:0回答:1

我正在解决 Stroustrup 的 PPP 书中第 17 章 - 演习中的一个问题。 我不断抛出超出范围的错误,并相信在初始化向量 m_vec 的值时可能会错误地访问它。我已尝试使用声明为 [[with size = 10]] 的向量尝试使用 '*' 和 '&' 运算符,但出现类似 C6200 Index '4' is out of range '0' to '1' for non-stack buffer ' 的错误m_vec'。

这是我的代码 - 谁能帮忙--

#include <iostream>
#include <vector>

void print_array10(std::ostream &os, int *a, int n);
void print_vector(std::ostream &os, std::vector<int> vec1);

int main()
{
    using std::cout;
    using std::endl;
    using std::vector;

    //create the ostream for printing
    std::ostream os(std::cout.rdbuf());

    // allocate a vector of int on the free store and initialize it

    vector<int>* m_vec = new vector<int>( 10 );
                    // vector<Type> *vect = new vector<Type>(integer); allocates the vector size
                    // with everything on the free store (except vect pointer, which is on the stack).


    // initialize the vector with integers starting at 100
    for (int i = 0; i <= 9; ++i) {
        m_vec->push_back(1);
        m_vec[i] = { i };
    };

    cout << &m_vec[4] << endl;
    cout << "  " << m_vec->size() << endl;



    //print_vector(os, *m_vec);

    delete m_vec;
    return 0;
};


// create print_vector function
void print_vector(std::ostream &os, std::vector<int> vec1) {
    for (int i = 0; i < 10; i++)
        std::cout << vec1[i] << std::endl;
};

我让这个 Drill 的数组部分正常工作,并且能够使用指针 // 取消引用 // 或 [] 下标运算符访问数组(在免费存储上)。当我对免费商店中声明的向量尝试相同的方法时,我在运行时遇到“超出范围”异常。

与我在免费商店中创建的向量关联的“非堆栈”缓冲区是什么?我该如何解决这个问题?

我还偶尔收到一些错误消息,建议我在 16 位空间中使用 32 位整数......鉴于上面的代码,我不太明白。当我在 for 循环中将 100 添加到“i”以初始化向量时,就会发生这种情况。关于这个的任何想法...我认为整数都是 32 位。

感谢您的帮助。

c++ vector heap-memory new-operator outofrangeexception
1个回答
0
投票

向量不要使用 new 关键字。它的元素始终位于堆/自由存储中。查找向量的文档以及有关如何初始化它们的示例。另外,我建议将三个 using 语句移到主函数之外和之上。

© www.soinside.com 2019 - 2024. All rights reserved.