向量下标超出范围 [英] Vector subscript out of range

查看:303
本文介绍了向量下标超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Records
{
    //DWORD message;

    int KeyNo;
    DWORD startTime;
    DWORD endTime;
    DWORD elapsed;
};
std::vector<Records> NoteArray;









void CDemoDlg::OnNoteOn(CPianoCtrl &PianoCtrl, unsigned char NoteId)
{
    midi::CShortMsg ShortMsg(midi::NOTE_ON, 0, NoteId, 127, 0);
    ShortMsg.SendMsg(m_OutDevice);

    if(RecordFlag==TRUE)
    {
     EventsCount=EventsCount+1;
  
    NoteArray[EventsCount].KeyNo=m_Keys.KeyNo;/* The Warning statement as Vector subscript out of range*/
    
    }

}




我是使用Vector的新手,所以请指导我.




I am new to use Vectors so please guide me.

推荐答案

如果声明您的vector可以容纳Record对象,并且您想按下"int"进入此向量,则您的Record结构应具有采用int
的构造函数
If your vector is declared to hold Record objects and if you want to to push an ''int'' into this vector then your Record structure should have constructor which takes int

struct Records
{
    //DWORD message;

    int KeyNo;
    DWORD startTime;
    DWORD endTime;
    DWORD elapsed;

   // constructor taking int argument
   Records(int key_in) : KeyNo(key_in) 
   {
      // Initialize other members appropiately
   }
};



通过这种方式,您可以从int构造Record对象,并且可以将该对象推送到vector.

希望您知道



Buy this way you are constructing Record object (from int) and this object can be pushed to vector.

Hope you got it


这是警告还是您正在崩溃窗口?

如果您的崩溃窗口带有向量订阅超出范围",则您正在尝试访问它不持有的向量元素.

假设您已推送3个元素,并且如果您说vec [4],则将导致这种类型的错误.

比较NoteArray向量的大小和EventsCount变量值.
Is this warning or your are getting crash window ?

If you have crash window with "vector subscription out of range", then you are trying to access vector element which it is not holding.

Say if you have pushed 3 elements and if your say vec[4], then this type of error results.

compare NoteArray vector size and EventsCount variable value.


您可以使用vector
的push_back()方法

You can use push_back() method of vector

vector<int> vec;
vec.push_back(8);
vec.push_back(18);
vec.push_back(118);



检查一下:

http://www.cplusplus.com/reference/stl/vector/ [



check this:

http://www.cplusplus.com/reference/stl/vector/[^]


这篇关于向量下标超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆