使用STL字符串和向量类的异常问题

Exception Problems using the STL string and vector class

本文关键字:异常 问题 向量 STL 字符串 使用      更新时间:2023-10-16

我对编程相当陌生,仍然不知道为什么会发生这种情况,也不知道如何修复我在运行这个程序时得到的异常。异常究竟是如何发生的?下面是代码:

#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));