矢量订阅超出范围 [英] Vector subscription out of range

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

问题描述

我是C ++的新手,并且遇到处理向量的问题。

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

I'm new to C++ and have faced a problem dealing with vectors.

I need to access a vector declared in "GridClass" from another class, so I declared the vector as public and tried to populate it. Here's my code.

GridClass.h

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

在GridClass.cpp中;

In the 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
}

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

I cannot use an array as the size is dynamic, I only used 20 for debugging. What am I doing wrong here?

推荐答案

std :: vector :: reserve 只增加vector的容量,不分配元素, str.size() / code>仍然是 0 这意味着向量是空的,你需要 std :: vector :: resize

std::vector::reserve only increase the capacity of vector, it doesn't allocate elements, str.size() is still 0 which means vector is empty., you need std::vector::resize in this case:

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.
}

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

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