I feel so lost trying to figure this out. I have my own data structure that I am planning on using vectors to avoid having to keep track of free space and reorginization that I would need to do if I used a simple array. I don’t don’t know if I’m just not initializing properly or what, but every assignment I do seems to just disappear into thin air.
Here is some simple code to illustrate what I’m talking about:
#include <vector>
#include <iostream>
using namespace std;
struct node
{
int test_int;
bool test_bool;
};
struct file
{
vector<node> test_file;
};
int main()
{
file myfile;
int myint;
cout << "Enter number: ";
cin >> myint;
myfile.test_file[0].test_int = myint;
cout << "Number entered is: " << myfile.test_file[0].test_int << endl;
return 0;
}
So basically it is a vector inside a struct. It seems that the normal ways to access a vector don’t seem to work, as in I can’t read or write anything to the vector however things like myfile.test_file.size() seem to work (as in they return a ‘0’ from a freshly created struct). Trying to access the index directly by myfile.test_file[0].test_int results in a runtime error of vector subscript out of range as if it isn’t actually there.
Am I not initializing it properly? This seems kind of ridiculous to me and I can’t understand why it wouldn’t work that way.
Edit:
Edited code to more clearly show behavior I’m referring to. This compiles but gives a runtime error vector subscript out of range
The edited version doesn’t work because you’re accessing an element past the end of the vector:
Before you can do this, you need to either
resize()the vector, or add an element usingpush_back():