Code Not Working (Vectors) Topic is solved

Talk about things C/C++, some related to AutoHotkey
1100++
Posts: 78
Joined: 10 Feb 2018, 19:05

Code Not Working (Vectors)

01 Jan 2020, 13:01

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?
HotKeyIt
Posts: 2134
Joined: 29 Sep 2013, 18:35
Contact:

Re: Code Not Working (Vectors)

01 Jan 2020, 14:58

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;
1100++
Posts: 78
Joined: 10 Feb 2018, 19:05

Re: Code Not Working (Vectors)  Topic is solved

01 Jan 2020, 15:06

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;
}

Return to “C/C++”

Who is online

Users browsing this forum: No registered users and 4 guests