矢量订阅超出范围

use*_*330 3 c++ runtime-error vector visual-studio-2010

我是C++的新手,遇到了处理向量的问题.

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

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
Run Code Online (Sandbox Code Playgroud)

在GridClass.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
}
Run Code Online (Sandbox Code Playgroud)

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

bil*_*llz 6

std :: vector :: reserve只增加vector的容量,它不分配元素,str.size()仍然0表示vector是空的.在这种情况下你需要std :: vector :: resize:

str.resize(20);
Run Code Online (Sandbox Code Playgroud)

或者只是打电话 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.
}
Run Code Online (Sandbox Code Playgroud)