Search code examples
c++vectorinitializationvariable-assignment

Can't assign value to vector in c++


I am trying to assign value to a vector but I keep getting different errors. I am using clang++ version 14.0.0 to build the file and I am getting the error using vs code debugger.

Here are the different erros:

When i run this code

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    
    v = {0, 1};

    return 0;
}

I get the error "expected expression".

When i run this code

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> v;
    
    v = vector<int>{0, 1};

    return 0;
}

I get error "expected '(' for function-style cast or type construction"

Neither initiliazing nor assigning the vector later seems to work.

If my problem is unclear. Please let me know how I can improve :)


Solution

  • clang++ on Mac defaults to using C++98 (-std=c++98) and in C++98 both errors are to be expected.

    Just add

    -std=c++11
    

    (or later, like -std=c++14, -std=c++17 or -std=c++20) when compiling and both your snippets will compile fine.