• 카테고리

    질문 & 답변
  • 세부 분야

    게임 프로그래밍

  • 해결 여부

    해결됨

예외가 throw됨: 쓰기 액세스 위반입니다. this->_data이(가) 0x1110112였습니다.

22.11.24 21:40 작성 조회수 2.02k

0

계속 제목과 같은 오류가 뜹니다 ㅠㅠ 살려주세요..

#include <iostream>
#include <vector>
using namespace std;


// vector를 만들어보자

template<typename T>
class Vector
{
public:
	Vector() : _data(nullptr), _size(0), _capacity(0)
	{

	}

	~Vector()
	{
		if (_data)
			delete[] _data;
	}
	// [               ]
	void push_back(const T& val)
	{
		if (_size == _capacity)
		{
			//증설 작업
			int newCapacity = static_cast<int>(_capacity * 1.5); //실수에서 int로 변환하면 데이터가 잘릴수도있다
			if (newCapacity == _capacity)
				newCapacity++;

			reserve(newCapacity);
		}

		// [1][2][3][]
		_data[_size] = val;
		
		//데이터 개수 증가
		_size++;
	}

	void reserve(int capacity)
	{
		_capacity = capacity;

		T* newData = new T[_capacity];

		//데이터 복사
		for (int i = 0; i < _size; i++)
		{
			newData[i] = _data[i];

			//기존에 있던 데이터를 날린다
			if (_data)
				delete[] _data;

			// 교체
			_data = newData;

		}
	}

	T& operator[](const int pos) { //레퍼런스로 만들어야 데이터를 넣을 수 있음 
		return _data[pos];
	}

	int size() { return _size; }
	int capacity() { return _capacity; }

private:
	T* _data;
	int _size;
	int _capacity;
};

int main()
{
	Vector<int> v;

	//v.reserve(100);

	for (int i = 0; i < 100; i++)
	{
		v.push_back(i);
		cout << v.size() << " " << v.capacity() << endl;
	}

	for (int i = 0; i < v.size(); i++)
	{
		cout << v[i] << endl;
	}


	cout << "-----------------" << endl;

	//
	//	for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
	//	{
	//		cout << (*it) << endl;
	//	}
	//

	return 0;
}

답변 1

답변을 작성해보세요.

0

image

코드가 살짝 다릅니다 !

성민님의 프로필

성민

질문자

2022.11.24

헉; 감사합니다 ㅠㅠ