矢量订阅超出范围

Vector subscription out of range

本文关键字:范围      更新时间:2023-10-16

我是C++新手,在处理向量时遇到了问题。

我需要从另一个类访问在"GridClass"中声明的向量,所以我将向量声明为公共并向量并尝试填充它。这是我的代码。

网格类.h

#include <vector>
class GridClass : public CDialog
{
    DECLARE_DYNAMIC(GridClass)
public:
    GridClass(CWnd* pParent = NULL);   // standard constructor
    virtual ~GridClass();
protected:
    int nItem, nSubItem;
public:
    std::vector<CString> str; // <--The vector

在网格类.cpp;

str.reserve(20);//This value is dynamic
for(int i=0;i<10;i++){
    str[i] = GetItemText(hwnd1,i ,1);// <-- The error occurs here
}

不能使用数组,因为大小是动态的,我只用了 20 进行调试。我在这里做错了什么?

std::vector::reserve 只会增加 vector 的容量,它不会分配元素,str.size() 仍然是0,这意味着 vector 是空的。

str.resize(20);

或者只是打电话std::vector::push_back

str.reserve(20);   // reserve some space which is good. It avoids reallocation when capacity exceeds
for(int i=0; i<10; i++){
    str.push_back(GetItemText(hwnd1,i ,1)); // push_back does work for you.
}

调用 reserve 后向量仍然为空;您仍然需要添加带有 insertpush_back 的字符串,或者带有 resize 的空字符串。

要使用循环填充十个字符串,请使用 push_back

for(int i=0;i<10;i++){
    str.push_back(GetItemText(hwnd1,i ,1));
}

或者,如果您想要 20 个字符串,分配前 10 个并将其余字符串留空,那么您可以保留循环,但使用 resize 而不是 reserve