【问题标题】:Runtime error for double dimensional vector二维向量的运行时错误
【发布时间】:2013-07-31 04:57:36
【问题描述】:

我在使用二维向量时遇到问题。在我的 main() 调用之前,我已经在我的头文件中将双向量声明为外部变量,并在我的 main.cpp 文件中再次声明(不是作为外部变量)。我调用一个函数来为双向量动态分配内存。给定的代码没有编译错误。但是在运行时,如果您访问该向量,它会给出一个向量下标超出范围异常。我使用调试器检查了它,发现向量在函数中分配了内存,但是一旦它回来(超出函数范围),向量大小就会回到 0。 我已附上代码

颜色.h:

#ifndef __COLOR__
#define __COLOR__

class color{
        public :
        int r,g,b;

        color(void);
        color(int R, int G,int B);
    };
#endif

颜色.cpp

#include"color.h"
#include <iostream>

color::color(void){
    r=g=b=0;
}
color::color(int R, int G,int B){
    if(R<=1 && G<=1 && B<=1){
    r=R;g=G;b=B;
    }
    else{
    std::cout<<"Error in RGB values";
    }
}

header.h:

#ifndef __HEADER__
#define __HEADER__

    #include <iostream>
    #include <vector>

    #include "color.h"

    const int windowWidth=200;
    const int windowHeight=200;

    void function();

    extern std::vector <std::vector<color> > buffer;

#endif __HEADER__

颜色.cpp

#ifndef __COLOR__
#define __COLOR__

class color{
        public :
        int r,g,b;

        color(void);
        color(int R, int G,int B);
    };
#endif

main.cpp

#include "header.h"
std::vector <std::vector<color> > buffer;
void main(void){
    //myClass obj=myClass(1,4);

    function(/*obj*/);
    std::cout<<"HI";
            std::cout<<"vector : "<<buffer[0][0].r;  //VECTOR SUBSCRIPT OUT OF RANGE
    getchar();
}
void function(){
    std::vector <std::vector<color> > buffer (2*windowHeight, std::vector<color>(2*windowWidth));
    std::cout<<"HI";
}

【问题讨论】:

    标签: c++ vector runtime


    【解决方案1】:

    您的函数调用 function() 对 main.cpp 中定义的变量 buffer 没有副作用。所以在你的 main 函数中它试图访问它会导致未定义的行为。

    如果您打算让function() 修改全局buffer 变量,您可以让function() 返回向量。

    std::vector <std::vector<color> > function()
    {
        std::vector <std::vector<color> > buffer (2*windowHeight, std::vector<color>(2*windowWidth));
        std::cout<<"HI";
        return buffer;
    }
    
    int main()
    {
        buffer = function();
        std::cout<<"vector : "<<buffer[0][0].r; // now you should be fine to access buffer elements
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2013-10-29
      • 2015-02-23
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多