简体   繁体   中英

Unable to initialize vector with initializer list in visual studio code

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    vector<int> v = {1,2,3,4};
    for (int x : v)
    {
        cout << x << ' ';
    }
return 0;
}

When I run the above code in vscode I receive the following ERROR:

non-aggregate type 'vector' cannot be initialized with an initializer list gcc [7, 17]

NOTICE - the error includes gcc even though that is not the compiler I am using.

The code compiles fine in the terminal and in Xcode so I know it has something to do with vscode. How do I fix this issue?

NOTE - I am using IC/C++ IntelliSense with the following configurations: Compiler Path (/usr/bin/clang++) IntelliSense mode (macros-clang-arm64) Include path (${workspaceFolder}/**) C standard (c17) C++ standard (C++17).

You might post your code and how you're compiling it. The following worked for me:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1,2,3,4};
    for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i) {
        std::cout << *i << ' ';
    }
    std::cout << std::endl;
    return 0;
}

Compiled and run like so:

$ g++ -std=c++11 test.cpp
$ ./a.out
1 2 3 4
$

Did you include it?

#include <vector>

If you include it you can set it easily like below:

    vector<int>numbersVect = {1,2,3,4};

If all of the previous doesn't work you can check this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM