矢量订阅超出范围
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
后向量仍然为空;您仍然需要添加带有 insert
或 push_back
的字符串,或者带有 resize
的空字符串。
要使用循环填充十个字符串,请使用 push_back
:
for(int i=0;i<10;i++){
str.push_back(GetItemText(hwnd1,i ,1));
}
或者,如果您想要 20 个字符串,分配前 10 个并将其余字符串留空,那么您可以保留循环,但使用 resize
而不是 reserve
。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 尝试通过多个向量访问变量时,向量下标超出范围
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 不计算一个范围内的完美数
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 如何访问超出其块范围的对象?
- 矢量下标超出SFML游戏中的范围