Last active
May 30, 2022 20:46
-
-
Save danadam/6236b13ab6e013813947957b02f03bd1 to your computer and use it in GitHub Desktop.
std::vector initialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <memory> | |
#include <string> | |
#include <typeinfo> | |
#include <vector> | |
#include <cxxabi.h> | |
template<typename T> | |
std::string getType(const T & t) | |
{ | |
int status = 0; | |
const auto & info = typeid(t); | |
char * type = abi::__cxa_demangle(info.name(), 0, 0, &status); | |
std::string result((status == 0) ? type : info.name()); | |
free(type); | |
return result; | |
} | |
template<typename T> | |
void print(const char* varname, const T & var) | |
{ | |
printf("%s [%3zu] : %s\n", varname, var.size(), getType(var).c_str()); | |
} | |
#define P(var) print(#var, var) | |
int main() | |
{ | |
// https://godbolt.org/z/Gq7oG39qE | |
// 1. vector of 10 integers | |
std::vector<int> a1(10); | |
// 2. vector of 10 integers | |
std::vector<int> a2(10, 1); | |
// 3. vector of 1 integer | |
std::vector<int> a3{10}; | |
// 4. vector of 2 integers | |
std::vector<int> a4{10, 1}; | |
// error: narrowing conversion | |
// std::vector<char> b1{128, 'a'}; | |
// 5. vector of 2 chars | |
std::vector<char> b2{127, 'a'}; | |
// 6. vector of 128 strings | |
std::vector<std::string> b3{128, "a"}; | |
// 7. vector of 10 integers (a copy of a1) | |
std::vector<int> c1{a1.begin(), a1.end()}; | |
// 8. vector of 2 iterators (C++17 required from now on, for Class Template Argument Deduction) | |
std::vector c2{a1.begin(), a1.end()}; | |
// 9. vector of 10 integers (a copy of a1) | |
std::vector d1(a1); | |
// 10a. vector of 1 vector in gcc <= 7.5 and clang <=5 | |
// 10b. vector of 10 integers (a copy of a1) in gcc >= 8.1 and clang >= 6 | |
std::vector d2{a1}; | |
// 11. vector of 2 vectors | |
std::vector d3{a1, a1}; | |
P(a1); | |
P(a2); | |
P(a3); | |
P(a4); | |
// P(b1); | |
P(b2); | |
P(b3); | |
P(c1); | |
P(c2); | |
P(d1); | |
P(d2); | |
P(d3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment