Basically, in C++ you can't put any code (unless it is a definition or declaration) outside functions. All that the program does happens within one function or another.
So your problem has nothing to do with vector specifically.
int a = 1; //declare a global variable, OK
a += 1; //nope, can't do this outside functions
std::cout << a << '\n'; //nor this
>> Proof it works without int main:
It didn't work there either:
It's not that the compiler doesn't like you, it's just like a big ole calculator. If you push the wrong buttons it gives you the wrong answer. If you write a program that doesn't adhere to the rules of the language then it will not compile. Every program needs an entry point, programs don't just start wherever they feel like it. If you don't have an int main then it just wont run.
You can call your compiler or the C++ language names as much as you like until you're blue in the face, it doesn't care. But if you want to do programming you just have to obey the rules of the language, that's just how it is. You're free to complain and protest loudly about your code not compiling, if you must, but if your goal is to learn to program then it wont help you. What will help is having plenty of reference material handy.
This is a basic question, but why would we want to use vectors when it seems a linked list does the same thing?
Put another way, why use linked lists when vectors do the same thing??
- What does it take to remove an item from the start of a vector, and how long does that take compared to a list when there are 1 million items?
- I want to lookup the value of item 999999 in the above list or vector. Which one is faster, and why?
- I have a number of pointers to the items in my list/vector and I want to remove an item. For which one of these will that cause problems?
Inserting into the middle of a linked list is easy. Inserting into the middle of a vector is a pain.
Thanks for the info.
How difficult is it to search in a vector? Say I have a vector x = [ 1, 3, 5, 2, 5, 5] and I want to know in which indices, if any, the number 5 occurs. Would that be difficult?
In this case, a map would be better.
There are lots of different containers that seem to do the same thing, but have different strengths and weaknesses. Your job as a programmer is to use the correct tool for the job.