我对编程还很陌生,仍然不知道为什么会发生这种情况,也不知道如何解决我在运行我正在制作的程序时遇到的这个异常…… 异常是如何发生的?那么这是代码:
#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++ - 使用 STL 字符串和 vector 类的异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827526/