Code Not Working (Vectors)

Post a reply

Confirmation code
Enter the code exactly as it appears. All letters are case insensitive.
Smilies
:D :) ;) :( :o :shock: :? 8-) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :!: :?: :idea: :| :mrgreen: :geek: :ugeek: :arrow: :angel: :clap: :crazy: :eh: :lolno: :problem: :shh: :shifty: :sick: :silent: :think: :thumbup: :thumbdown: :salute: :wave: :wtf: :yawn: :facepalm: :bravo: :dance: :beard: :morebeard: :xmas: :HeHe: :trollface: :cookie: :rainbow: :monkeysee: :monkeysay: :happybday: :headwall: :offtopic: :superhappy: :terms: :beer:
View more smilies

BBCode is ON
[img] is OFF
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Code Not Working (Vectors)

Re: Code Not Working (Vectors)

by 1100++ » 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;
}

Re: Code Not Working (Vectors)

by HotKeyIt » 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;

Code Not Working (Vectors)

by 1100++ » 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?

Top