Ian Ian - 3 months ago 7
C++ Question

How do you use a vector in c++?

I am a beginner in c++ and I am trying to understand vectors.

I know the basic format which is:

vector <dataType> vectorName;


People are telling me that vectors are like arrays. But, what I don't

understand is that for arrays you can do this:

array[] = {1, 2, 3}


But for vectors you don't seem to get to set it to a list. Or do you have

to keep using
.push_back()
.

Also, can you use something like
vectorName[1]
or not?

Can anyone explain this to me?

Thanks.

Answer

You can use the style if you use C++11 or later.

#include <iostream>
#include <vector>

int main(void) {
    std::vector<int> vec = {1, 2, 3};
    std::cout << vec[1] << std::endl;
    return 0;
}