Page 1 of 1

Code Not Working (Vectors)

Posted: 01 Jan 2020, 13:01
by 1100++
As a test, I wrote a code sample that includes a pointer to a vector in a struct. It attempts to create an instance of the struct, assign a new vector to it, assign a value to one of the vector's members, and then print that value as read from the vector.

Code: Select all

#include <iostream>
#include <vector>

using namespace std;

typedef struct {
	__int64 size = 0;
	vector<__int64>* array;
} int_array;

int main () {
	int_array num_array;
	num_array.array = new vector<__int64>;
	num_array.array->reserve(5);
	(*num_array.array)[0] = 5;
	cout << (*num_array.array)[0];
	return 0;
}
However, when I run the code, I get an error "vector subscript out of range". Am I doing something wrong?

Re: Code Not Working (Vectors)

Posted: 01 Jan 2020, 14:58
by HotKeyIt
Probably:

Code: Select all

	num_array.array->push_back(5);
	cout << num_array.array->at(0);
Or

Code: Select all

	num_array.array->resize(5);
	num_array.array->at(0) = 5;

Re: Code Not Working (Vectors)  Topic is solved

Posted: 01 Jan 2020, 15:06
by 1100++
I figured it out.

Code: Select all

#include <iostream>
#include <vector>

using namespace std;

typedef struct {
	__int64 size = 0;
	vector<__int64>* array;
} int_array;

int main () {
	int_array num_array;
	num_array.array = new vector<__int64>;
	num_array.array->resize(5);	// Apparently, reserve() doesn't do what I thought it did.
	(*num_array.array)[0] = 5;
	cout << (*num_array.array)[0];
	return 0;
}