将vector初始化为0

Initialize vector to zero

本文关键字:初始化 vector      更新时间:2023-10-16

初始向量"perm"为空。我想根据循环的索引把它设为0。但我遇到错误"矢量下标超出范围",而做下面的代码。

我把"perm(charLength, 0)"放在任何循环之外的"Start()"方法中,这样它就不会被重置,它用于累积值。

DecodeEngine.h

class DecodeEngine
{
public:
    vector<int> temp;
    vector<int> perm;
    //Default constructor
    DecodeEngine();

    //Declare a virtual destructor:
    virtual ~DecodeEngine();
    //Methods
    string GetFilePath();
    Mat Start();
    void FrameTo8by8();         
};

DecodeEngine.cpp

Mat DecodeEngine::Start()
{
  charLength = 160;
  //Initialize perm to zero
  perm(charLength, 0);
  //Loop 1st 100 frame of header
  while(true)
  {
     if(frame_count <= 100)
     {
        FrameTo8by8();                  //Proccess and algorithm
        namedWindow("dctBlockImage"); 
        imshow("dctBlockImage", dctImage);      //display watermarked image
        if(waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
        {
            cout << "esc key is pressed by user" << endl; 
            break; 
        }
        frame_count++;
     }
     else
     {
        cout << endl;
        cout << "End of video" << endl;
        cout << endl;
        destroyWindow("Original Video");
        destroyWindow("dctBlockImage");
        break;
     }
}


void DecodeEngine::FrameTo8by8()
{
  for(int i = 0; i < height-16; i += 16)
  {
    for(int j = 0 ; j < width-16; j += 16)
    {
       if(j > 112)
       {
           if(((sum4 / 4) - avg) > 0)
           {
              value = 0;
              temp.push_back(value);
           }
           else
           {
              value = 1;
              temp.push_back(value);
           }
       }
       if(temp.size() == charLength)
       {
          for(int a = 0; a <= temp.size(); a ++)
          {
             //Initialize perm to zero
             perm[a] = 0;
             if(temp[a] == 1)
             {
                perm[a]++;
             }
             //Reset temp for next frame to use
             temp[a] = 0;
          }
       }                
    }
  }
}

这一行:

perm(charLength, 0);

不调用构造函数std::vector(size_t, const T&)并初始化值为10的160个元素的向量。事实上,我根本看不出这是如何编译的,因为vector类没有operator()

std::vector包含一个成员函数assign(),您可以替换它:

perm.assign(charLength, 0);

在下面这段代码中,您超出了范围:

   ...
   if(temp.size() == charLength)   // ok!  temp.size() is same as perm.size() 
   {
      for(int a = 0; a <= temp.size(); a ++)   // !!! loop will execute with a=temp.size() and stop afterwards
      {
         //Initialize perm to zero
         perm[a] = 0;                    // !!! but subscripts start with 0 and go to temp.size()-1