使用STL字符串和向量类的异常问题
Exception Problems using the STL string and vector class
我对编程相当陌生,仍然不知道为什么会发生这种情况,也不知道如何修复我在运行这个程序时得到的异常。异常究竟是如何发生的?下面是代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
///////////////////////// SCREEN CLASS ////////////////////////////
class Screen
{
private:
/////////////////////////////////////////// Screen Variables //////////////
string _name;
string _contents[56];
public:
Screen(){};
~Screen(){};
//////////////////////////////////////////// Display ///////////////
void Display()
{
for (int I = 0; I <56; I++)
{
cout << _contents[I];
}
};
/////////////////////////////////////////// Insert ///////////////////////
bool Insert(vector <string> _string)
{
vector<string>::const_iterator I;
int y = 0;
for (I = _string.begin(); I != _string.end(); I++)
{
_contents[y] = _string[y];
y++;
}
return true;
};
};
///////////////////////////////////////////// Main ////////////////////////
int main()
{
vector <string> Map(56);
string _lines_[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};
int offset = 0;
for (vector <string>::const_iterator I = Map.begin(); I != Map.end(); I++)
{
Map[offset] = _lines_[offset];
offset++;
}
Screen theScreen;
theScreen.Insert(Map);
theScreen.Display();
char response;
cin >> response;
return 0;
}
我得到了这个异常:
First-chance exception at 0x5acfc9c7 (msvcr100d.dll) in TestGame.exe: 0xC0000005: Access violation reading location 0xcccccccc.
Unhandled exception at 0x5acfc9c7 (msvcr100d.dll) in TestGame.exe: 0xC0000005: Access violation reading location 0xcccccccc.
指向"memcpy.asm"中的这行代码:
185 rep movsd ;N - move all of our dwords
谢谢! !
您创建了一个包含56个元素的vector
:
vector <string> Map(56);
然后定义一个包含五个string
对象的数组:
string _lines_[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};
然后尝试从该数组中读取56个string
对象:
v 56 elements between begin() and end()
for (vector <string>::const_iterator I = Map.begin(); I != Map.end(); I++)
{
Map[offset] = _lines_[offset];
^ reading from the I'th element of the array
由于数组中只有五个元素,您正在读取未初始化的内存(或初始化但可能不包含string
对象的内存)并将该内存视为包含string
对象。
我不太确定你想做什么,但为什么不直接插入字符串到vector
?
vector<string> Map;
Map.push_back("Hi");
Map.push_back("Holla");
// etc.
或者使用std::copy
算法:
int elements_in_lines = sizeof(_lines_) / sizeof(_lines_[0]);
std::copy(_lines_, _lines_ + elements_in_lines, std::back_inserter(Map));
相关文章:
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题
- 发生此错误:在0x0F2BFB7C(基于.dll)时引发异常 尝试更改大小是问题吗?
- 关于异常继承中的语法的问题
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 存在内存访问异常,但我不确定我的代码中出了什么问题
- Catch2 迫使我在异常中添加对 std::string 的强制转换,这会产生其他问题吗?
- (SDL 渲染问题)C++ 引发异常:读取访问冲突.这是无效的
- PCL 和 CMake 的问题:链接时未定义统计异常值删除
- 值传递、异常/断言和类设计.批评/问题
- 在使用SFML时,我会得到记忆或出于界限异常,这是什么问题
- 此C 异常语法有什么问题(std :: runtime_error)
- 递归中的异常问题(8皇后问题)
- 如何避免意外异常导致的问题
- 为什么我们需要 RAII 来解决异常安全问题
- 异常处理问题,原因
- 向量使用的异常问题
- c++基本异常问题
- C++ 中的 I/O 异常问题("cin"语句)
- 浮点异常问题
- 使用STL字符串和向量类的异常问题