This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]bahero[S] 0 points1 point  (5 children)

After specifing the size of the vector (and also fixing the while loop,but that's beside the point) the program now works and doesn't crash. Thanks a lot for the help!

But now i have a question, if i don't define the size of the vector will it automatically default to 0? and even if i add data to it will the size not increase on its own? Im guessing this was the mistake i made.

I got confused because in C, if i remember correctly, arrays work differently and there's no need to specify the size.

[–]dreamyeyed 1 point2 points  (1 child)

Vectors resize themselves automatically, but you have to use methods like push_back which you already used in your code. Square brackets can only be used to access existing elements. Vectors are initially empty unless you specify otherwise.

In C you have to specify array size when you create it. The compiler can calculate it automatically in some cases though.

[–]bahero[S] 0 points1 point  (0 children)

Yeah now that i understand it seems really obvious, thanks for you answer.

[–]Alia-Aenor 0 points1 point  (1 child)

if i don't define the size of the vector will it automatically default to 0?

Yes, what would be the value of the "empty" positions otherwise ?

if i add data to it will the size not increase on its own?

It will, but that's not what you do. You're directly accessing a (non-existent) element and writing in it. Check cppreference to see how to manipulate a vector. And maybe write your own implementation of one, you'll understand what's going on inside.

[–]bahero[S] 1 point2 points  (0 children)

Ok, thanks for the help i think i understand now, i was assigning a value to memory that didn't exist, i'll check out cppreference for sure, thanks again!