I'm trying to teach myself some C++17.
Why is the compiler throwing an error for the below code snippet?
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v = { 3, 1, 4 };
std::cout << std::size(v) << '\n';
int a[] = { -5, 10, 15 };
std::cout << std::size(a) << '\n';
}
The compiler throws the following error
manish@Manish-Tummala:~/c_files$ g++ 6.cpp -o - 6.out
6.cpp: In function ‘int main()’:
6.cpp:8:23: error: ‘size’ is not a member of ‘std’
std::cout << std::size(v) << '\n';
^~~~
6.cpp:8:23: note: suggested alternative: ‘size_t’
std::cout << std::size(v) << '\n';
^~~~
size_t
6.cpp:11:23: error: ‘size’ is not a member of ‘std’
std::cout << std::size(a) << '\n';
^~~~
6.cpp:11:23: note: suggested alternative: ‘size_t’
std::cout << std::size(a) << '\n';
^~~~
size_t
The C++ function std::array::size() is used to get the number of elements present in the array.
Master C and Embedded C Programming- Learn as you goC++98 − GCC has full support for the 1998 C++ standard as modified in 2003 and renamed to C++03 and some later defect reports. C++11 − GCC 4.8.
GCC has experimental support for the latest revision of the C++ standard, which was published in 2020. C++20 features are available since GCC 8.
For C++17 support in GCC, please refer to:
The C++17 compilation mode is the default starting with GCC 11.1. In earlier GCC versions, it is possible to enable with a command-line parameter:
To enable C++17 support, add the command-line parameter
-std=c++17
to yourg++
command line. Or, to enable GNU extensions in addition to C++17 features, add-std=gnu++17
.
Note that for GCC versions before GCC 9.1, the C++ library ABI was still considered unstable, so if you build and link your application with an earlier compiler, it may not work correctly with a different libstdc++ run-time library version (from a different GCC release, such as introduced by an operating system upgrade).
For VSCode: Add an explicit reference to C++17 would help which can be done by modifying the tasks.json file in the folder
"args": [
"-std=c++17",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
]
Your g++ installation needs to be at version 6 or higher. You can check it with
g++ -v
If your g++ version is high enough. You must also execute it with the c++17 command line option.
g++ -std=c++17 6.cpp -o 6.out
or
g++ -std=gnu++17 6.cpp -o 6.out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With