-
Notifications
You must be signed in to change notification settings - Fork 0
/
c++_1000.json
1 lines (1 loc) · 616 KB
/
c++_1000.json
1
[{"idx": "webquery-test-1", "doc": "Why is processing a sorted array faster than processing an unsorted array?", "code": "if (data[c] >= 128)\n sum += data[c];\nT = branch taken\nN = branch not taken\n\ndata[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...\nbranch = N N N N N ... N N T T T ... T T T ...\n\n = NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT (easy to predict)\ndata[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118, 14, 150, 177, 182, ...\nbranch = T, T, N, T, T, T, T, N, T, N, N, T, T, T ...\n\n = TTNTTTTNTNNTTT ... (completely random - impossible to predict)\nif (data[c] >= 128)\n sum += data[c];\nint t = (data[c] - 128) >> 31;\nsum += ~t & data[c];\ndata[]-O3-O3-O3-O3-O3-O3"}, {"idx": "webquery-test-2", "doc": "How do I set, clear, and toggle a single bit?", "code": "|number |= 1UL << n;\nnnnnnn1ULL1ULL1ULL1ULL1ULL1ULL&number &= ~(1UL << n);\nnnn^number ^= 1UL << n;\nnnbit = (number >> n) & 1U;\nnnnnnnnumber ^= (-x ^ number) & (1UL << n);\nnnnnnnn-1number ^= (-(unsigned long)x ^ number) & (1UL << n);\nunsigned long newbit = !!x; // Also booleanize to force 0 or 1\nnumber ^= (-newbit ^ number) & (1UL << n);\nnumber = (number & ~(1UL << n)) | (x << n);\n(number & ~(1UL << n))(number & ~(1UL << n))(number & ~(1UL << n))(number & ~(1UL << n))(number & ~(1UL << n))"}, {"idx": "webquery-test-3", "doc": "What is the difference between #include <filename> and #include \"filename\"?", "code": "#include <filename>#include <filename>"}, {"idx": "webquery-test-4", "doc": "What is The Rule of Three?", "code": "class person\n{\n std::string name;\n int age;\n\npublic:\n\n person(const std::string& name, int age) : name(name), age(age)\n {\n }\n};\n\nint main()\n{\n person a(\"Bjarne Stroustrup\", 60);\n person b(a); // What happens here?\n b = a; // And here?\n}\nname(name), age(age)personpersonpersonpersonperson// 1. copy constructor\nperson(const person& that) : name(that.name), age(that.age)\n{\n}\n\n// 2. copy assignment operator\nperson& operator=(const person& that)\n{\n name = that.name;\n age = that.age;\n return *this;\n}\n\n// 3. destructor\n~person()\n{\n}\nnamenamenamenamestd::stringstd::stringclass person\n{\n char* name;\n int age;\n\npublic:\n\n // the constructor acquires a resource:\n // in this case, dynamic memory obtained via new[]\n person(const char* the_name, int the_age)\n {\n name = new char[strlen(the_name) + 1];\n strcpy(name, the_name);\n age = the_age;\n }\n\n // the destructor must release this resource via delete[]\n ~person()\n {\n delete[] name;\n }\n};\nnameaaaaaa// 1. copy constructor\nperson(const person& that)\n{\n name = new char[strlen(that.name) + 1];\n strcpy(name, that.name);\n age = that.age;\n}\n\n// 2. copy assignment operator\nperson& operator=(const person& that)\n{\n if (this != &that)\n {\n delete[] name;\n // This is a dangerous point in the flow of execution!\n // We have temporarily invalidated the class invariants,\n // and the next statement might throw an exception,\n // leaving the object in an invalid state :(\n name = new char[strlen(that.name) + 1];\n strcpy(name, that.name);\n age = that.age;\n }\n return *this;\n}\nnamenamenamenamenamenamenew char[...]// 2. copy assignment operator\nperson& operator=(const person& that)\n{\n char* local_name = new char[strlen(that.name) + 1];\n // If the above statement throws,\n // the object is still in the same state as before.\n // None of the following statements will throw an exception :)\n strcpy(local_name, that.name);\n delete[] name;\n name = local_name;\n age = that.age;\n return *this;\n}\nprivateprivate:\n\n person(const person& that);\n person& operator=(const person& that);\nboost::noncopyableperson(const person& that) = delete;\nperson& operator=(const person& that) = delete;\nclass person\n{\n std::string name;\n int age;\n\npublic:\n person(const std::string& name, int age); // Ctor\n person(const person &) = default; // 1/5: Copy Ctor\n person(person &&) noexcept = default; // 4/5: Move Ctor\n person& operator=(const person &) = default; // 2/5: Copy Assignment\n person& operator=(person &&) noexcept = default; // 5/5: Move Assignment\n ~person() noexcept = default; // 3/5: Dtor\n};\nstd::stringstd::stringstd::string"}, {"idx": "webquery-test-5", "doc": "Why are elementwise additions much faster in separate loops than in a combined loop?", "code": "int main(){\n const int n = 100000;\n\n#ifdef ALLOCATE_SEPERATE\n double *a1 = (double*)malloc(n * sizeof(double));\n double *b1 = (double*)malloc(n * sizeof(double));\n double *c1 = (double*)malloc(n * sizeof(double));\n double *d1 = (double*)malloc(n * sizeof(double));\n#else\n double *a1 = (double*)malloc(n * sizeof(double) * 4);\n double *b1 = a1 + n;\n double *c1 = b1 + n;\n double *d1 = c1 + n;\n#endif\n\n // Zero the data to prevent any chance of denormals.\n memset(a1,0,n * sizeof(double));\n memset(b1,0,n * sizeof(double));\n memset(c1,0,n * sizeof(double));\n memset(d1,0,n * sizeof(double));\n\n // Print the addresses\n cout << a1 << endl;\n cout << b1 << endl;\n cout << c1 << endl;\n cout << d1 << endl;\n\n clock_t start = clock();\n\n int c = 0;\n while (c++ < 10000){\n\n#if ONE_LOOP\n for(int j=0;j<n;j++){\n a1[j] += b1[j];\n c1[j] += d1[j];\n }\n#else\n for(int j=0;j<n;j++){\n a1[j] += b1[j];\n }\n for(int j=0;j<n;j++){\n c1[j] += d1[j];\n }\n#endif\n\n }\n\n clock_t end = clock();\n cout << \"seconds = \" << (double)(end - start) / CLOCKS_PER_SEC << endl;\n\n system(\"pause\");\n return 0;\n}\n#define ALLOCATE_SEPERATE\n#define ONE_LOOP\n00600020\n006D0020\n007A0020\n00870020\nseconds = 6.206\n\n#define ALLOCATE_SEPERATE\n//#define ONE_LOOP\n005E0020\n006B0020\n00780020\n00850020\nseconds = 2.116\n\n//#define ALLOCATE_SEPERATE\n#define ONE_LOOP\n00570020\n00633520\n006F6A20\n007B9F20\nseconds = 1.894\n\n//#define ALLOCATE_SEPERATE\n//#define ONE_LOOP\n008C0020\n00983520\n00A46A20\n00B09F20\nseconds = 1.993\n"}, {"idx": "webquery-test-1", "doc": "Why does changing 0.1f to 0 slow down performance by 10x?", "code": "00int main() {\n\n double start = omp_get_wtime();\n\n const float x[16]={1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,2.3,2.4,2.5,2.6};\n const float z[16]={1.123,1.234,1.345,156.467,1.578,1.689,1.790,1.812,1.923,2.034,2.145,2.256,2.367,2.478,2.589,2.690};\n float y[16];\n for(int i=0;i<16;i++)\n {\n y[i]=x[i];\n }\n for(int j=0;j<9000000;j++)\n {\n for(int i=0;i<16;i++)\n {\n y[i]*=x[i];\n y[i]/=z[i];\n#ifdef FLOATING\n y[i]=y[i]+0.1f;\n y[i]=y[i]-0.1f;\n#else\n y[i]=y[i]+0;\n y[i]=y[i]-0;\n#endif\n\n if (j > 10000)\n cout << y[i] << \" \";\n }\n if (j > 10000)\n cout << endl;\n }\n\n double end = omp_get_wtime();\n cout << end - start << endl;\n\n system(\"pause\");\n return 0;\n}\n#define FLOATING\n1.78814e-007 1.3411e-007 1.04308e-007 0 7.45058e-008 6.70552e-008 6.70552e-008 5.58794e-007 3.05474e-007 2.16067e-007 1.71363e-007 1.49012e-007 1.2666e-007 1.11759e-007 1.04308e-007 1.04308e-007\n1.78814e-007 1.3411e-007 1.04308e-007 0 7.45058e-008 6.70552e-008 6.70552e-008 5.58794e-007 3.05474e-007 2.16067e-007 1.71363e-007 1.49012e-007 1.2666e-007 1.11759e-007 1.04308e-007 1.04308e-007\n\n//#define FLOATING\n6.30584e-044 3.92364e-044 3.08286e-044 0 1.82169e-044 1.54143e-044 2.10195e-044 2.46842e-029 7.56701e-044 4.06377e-044 3.92364e-044 3.22299e-044 3.08286e-044 2.66247e-044 2.66247e-044 2.24208e-044\n6.30584e-044 3.92364e-044 3.08286e-044 0 1.82169e-044 1.54143e-044 2.10195e-044 2.45208e-029 7.56701e-044 4.06377e-044 3.92364e-044 3.22299e-044 3.08286e-044 2.66247e-044 2.66247e-044 2.24208e-044\n_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n0// Don't flush denormals to zero.\n0.1f: 0.564067\n0 : 26.7669\n\n// Flush denormals to zero.\n0.1f: 0.587117\n0 : 0.341406\n00"}, {"idx": "webquery-test-2", "doc": "Where and why do I have to put the \"template\" and \"typename\" keywords?", "code": "t * f;\nttt::xt::xt::xt::x * f;t::xt::xtypenametypenametypenametypenametypename// t::x is taken as non-type, but as an expression the following misses an\n// operator between the two names or a semicolon separating them.\nt::x f;\ntypenameboost::function< int() > f;\nboost::functionboost::functionnamespace boost { int function = 0; }\nint main() { \n int f = 0;\n boost::function< int() > f; \n}\nboost::functionboost::functionboost::functionboost::functionboost::functiontypenametypenametypenamet::template f<int>(); // call a function template\n::::::this->template f<int>(); // call a function template\nTTTT[N]T[N]T[N]T[N]T[N]T[N]T::xoperator +operator +operator +1 + N1 + Nf((T)0)f((T)0)f((T)0)typenametypenametemplate <typename T, typename Tail>\nstruct UnionNode : public Tail {\n // ...\n template<typename U> struct inUnion {\n typedef typename Tail::template inUnion<U> dummy;\n };\n // ...\n};\ntemplatetypename t::template iterator<int>::value_type v;\ntypenametypenametypenametypenametypename"}, {"idx": "webquery-test-3", "doc": "When should you use a class vs a struct in C++?", "code": "classclassstructstructstructstructpublicpublicpublicstructstructstructstruct"}, {"idx": "webquery-test-4", "doc": "How do I use extern to share variables between source files?", "code": "externexternexternexternfile3.hfile3.hfile3.hextern int global_variable; /* Declaration of the variable */\n#include \"file3.h\" /* Declaration made available here */\n#include \"prog1.h\" /* Function declarations */\n\n/* Variable defined here */\nint global_variable = 37; /* Definition checked against declaration */\n\nint increment(void) { return global_variable++; }\n#include \"file3.h\"\n#include \"prog1.h\"\n#include <stdio.h>\n\nvoid use_it(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n}\nprog1externexternexternextern void use_it(void);\nextern int increment(void);\n#include \"file3.h\"\n#include \"prog1.h\"\n#include <stdio.h>\n\nint main(void)\n{\n use_it();\n global_variable += 19;\n use_it();\n printf(\"Increment: %d\\n\", increment());\n return 0;\n}\nprog1prog1prog1prog1prog1prog1prog1.mkprog1.mkprog1.mk# Minimal makefile for prog1\n\nPROGRAM = prog1\nFILES.c = prog1.c file1.c file2.c\nFILES.h = prog1.h file3.h\nFILES.o = ${FILES.c:.c=.o}\n\nCC = gcc\nSFLAGS = -std=c11\nGFLAGS = -g\nOFLAGS = -O3\nWFLAG1 = -Wall\nWFLAG2 = -Wextra\nWFLAG3 = -Werror\nWFLAG4 = -Wstrict-prototypes\nWFLAG5 = -Wmissing-prototypes\nWFLAGS = ${WFLAG1} ${WFLAG2} ${WFLAG3} ${WFLAG4} ${WFLAG5}\nUFLAGS = # Set on command line only\n\nCFLAGS = ${SFLAGS} ${GFLAGS} ${OFLAGS} ${WFLAGS} ${UFLAGS}\nLDFLAGS =\nLDLIBS =\n\nall: ${PROGRAM}\n\n${PROGRAM}: ${FILES.o}\n ${CC} -o $@ ${CFLAGS} ${FILES.o} ${LDFLAGS} ${LDLIBS}\n\nprog1.o: ${FILES.h}\nfile1.o: ${FILES.h}\nfile2.o: ${FILES.h}\n\n# If it exists, prog1.dSYM is a directory on macOS\nDEBRIS = a.out core *~ *.dSYM\nRM_FR = rm -fr\n\nclean:\n ${RM_FR} ${FILES.o} ${PROGRAM} ${DEBRIS}\n\nexternexternexternextern#include \"prog2.h\"\n\nlong l; /* Do not do this in portable code */\n\nvoid inc(void) { l++; }\n#include \"prog2.h\"\n\nlong l; /* Do not do this in portable code */\n\nvoid dec(void) { l--; }\n#include \"prog2.h\"\n#include <stdio.h>\n\nlong l = 9; /* Do not do this in portable code */\n\nvoid put(void) { printf(\"l = %ld\\n\", l); }\nsizeofsizeoflllllll-fno-common-fno-commonprog2extern void dec(void);\nextern void put(void);\nextern void inc(void);\n#include \"prog2.h\"\n#include <stdio.h>\n\nint main(void)\n{\n inc();\n put();\n dec();\n put();\n dec();\n put();\n}\nprog2prog2prog2prog2prog2prog2int some_var; /* Do not do this in a header!!! */\nexternint some_var = 13; /* Only one source file in a program can use this */\nstatic int hidden_global = 3; /* Each source file gets its own copy */\nglobal_variablefile3.h#ifdef DEFINE_VARIABLES\n#define EXTERN /* nothing */\n#else\n#define EXTERN extern\n#endif /* DEFINE_VARIABLES */\n\nEXTERN int global_variable;\n#define DEFINE_VARIABLES\n#include \"file3a.h\" /* Variable defined - but not initialized */\n#include \"prog3.h\"\n\nint increment(void) { return global_variable++; }\n#include \"file3a.h\"\n#include \"prog3.h\"\n#include <stdio.h>\n\nvoid use_it(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n}\nprog3extern void use_it(void);\nextern int increment(void);\n#include \"file3a.h\"\n#include \"prog3.h\"\n#include <stdio.h>\n\nint main(void)\n{\n use_it();\n global_variable += 19;\n use_it();\n printf(\"Increment: %d\\n\", increment());\n return 0;\n}\nprog3prog3prog3prog3prog3prog3#ifdef DEFINE_VARIABLES\n#define EXTERN /* nothing */\n#define INITIALIZER(...) = __VA_ARGS__\n#else\n#define EXTERN extern\n#define INITIALIZER(...) /* nothing */\n#endif /* DEFINE_VARIABLES */\n\nEXTERN int global_variable INITIALIZER(37);\nEXTERN struct { int a; int b; } oddball_struct INITIALIZER({ 41, 43 });\n#if#if#define DEFINE_VARIABLES\n#include \"file3b.h\" /* Variables now defined and initialized */\n#include \"prog4.h\"\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\n#include \"file3b.h\"\n#include \"prog4.h\"\n#include <stdio.h>\n\nvoid use_them(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n oddball_struct.a += global_variable;\n oddball_struct.b -= global_variable / 2;\n}\nINITIALIZERINITIALIZERINITIALIZERfile3b.hfile3b.hprog4extern int increment(void);\nextern int oddball_value(void);\nextern void use_them(void);\n#include \"file3b.h\"\n#include \"prog4.h\"\n#include <stdio.h>\n\nint main(void)\n{\n use_them();\n global_variable += 19;\n use_them();\n printf(\"Increment: %d\\n\", increment());\n printf(\"Oddball: %d\\n\", oddball_value());\n return 0;\n}\nprog4prog4prog4prog4prog4prog4#ifndef FILE3B_H_INCLUDED\n#define FILE3B_H_INCLUDED\n\n...contents of header...\n\n#endif /* FILE3B_H_INCLUDED */\nfile4b.hfile4b.hfile4b.hfile4b.hfile4b.hfile4b.hfile4b.hfile4b.hfile4b.hfile3b.hexternal.hexternal.hexternal.hexternal.hexternal.hexternal.hexternal.hexternal.hexternal.hfile5c.cfile5c.cfile5c.c/*\n** This header must not contain header guards (like <assert.h> must not).\n** Each time it is invoked, it redefines the macros EXTERN, INITIALIZE\n** based on whether macro DEFINE_VARIABLES is currently defined.\n*/\n#undef EXTERN\n#undef INITIALIZE\n\n#ifdef DEFINE_VARIABLES\n#define EXTERN /* nothing */\n#define INITIALIZE(...) = __VA_ARGS__\n#else\n#define EXTERN extern\n#define INITIALIZE(...) /* nothing */\n#endif /* DEFINE_VARIABLES */\n#ifndef FILE1C_H_INCLUDED\n#define FILE1C_H_INCLUDED\n\nstruct oddball\n{\n int a;\n int b;\n};\n\nextern void use_them(void);\nextern int increment(void);\nextern int oddball_value(void);\n\n#endif /* FILE1C_H_INCLUDED */\n\n\n/* Standard prologue */\n#if defined(DEFINE_VARIABLES) && !defined(FILE2C_H_DEFINITIONS)\n#undef FILE2C_H_INCLUDED\n#endif\n\n#ifndef FILE2C_H_INCLUDED\n#define FILE2C_H_INCLUDED\n\n#include \"external.h\" /* Support macros EXTERN, INITIALIZE */\n#include \"file1c.h\" /* Type definition for struct oddball */\n\n#if !defined(DEFINE_VARIABLES) || !defined(FILE2C_H_DEFINITIONS)\n\n/* Global variable declarations / definitions */\nEXTERN int global_variable INITIALIZE(37);\nEXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });\n\n#endif /* !DEFINE_VARIABLES || !FILE2C_H_DEFINITIONS */\n\n/* Standard epilogue */\n#ifdef DEFINE_VARIABLES\n#define FILE2C_H_DEFINITIONS\n#endif /* DEFINE_VARIABLES */\n\n#endif /* FILE2C_H_INCLUDED */\n#define DEFINE_VARIABLES\n#include \"file2c.h\" /* Variables now defined and initialized */\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\n#include \"file2c.h\"\n#include <stdio.h>\n\nvoid use_them(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n oddball_struct.a += global_variable;\n oddball_struct.b -= global_variable / 2;\n}\n\n\n#include \"file2c.h\" /* Declare variables */\n\n#define DEFINE_VARIABLES\n#include \"file2c.h\" /* Variables now defined and initialized */\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\n\n#define DEFINE_VARIABLES\n#include \"file2c.h\" /* Variables now defined and initialized */\n\n#include \"file2c.h\" /* Declare variables */\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\nprog5prog5prog5#include \"file2c.h\"\n#include <stdio.h>\n\nint main(void)\n{\n use_them();\n global_variable += 19;\n use_them();\n printf(\"Increment: %d\\n\", increment());\n printf(\"Oddball: %d\\n\", oddball_value());\n return 0;\n}\nprog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5prog5file2c.hfile2c.hfile2c.hfile2c.h/* Standard prologue */\n#if defined(DEFINE_VARIABLES) && !defined(FILE2D_H_DEFINITIONS)\n#undef FILE2D_H_INCLUDED\n#endif\n\n#ifndef FILE2D_H_INCLUDED\n#define FILE2D_H_INCLUDED\n\n#include \"external.h\" /* Support macros EXTERN, INITIALIZE */\n#include \"file1c.h\" /* Type definition for struct oddball */\n\n#if !defined(DEFINE_VARIABLES) || !defined(FILE2D_H_DEFINITIONS)\n\n/* Global variable declarations / definitions */\nEXTERN int global_variable INITIALIZE(37);\nEXTERN struct oddball oddball_struct INITIALIZE({ 41, 43 });\n\n#endif /* !DEFINE_VARIABLES || !FILE2D_H_DEFINITIONS */\n\n/* Standard epilogue */\n#ifdef DEFINE_VARIABLES\n#define FILE2D_H_DEFINITIONS\n#undef DEFINE_VARIABLES\n#endif /* DEFINE_VARIABLES */\n\n#endif /* FILE2D_H_INCLUDED */\n#undef DEFINE_VARIABLES#undef DEFINE_VARIABLES#undef DEFINE_VARIABLES#define DEFINE_VARIABLES\n#include \"file2c.h\"\n#undef DEFINE_VARIABLES\nDEFINE_VARIABLES#define HEADER_DEFINING_VARIABLES \"file2c.h\"\n#include \"externdef.h\"\n/*\n** This header must not contain header guards (like <assert.h> must not).\n** Each time it is included, the macro HEADER_DEFINING_VARIABLES should\n** be defined with the name (in quotes - or possibly angle brackets) of\n** the header to be included that defines variables when the macro\n** DEFINE_VARIABLES is defined. See also: external.h (which uses\n** DEFINE_VARIABLES and defines macros EXTERN and INITIALIZE\n** appropriately).\n**\n** #define HEADER_DEFINING_VARIABLES \"file2c.h\"\n** #include \"externdef.h\"\n*/\n\n#if defined(HEADER_DEFINING_VARIABLES)\n#define DEFINE_VARIABLES\n#include HEADER_DEFINING_VARIABLES\n#undef DEFINE_VARIABLES\n#undef HEADER_DEFINING_VARIABLES\n#endif /* HEADER_DEFINING_VARIABLES */\n\nfile2d.hfile2d.hfile2d.h/* Declare variables */\n#include \"file2d.h\"\n\n/* Define variables */\n#define HEADER_DEFINING_VARIABLES \"file2d.h\"\n#include \"externdef.h\"\n\n/* Declare variables - again */\n#include \"file2d.h\"\n\n/* Define variables - again */\n#define HEADER_DEFINING_VARIABLES \"file2d.h\"\n#include \"externdef.h\"\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\n/* Standard prologue */\n#if defined(DEFINE_VARIABLES) && !defined(FILE8C_H_DEFINITIONS)\n#undef FILE8C_H_INCLUDED\n#endif\n\n#ifndef FILE8C_H_INCLUDED\n#define FILE8C_H_INCLUDED\n\n#include \"external.h\" /* Support macros EXTERN, INITIALIZE */\n#include \"file2d.h\" /* struct oddball */\n\n#if !defined(DEFINE_VARIABLES) || !defined(FILE8C_H_DEFINITIONS)\n\n/* Global variable declarations / definitions */\nEXTERN struct oddball another INITIALIZE({ 14, 34 });\n\n#endif /* !DEFINE_VARIABLES || !FILE8C_H_DEFINITIONS */\n\n/* Standard epilogue */\n#ifdef DEFINE_VARIABLES\n#define FILE8C_H_DEFINITIONS\n#endif /* DEFINE_VARIABLES */\n\n#endif /* FILE8C_H_INCLUDED */\n\n/* Define variables */\n#define HEADER_DEFINING_VARIABLES \"file2d.h\"\n#include \"externdef.h\"\n\n/* Define variables */\n#define HEADER_DEFINING_VARIABLES \"file8c.h\"\n#include \"externdef.h\"\n\nint increment(void) { return global_variable++; }\nint oddball_value(void) { return oddball_struct.a + oddball_struct.b; }\n\nprog8prog8#include \"file2d.h\"\n#include <stdio.h>\n\nint main(void)\n{\n use_them();\n global_variable += 19;\n use_them();\n printf(\"Increment: %d\\n\", increment());\n printf(\"Oddball: %d\\n\", oddball_value());\n return 0;\n}\n#include \"file2d.h\"\n#include <stdio.h>\n\nvoid use_them(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n oddball_struct.a += global_variable;\n oddball_struct.b -= global_variable / 2;\n}\n\nprog8prog8prog8prog8prog8prog8prog8prog8prog5.cprog5.cprog5.c"}, {"idx": "webquery-test-5", "doc": "What is the difference between g++ and gcc?", "code": "gccgcccc1cc1cc1g++g++g++"}, {"idx": "webquery-test-6", "doc": "Can I call a constructor from another constructor (do constructor chaining) in C++?", "code": "class Foo {\npublic: \n Foo(char x, int y) {}\n Foo(int y) : Foo('a', y) {}\n};\nclass Foo {\npublic:\n Foo(char x, int y=0); // combines two constructors (char) and (char, int)\n // ...\n};\nclass Foo {\npublic:\n Foo(char x, int y=0); // combines two constructors (char) and (char, int)\n // ...\n};\n"}, {"idx": "webquery-test-1", "doc": "Concatenating two std::vectors", "code": "vector1.insert( vector1.end(), vector2.begin(), vector2.end() );\n"}, {"idx": "webquery-test-2", "doc": "What is a \"cache-friendly\" code?", "code": "std::vectorstd::vectorstd::vectorstd::vector1 2\n3 4\n1 2 3 41 2 3 4MM[0][0] (memory) + M[0][1] (cached) + M[1][0] (memory) + M[1][1] (cached)\n= 1 + 2 + 3 + 4\n--> 2 cache hits, 2 memory accesses\nM[0][0] (memory) + M[1][0] (memory) + M[0][1] (memory) + M[1][1] (memory)\n= 1 + 3 + 2 + 4\n--> 0 cache hits, 4 memory accesses\nvirtual"}, {"idx": "webquery-test-3", "doc": "Meaning of 'const' last in a function declaration of a class?", "code": "constconstconstconstconstconst#include <iostream>\n\nclass MyClass\n{\nprivate:\n int counter;\npublic:\n void Foo()\n { \n std::cout << \"Foo\" << std::endl; \n }\n\n void Foo() const\n {\n std::cout << \"Foo const\" << std::endl;\n }\n\n};\n\nint main()\n{\n MyClass cc;\n const MyClass& ccc = cc;\n cc.Foo();\n ccc.Foo();\n}\nFoo\nFoo const\nconst void Foo()\n {\n counter++; //this works\n std::cout << \"Foo\" << std::endl; \n }\n\n void Foo() const\n {\n counter++; //this will not compile\n std::cout << \"Foo const\" << std::endl;\n }\nmutablemutable#include <iostream>\n\nclass MyClass\n{\nprivate:\n mutable int counter;\npublic:\n\n MyClass() : counter(0) {}\n\n void Foo()\n {\n counter++;\n std::cout << \"Foo\" << std::endl; \n }\n\n void Foo() const\n {\n counter++; // This works because counter is `mutable`\n std::cout << \"Foo const\" << std::endl;\n }\n\n int GetInvocations() const\n {\n return counter;\n }\n};\n\nint main(void)\n{\n MyClass cc;\n const MyClass& ccc = cc;\n cc.Foo();\n ccc.Foo();\n std::cout << \"Foo has been invoked \" << ccc.GetInvocations() << \" times\" << std::endl;\n}\nFoo\nFoo const\nFoo has been invoked 2 times\n"}, {"idx": "webquery-test-4", "doc": "Why isn't sizeof for a struct equal to the sum of sizeof of each member?", "code": "SIGBUSstruct X\n{\n short s; /* 2 bytes */\n /* 2 padding bytes */\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 3 padding bytes */\n};\n\nstruct Y\n{\n int i; /* 4 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n short s; /* 2 bytes */\n};\n\nstruct Z\n{\n int i; /* 4 bytes */\n short s; /* 2 bytes */\n char c; /* 1 byte */\n /* 1 padding byte */\n};\n\nconst int sizeX = sizeof(struct X); /* = 12 */\nconst int sizeY = sizeof(struct Y); /* = 8 */\nconst int sizeZ = sizeof(struct Z); /* = 8 */\nZ#pragma"}, {"idx": "webquery-test-5", "doc": "What are the rules for calling the base class constructor?", "code": "class SuperClass\n{\n public:\n\n SuperClass(int foo)\n {\n // do something with foo\n }\n};\n\nclass SubClass : public SuperClass\n{\n public:\n\n SubClass(int foo, int bar)\n : SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.\n {\n // do something with bar\n }\n};\n"}, {"idx": "webquery-test-6", "doc": "What is a segmentation fault?", "code": "int *p = NULL;\n*p = 1;\nchar *str = \"Foo\"; // Compiler marks the constant string as read-only\n*str = 'b'; // Which means this is illegal and results in a segfault\nchar *p = NULL;\n{\n char c;\n p = &c;\n}\n// Now p is dangling\nppp"}, {"idx": "webquery-test-7", "doc": "Appending a vector to a vector", "code": "a.insert(a.end(), b.begin(), b.end());\na.insert(std::end(a), std::begin(b), std::end(b));\nbusing std::begin, std::end;\na.insert(end(a), begin(b), end(b));\n"}, {"idx": "webquery-test-8", "doc": "Why is my program slow when looping over exactly 8192 elements?", "code": "for(i=1;i<SIZE-1;i++) \n for(j=1;j<SIZE-1;j++) {\n res[j][i]=0;\n for(k=-1;k<2;k++) \n for(l=-1;l<2;l++) \n res[j][i] += img[j+l][i+k];\n res[j][i] /= 9;\n}\nfor(i=1;i<SIZE-1;i++) {\n for(j=1;j<SIZE-1;j++) {\n res[j][i]=0;\n res[j][i] += img[j-1][i-1];\n res[j][i] += img[j ][i-1];\n res[j][i] += img[j+1][i-1];\n res[j][i] += img[j-1][i ];\n res[j][i] += img[j ][i ];\n res[j][i] += img[j+1][i ];\n res[j][i] += img[j-1][i+1];\n res[j][i] += img[j ][i+1];\n res[j][i] += img[j+1][i+1];\n res[j][i] /= 9;\n }\n}\nfor(j=1;j<SIZE-1;j++) {\n for(i=1;i<SIZE-1;i++) {\n res[j][i]=0;\n res[j][i] += img[j-1][i-1];\n res[j][i] += img[j ][i-1];\n res[j][i] += img[j+1][i-1];\n res[j][i] += img[j-1][i ];\n res[j][i] += img[j ][i ];\n res[j][i] += img[j+1][i ];\n res[j][i] += img[j-1][i+1];\n res[j][i] += img[j ][i+1];\n res[j][i] += img[j+1][i+1];\n res[j][i] /= 9;\n }\n}\n8191: 1.499 seconds\n8192: 2.122 seconds\n8193: 1.582 seconds\n8191: 0.376 seconds\n8192: 0.357 seconds\n8193: 0.351 seconds\n"}, {"idx": "webquery-test-1", "doc": "Difference of keywords 'typename' and 'class' in templates?", "code": "typenametypenametemplate<class T>\nclass Foo\n{\n};\ntemplate<typename T>\nclass Foo\n{\n};\ntypenametypenametypenametypenametemplate<typename param_t>\nclass Foo\n{\n typedef typename param_t::baz sub_t;\n};\ntemplate < template < typename, typename > class Container, typename Type >\nclassclassclasstemplate class Foo<int>;\n"}, {"idx": "webquery-test-2", "doc": "What is the easiest way to initialize a std::vector with hardcoded elements?", "code": "std::vector<int> v = {1, 2, 3, 4};\n#include <boost/assign/list_of.hpp>\n...\nstd::vector<int> v = boost::assign::list_of(1)(2)(3)(4);\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign;\n...\nstd::vector<int> v;\nv += 1, 2, 3, 4;\nlist_oflist_of"}, {"idx": "webquery-test-3", "doc": "How do I achieve the theoretical maximum of 4 FLOPs per cycle?", "code": "#include <emmintrin.h>\n#include <omp.h>\n#include <iostream>\nusing namespace std;\n\ntypedef unsigned long long uint64;\n\ndouble test_dp_mac_SSE(double x,double y,uint64 iterations){\n register __m128d r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,rA,rB,rC,rD,rE,rF;\n\n // Generate starting data.\n r0 = _mm_set1_pd(x);\n r1 = _mm_set1_pd(y);\n\n r8 = _mm_set1_pd(-0.0);\n\n r2 = _mm_xor_pd(r0,r8);\n r3 = _mm_or_pd(r0,r8);\n r4 = _mm_andnot_pd(r8,r0);\n r5 = _mm_mul_pd(r1,_mm_set1_pd(0.37796447300922722721));\n r6 = _mm_mul_pd(r1,_mm_set1_pd(0.24253562503633297352));\n r7 = _mm_mul_pd(r1,_mm_set1_pd(4.1231056256176605498));\n r8 = _mm_add_pd(r0,_mm_set1_pd(0.37796447300922722721));\n r9 = _mm_add_pd(r1,_mm_set1_pd(0.24253562503633297352));\n rA = _mm_sub_pd(r0,_mm_set1_pd(4.1231056256176605498));\n rB = _mm_sub_pd(r1,_mm_set1_pd(4.1231056256176605498));\n\n rC = _mm_set1_pd(1.4142135623730950488);\n rD = _mm_set1_pd(1.7320508075688772935);\n rE = _mm_set1_pd(0.57735026918962576451);\n rF = _mm_set1_pd(0.70710678118654752440);\n\n uint64 iMASK = 0x800fffffffffffffull;\n __m128d MASK = _mm_set1_pd(*(double*)&iMASK);\n __m128d vONE = _mm_set1_pd(1.0);\n\n uint64 c = 0;\n while (c < iterations){\n size_t i = 0;\n while (i < 1000){\n // Here's the meat - the part that really matters.\n\n r0 = _mm_mul_pd(r0,rC);\n r1 = _mm_add_pd(r1,rD);\n r2 = _mm_mul_pd(r2,rE);\n r3 = _mm_sub_pd(r3,rF);\n r4 = _mm_mul_pd(r4,rC);\n r5 = _mm_add_pd(r5,rD);\n r6 = _mm_mul_pd(r6,rE);\n r7 = _mm_sub_pd(r7,rF);\n r8 = _mm_mul_pd(r8,rC);\n r9 = _mm_add_pd(r9,rD);\n rA = _mm_mul_pd(rA,rE);\n rB = _mm_sub_pd(rB,rF);\n\n r0 = _mm_add_pd(r0,rF);\n r1 = _mm_mul_pd(r1,rE);\n r2 = _mm_sub_pd(r2,rD);\n r3 = _mm_mul_pd(r3,rC);\n r4 = _mm_add_pd(r4,rF);\n r5 = _mm_mul_pd(r5,rE);\n r6 = _mm_sub_pd(r6,rD);\n r7 = _mm_mul_pd(r7,rC);\n r8 = _mm_add_pd(r8,rF);\n r9 = _mm_mul_pd(r9,rE);\n rA = _mm_sub_pd(rA,rD);\n rB = _mm_mul_pd(rB,rC);\n\n r0 = _mm_mul_pd(r0,rC);\n r1 = _mm_add_pd(r1,rD);\n r2 = _mm_mul_pd(r2,rE);\n r3 = _mm_sub_pd(r3,rF);\n r4 = _mm_mul_pd(r4,rC);\n r5 = _mm_add_pd(r5,rD);\n r6 = _mm_mul_pd(r6,rE);\n r7 = _mm_sub_pd(r7,rF);\n r8 = _mm_mul_pd(r8,rC);\n r9 = _mm_add_pd(r9,rD);\n rA = _mm_mul_pd(rA,rE);\n rB = _mm_sub_pd(rB,rF);\n\n r0 = _mm_add_pd(r0,rF);\n r1 = _mm_mul_pd(r1,rE);\n r2 = _mm_sub_pd(r2,rD);\n r3 = _mm_mul_pd(r3,rC);\n r4 = _mm_add_pd(r4,rF);\n r5 = _mm_mul_pd(r5,rE);\n r6 = _mm_sub_pd(r6,rD);\n r7 = _mm_mul_pd(r7,rC);\n r8 = _mm_add_pd(r8,rF);\n r9 = _mm_mul_pd(r9,rE);\n rA = _mm_sub_pd(rA,rD);\n rB = _mm_mul_pd(rB,rC);\n\n i++;\n }\n\n // Need to renormalize to prevent denormal/overflow.\n r0 = _mm_and_pd(r0,MASK);\n r1 = _mm_and_pd(r1,MASK);\n r2 = _mm_and_pd(r2,MASK);\n r3 = _mm_and_pd(r3,MASK);\n r4 = _mm_and_pd(r4,MASK);\n r5 = _mm_and_pd(r5,MASK);\n r6 = _mm_and_pd(r6,MASK);\n r7 = _mm_and_pd(r7,MASK);\n r8 = _mm_and_pd(r8,MASK);\n r9 = _mm_and_pd(r9,MASK);\n rA = _mm_and_pd(rA,MASK);\n rB = _mm_and_pd(rB,MASK);\n r0 = _mm_or_pd(r0,vONE);\n r1 = _mm_or_pd(r1,vONE);\n r2 = _mm_or_pd(r2,vONE);\n r3 = _mm_or_pd(r3,vONE);\n r4 = _mm_or_pd(r4,vONE);\n r5 = _mm_or_pd(r5,vONE);\n r6 = _mm_or_pd(r6,vONE);\n r7 = _mm_or_pd(r7,vONE);\n r8 = _mm_or_pd(r8,vONE);\n r9 = _mm_or_pd(r9,vONE);\n rA = _mm_or_pd(rA,vONE);\n rB = _mm_or_pd(rB,vONE);\n\n c++;\n }\n\n r0 = _mm_add_pd(r0,r1);\n r2 = _mm_add_pd(r2,r3);\n r4 = _mm_add_pd(r4,r5);\n r6 = _mm_add_pd(r6,r7);\n r8 = _mm_add_pd(r8,r9);\n rA = _mm_add_pd(rA,rB);\n\n r0 = _mm_add_pd(r0,r2);\n r4 = _mm_add_pd(r4,r6);\n r8 = _mm_add_pd(r8,rA);\n\n r0 = _mm_add_pd(r0,r4);\n r0 = _mm_add_pd(r0,r8);\n\n\n // Prevent Dead Code Elimination\n double out = 0;\n __m128d temp = r0;\n out += ((double*)&temp)[0];\n out += ((double*)&temp)[1];\n\n return out;\n}\n\nvoid test_dp_mac_SSE(int tds,uint64 iterations){\n\n double *sum = (double*)malloc(tds * sizeof(double));\n double start = omp_get_wtime();\n\n#pragma omp parallel num_threads(tds)\n {\n double ret = test_dp_mac_SSE(1.1,2.1,iterations);\n sum[omp_get_thread_num()] = ret;\n }\n\n double secs = omp_get_wtime() - start;\n uint64 ops = 48 * 1000 * iterations * tds * 2;\n cout << \"Seconds = \" << secs << endl;\n cout << \"FP Ops = \" << ops << endl;\n cout << \"FLOPs = \" << ops / secs << endl;\n\n double out = 0;\n int c = 0;\n while (c < tds){\n out += sum[c++];\n }\n\n cout << \"sum = \" << out << endl;\n cout << endl;\n\n free(sum);\n}\n\nint main(){\n // (threads, iterations)\n test_dp_mac_SSE(8,10000000);\n\n system(\"pause\");\n}\nSeconds = 55.5104\nFP Ops = 960000000000\nFLOPs = 1.7294e+010\nsum = 2.22652\nSeconds = 117.202\nFP Ops = 7680000000000\nFLOPs = 6.55279e+010\nsum = 17.8122\n#include <immintrin.h>\n#include <omp.h>\n#include <iostream>\nusing namespace std;\n\ntypedef unsigned long long uint64;\n\ndouble test_dp_mac_AVX(double x,double y,uint64 iterations){\n register __m256d r0,r1,r2,r3,r4,r5,r6,r7,r8,r9,rA,rB,rC,rD,rE,rF;\n\n // Generate starting data.\n r0 = _mm256_set1_pd(x);\n r1 = _mm256_set1_pd(y);\n\n r8 = _mm256_set1_pd(-0.0);\n\n r2 = _mm256_xor_pd(r0,r8);\n r3 = _mm256_or_pd(r0,r8);\n r4 = _mm256_andnot_pd(r8,r0);\n r5 = _mm256_mul_pd(r1,_mm256_set1_pd(0.37796447300922722721));\n r6 = _mm256_mul_pd(r1,_mm256_set1_pd(0.24253562503633297352));\n r7 = _mm256_mul_pd(r1,_mm256_set1_pd(4.1231056256176605498));\n r8 = _mm256_add_pd(r0,_mm256_set1_pd(0.37796447300922722721));\n r9 = _mm256_add_pd(r1,_mm256_set1_pd(0.24253562503633297352));\n rA = _mm256_sub_pd(r0,_mm256_set1_pd(4.1231056256176605498));\n rB = _mm256_sub_pd(r1,_mm256_set1_pd(4.1231056256176605498));\n\n rC = _mm256_set1_pd(1.4142135623730950488);\n rD = _mm256_set1_pd(1.7320508075688772935);\n rE = _mm256_set1_pd(0.57735026918962576451);\n rF = _mm256_set1_pd(0.70710678118654752440);\n\n uint64 iMASK = 0x800fffffffffffffull;\n __m256d MASK = _mm256_set1_pd(*(double*)&iMASK);\n __m256d vONE = _mm256_set1_pd(1.0);\n\n uint64 c = 0;\n while (c < iterations){\n size_t i = 0;\n while (i < 1000){\n // Here's the meat - the part that really matters.\n\n r0 = _mm256_mul_pd(r0,rC);\n r1 = _mm256_add_pd(r1,rD);\n r2 = _mm256_mul_pd(r2,rE);\n r3 = _mm256_sub_pd(r3,rF);\n r4 = _mm256_mul_pd(r4,rC);\n r5 = _mm256_add_pd(r5,rD);\n r6 = _mm256_mul_pd(r6,rE);\n r7 = _mm256_sub_pd(r7,rF);\n r8 = _mm256_mul_pd(r8,rC);\n r9 = _mm256_add_pd(r9,rD);\n rA = _mm256_mul_pd(rA,rE);\n rB = _mm256_sub_pd(rB,rF);\n\n r0 = _mm256_add_pd(r0,rF);\n r1 = _mm256_mul_pd(r1,rE);\n r2 = _mm256_sub_pd(r2,rD);\n r3 = _mm256_mul_pd(r3,rC);\n r4 = _mm256_add_pd(r4,rF);\n r5 = _mm256_mul_pd(r5,rE);\n r6 = _mm256_sub_pd(r6,rD);\n r7 = _mm256_mul_pd(r7,rC);\n r8 = _mm256_add_pd(r8,rF);\n r9 = _mm256_mul_pd(r9,rE);\n rA = _mm256_sub_pd(rA,rD);\n rB = _mm256_mul_pd(rB,rC);\n\n r0 = _mm256_mul_pd(r0,rC);\n r1 = _mm256_add_pd(r1,rD);\n r2 = _mm256_mul_pd(r2,rE);\n r3 = _mm256_sub_pd(r3,rF);\n r4 = _mm256_mul_pd(r4,rC);\n r5 = _mm256_add_pd(r5,rD);\n r6 = _mm256_mul_pd(r6,rE);\n r7 = _mm256_sub_pd(r7,rF);\n r8 = _mm256_mul_pd(r8,rC);\n r9 = _mm256_add_pd(r9,rD);\n rA = _mm256_mul_pd(rA,rE);\n rB = _mm256_sub_pd(rB,rF);\n\n r0 = _mm256_add_pd(r0,rF);\n r1 = _mm256_mul_pd(r1,rE);\n r2 = _mm256_sub_pd(r2,rD);\n r3 = _mm256_mul_pd(r3,rC);\n r4 = _mm256_add_pd(r4,rF);\n r5 = _mm256_mul_pd(r5,rE);\n r6 = _mm256_sub_pd(r6,rD);\n r7 = _mm256_mul_pd(r7,rC);\n r8 = _mm256_add_pd(r8,rF);\n r9 = _mm256_mul_pd(r9,rE);\n rA = _mm256_sub_pd(rA,rD);\n rB = _mm256_mul_pd(rB,rC);\n\n i++;\n }\n\n // Need to renormalize to prevent denormal/overflow.\n r0 = _mm256_and_pd(r0,MASK);\n r1 = _mm256_and_pd(r1,MASK);\n r2 = _mm256_and_pd(r2,MASK);\n r3 = _mm256_and_pd(r3,MASK);\n r4 = _mm256_and_pd(r4,MASK);\n r5 = _mm256_and_pd(r5,MASK);\n r6 = _mm256_and_pd(r6,MASK);\n r7 = _mm256_and_pd(r7,MASK);\n r8 = _mm256_and_pd(r8,MASK);\n r9 = _mm256_and_pd(r9,MASK);\n rA = _mm256_and_pd(rA,MASK);\n rB = _mm256_and_pd(rB,MASK);\n r0 = _mm256_or_pd(r0,vONE);\n r1 = _mm256_or_pd(r1,vONE);\n r2 = _mm256_or_pd(r2,vONE);\n r3 = _mm256_or_pd(r3,vONE);\n r4 = _mm256_or_pd(r4,vONE);\n r5 = _mm256_or_pd(r5,vONE);\n r6 = _mm256_or_pd(r6,vONE);\n r7 = _mm256_or_pd(r7,vONE);\n r8 = _mm256_or_pd(r8,vONE);\n r9 = _mm256_or_pd(r9,vONE);\n rA = _mm256_or_pd(rA,vONE);\n rB = _mm256_or_pd(rB,vONE);\n\n c++;\n }\n\n r0 = _mm256_add_pd(r0,r1);\n r2 = _mm256_add_pd(r2,r3);\n r4 = _mm256_add_pd(r4,r5);\n r6 = _mm256_add_pd(r6,r7);\n r8 = _mm256_add_pd(r8,r9);\n rA = _mm256_add_pd(rA,rB);\n\n r0 = _mm256_add_pd(r0,r2);\n r4 = _mm256_add_pd(r4,r6);\n r8 = _mm256_add_pd(r8,rA);\n\n r0 = _mm256_add_pd(r0,r4);\n r0 = _mm256_add_pd(r0,r8);\n\n // Prevent Dead Code Elimination\n double out = 0;\n __m256d temp = r0;\n out += ((double*)&temp)[0];\n out += ((double*)&temp)[1];\n out += ((double*)&temp)[2];\n out += ((double*)&temp)[3];\n\n return out;\n}\n\nvoid test_dp_mac_AVX(int tds,uint64 iterations){\n\n double *sum = (double*)malloc(tds * sizeof(double));\n double start = omp_get_wtime();\n\n#pragma omp parallel num_threads(tds)\n {\n double ret = test_dp_mac_AVX(1.1,2.1,iterations);\n sum[omp_get_thread_num()] = ret;\n }\n\n double secs = omp_get_wtime() - start;\n uint64 ops = 48 * 1000 * iterations * tds * 4;\n cout << \"Seconds = \" << secs << endl;\n cout << \"FP Ops = \" << ops << endl;\n cout << \"FLOPs = \" << ops / secs << endl;\n\n double out = 0;\n int c = 0;\n while (c < tds){\n out += sum[c++];\n }\n\n cout << \"sum = \" << out << endl;\n cout << endl;\n\n free(sum);\n}\n\nint main(){\n // (threads, iterations)\n test_dp_mac_AVX(8,10000000);\n\n system(\"pause\");\n}\nSeconds = 57.4679\nFP Ops = 1920000000000\nFLOPs = 3.34099e+010\nsum = 4.45305\nSeconds = 111.119\nFP Ops = 15360000000000\nFLOPs = 1.3823e+011\nsum = 35.6244\nSeconds = 72.1116\nFP Ops = 960000000000\nFLOPs = 1.33127e+010\nsum = 2.22652\nSeconds = 149.576\nFP Ops = 7680000000000\nFLOPs = 5.13452e+010\nsum = 17.8122\nSeconds = 78.3357\nFP Ops = 960000000000\nFLOPs = 1.22549e+10\nsum = 2.22652\nSeconds = 78.4733\nFP Ops = 7680000000000\nFLOPs = 9.78676e+10\nsum = 17.8122\n"}, {"idx": "webquery-test-4", "doc": "How to automatically generate a stacktrace when my program crashes", "code": "execinfo.hSIGSEGVSIGSEGVSIGSEGV#include <stdio.h>\n#include <execinfo.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n\nvoid handler(int sig) {\n void *array[10];\n size_t size;\n\n // get void*'s for all entries on the stack\n size = backtrace(array, 10);\n\n // print out all the frames to stderr\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n exit(1);\n}\n\nvoid baz() {\n int *foo = (int*)-1; // make a bad pointer\n printf(\"%d\\n\", *foo); // causes segfault\n}\n\nvoid bar() { baz(); }\nvoid foo() { bar(); }\n\n\nint main(int argc, char **argv) {\n signal(SIGSEGV, handler); // install our handler\n foo(); // this will call foo, bar, and baz. baz segfaults.\n}\n-g -rdynamic$ gcc -g -rdynamic ./test.c -o test\n$ ./test\nError: signal 11:\n./test(handler+0x19)[0x400911]\n/lib64/tls/libc.so.6[0x3a9b92e380]\n./test(baz+0x14)[0x400962]\n./test(bar+0xe)[0x400983]\n./test(foo+0xe)[0x400993]\n./test(main+0x28)[0x4009bd]\n/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]\n./test[0x40086a]\nmainmainmainmainmain"}, {"idx": "webquery-test-1", "doc": "Why does C++ compilation take so long?", "code": "List<T>List<T>List<T>"}, {"idx": "webquery-test-2", "doc": "How to initialize private static members in C++?", "code": "class foo\n{\n private:\n static int i;\n};\nint foo::i = 0;\nstatic int iboolboolboolboolboolboolboolboolboolboolclass foo\n{\n private:\n static int const i = 42;\n};\n"}, {"idx": "webquery-test-3", "doc": "Iterator invalidation rules for C++ containers", "code": "vectorvectorvector[multi]{set,map}stackstackstackvectorvectorvector[multi]{set,map}stackstackstackvectorvectorvector"}, {"idx": "webquery-test-4", "doc": "Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?", "code": "mutableint x = 0;\nauto f1 = [=]() mutable {x = 42;}; // OK\nauto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda\n"}, {"idx": "webquery-test-5", "doc": "usr/bin/ld: cannot find -l<nameOfTheLibrary>", "code": "/usr/bin/ld: cannot find -lzlib\nLD_DEBUG=all make\nld --help\nld -lzlib --verbose\n==================================================\nattempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed\nattempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed\nattempt to open /usr/local/lib64/libzlib.so failed\nattempt to open /usr/local/lib64/libzlib.a failed\nattempt to open /lib64/libzlib.so failed\nattempt to open /lib64/libzlib.a failed\nattempt to open /usr/lib64/libzlib.so failed\nattempt to open /usr/lib64/libzlib.a failed\nattempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed\nattempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed\nattempt to open /usr/local/lib/libzlib.so failed\nattempt to open /usr/local/lib/libzlib.a failed\nattempt to open /lib/libzlib.so failed\nattempt to open /lib/libzlib.a failed\nattempt to open /usr/lib/libzlib.so failed\nattempt to open /usr/lib/libzlib.a failed\n/usr/bin/ld.bfd.real: cannot find -lzlib\nsudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so\n"}, {"idx": "webquery-test-6", "doc": "How to replace all occurrences of a character in string?", "code": "std::stringstd::stringstd::string#include <algorithm>\n#include <string>\n\nvoid some_func() {\n std::string s = \"example string\";\n std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'\n}\n"}, {"idx": "webquery-test-7", "doc": "Calling C/C++ from Python?", "code": "#include <iostream>\n\nclass Foo{\n public:\n void bar(){\n std::cout << \"Hello\" << std::endl;\n }\n};\nextern \"C\" {\n Foo* Foo_new(){ return new Foo(); }\n void Foo_bar(Foo* foo){ foo->bar(); }\n}\ng++ -c -fPIC foo.cpp -o foo.o\ng++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o\nfrom ctypes import cdll\nlib = cdll.LoadLibrary('./libfoo.so')\n\nclass Foo(object):\n def __init__(self):\n self.obj = lib.Foo_new()\n\n def bar(self):\n lib.Foo_bar(self.obj)\nf = Foo()\nf.bar() #and you will see \"Hello\" on the screen\n"}, {"idx": "webquery-test-8", "doc": "How to find if a given key exists in a C++ std::map", "code": "map::findmap::findif (m.find(\"f\") == m.end()) {\n // not found\n} else {\n // found\n}\n"}, {"idx": "webquery-test-9", "doc": "How do I list the symbols in a .so file", "code": "nmnm -gD yourLib.so\nnm -gDC yourLib.so\nobjdumpobjdump$ objdump -TC libz.so\n\nlibz.so: file format elf64-x86-64\n\nDYNAMIC SYMBOL TABLE:\n0000000000002010 l d .init 0000000000000000 .init\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location\n0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable\nreadelf$ readelf -Ws libz.so\nSymbol table '.dynsym' contains 112 entries:\n Num: Value Size Type Bind Vis Ndx Name\n 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND\n 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10\n 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)\n 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)\n 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable\n"}, {"idx": "webquery-test-1", "doc": "How do I get the index of an iterator of an std::vector?", "code": "it - vec.begin()itit"}, {"idx": "webquery-test-2", "doc": "error: request for member '..' in '..' which is of non-class type", "code": "Foo foo2();\nFoo foo2;\nFoo foo2()\nFoo foo2Foo foo2"}, {"idx": "webquery-test-3", "doc": "What is an unsigned char?", "code": "charcharcharchar'a''a''a''a'signed charsigned charsizeof (char)sizeof (char)sizeof (char)sizeof (char)"}, {"idx": "webquery-test-4", "doc": "When to use extern in C++", "code": "extern int x;extern int x;extern int x;extern int x;extern int x;extern int x;#ifndef HEADER_H\n#define HEADER_H\n\n// any source file that includes this will be able to use \"global_x\"\nextern int global_x;\n\nvoid print_global_x();\n\n#endif\n#include \"header.h\"\n\n// since global_x still needs to be defined somewhere,\n// we define it (for example) in this source file\nint global_x;\n\nint main()\n{\n //set global_x here:\n global_x = 5;\n\n print_global_x();\n}\n#include <iostream>\n#include \"header.h\"\n\nvoid print_global_x()\n{\n //print global_x here:\n std::cout << global_x << std::endl;\n}\n"}, {"idx": "webquery-test-5", "doc": "Initializing a static std::map<int, int> in C++", "code": "#include <map>\nusing namespace std;\n\nmap<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};\n#include <map>\n#include \"boost/assign.hpp\"\nusing namespace std;\nusing namespace boost::assign;\n\nmap<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');\n"}, {"idx": "webquery-test-6", "doc": "error: passing xxx as 'this' argument of xxx discards qualifiers", "code": "std::setstd::setstd::setstd::setstd::setint getId() const {\n return id;\n}\nstring getName() const {\n return name;\n}\ngetId()getId()void f(const StudentT & s)\n{\n cout << s.getId(); //now okay, but error with your versions\n cout << s.getName(); //now okay, but error with your versions\n}\noperator<inline bool operator< (const StudentT & s1, const StudentT & s2)\n{\n return s1.getId() < s2.getId();\n}\nconst"}, {"idx": "webquery-test-7", "doc": "enum to string in modern C++11 / C++14 / C++17 and future C++20", "code": "ENUM(Channel, char, Red = 1, Green, Blue)\n\n// \"Same as\":\n// enum class Channel : char { Red = 1, Green, Blue };\nChannel c = Channel::_from_string(\"Green\"); // Channel::Green (2)\nc._to_string(); // string \"Green\"\n\nfor (Channel c : Channel::_values())\n std::cout << c << std::endl;\n\n// And so on...\nconstexpr###structstructstruct Channel {\n enum _enum : char { __VA_ARGS__ };\n constexpr static const Channel _values[] = { __VA_ARGS__ };\n constexpr static const char * const _names[] = { #__VA_ARGS__ };\n\n static const char* _to_string(Channel v) { /* easy */ }\n constexpr static Channel _from_string(const char *s) { /* easy */ }\n};\n{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}{Red = 1, Green, Blue}#include <cstddef> // For size_t.\n#include <cstring> // For strcspn, strncpy.\n#include <stdexcept> // For runtime_error.\n\n\n\n// A \"typical\" mapping macro. MAP(macro, a, b, c, ...) expands to\n// macro(a) macro(b) macro(c) ...\n// The helper macro COUNT(a, b, c, ...) expands to the number of\n// arguments, and IDENTITY(x) is needed to control the order of\n// expansion of __VA_ARGS__ on Visual C++ compilers.\n#define MAP(macro, ...) \\\n IDENTITY( \\\n APPLY(CHOOSE_MAP_START, COUNT(__VA_ARGS__)) \\\n (macro, __VA_ARGS__))\n\n#define CHOOSE_MAP_START(count) MAP ## count\n\n#define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))\n\n#define IDENTITY(x) x\n\n#define MAP1(m, x) m(x)\n#define MAP2(m, x, ...) m(x) IDENTITY(MAP1(m, __VA_ARGS__))\n#define MAP3(m, x, ...) m(x) IDENTITY(MAP2(m, __VA_ARGS__))\n#define MAP4(m, x, ...) m(x) IDENTITY(MAP3(m, __VA_ARGS__))\n#define MAP5(m, x, ...) m(x) IDENTITY(MAP4(m, __VA_ARGS__))\n#define MAP6(m, x, ...) m(x) IDENTITY(MAP5(m, __VA_ARGS__))\n#define MAP7(m, x, ...) m(x) IDENTITY(MAP6(m, __VA_ARGS__))\n#define MAP8(m, x, ...) m(x) IDENTITY(MAP7(m, __VA_ARGS__))\n\n#define EVALUATE_COUNT(_1, _2, _3, _4, _5, _6, _7, _8, count, ...) \\\n count\n\n#define COUNT(...) \\\n IDENTITY(EVALUATE_COUNT(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1))\n\n\n\n// The type \"T\" mentioned above that drops assignment operations.\ntemplate <typename U>\nstruct ignore_assign {\n constexpr explicit ignore_assign(U value) : _value(value) { }\n constexpr operator U() const { return _value; }\n\n constexpr const ignore_assign& operator =(int dummy) const\n { return *this; }\n\n U _value;\n};\n\n\n\n// Prepends \"(ignore_assign<_underlying>)\" to each argument.\n#define IGNORE_ASSIGN_SINGLE(e) (ignore_assign<_underlying>)e,\n#define IGNORE_ASSIGN(...) \\\n IDENTITY(MAP(IGNORE_ASSIGN_SINGLE, __VA_ARGS__))\n\n// Stringizes each argument.\n#define STRINGIZE_SINGLE(e) #e,\n#define STRINGIZE(...) IDENTITY(MAP(STRINGIZE_SINGLE, __VA_ARGS__))\n\n\n\n// Some helpers needed for _from_string.\nconstexpr const char terminators[] = \" =\\t\\r\\n\";\n\n// The size of terminators includes the implicit '\\0'.\nconstexpr bool is_terminator(char c, size_t index = 0)\n{\n return\n index >= sizeof(terminators) ? false :\n c == terminators[index] ? true :\n is_terminator(c, index + 1);\n}\n\nconstexpr bool matches_untrimmed(const char *untrimmed, const char *s,\n size_t index = 0)\n{\n return\n is_terminator(untrimmed[index]) ? s[index] == '\\0' :\n s[index] != untrimmed[index] ? false :\n matches_untrimmed(untrimmed, s, index + 1);\n}\n\n\n\n// The macro proper.\n//\n// There are several \"simplifications\" in this implementation, for the\n// sake of brevity. First, we have only one viable option for declaring\n// constexpr arrays: at namespace scope. This probably should be done\n// two namespaces deep: one namespace that is likely to be unique for\n// our little enum \"library\", then inside it a namespace whose name is\n// based on the name of the enum to avoid collisions with other enums.\n// I am using only one level of nesting.\n//\n// Declaring constexpr arrays inside the struct is not viable because\n// they will need out-of-line definitions, which will result in\n// duplicate symbols when linking. This can be solved with weak\n// symbols, but that is compiler- and system-specific. It is not\n// possible to declare constexpr arrays as static variables in\n// constexpr functions due to the restrictions on such functions.\n//\n// Note that this prevents the use of this macro anywhere except at\n// namespace scope. Ironically, the C++98 version of this, which can\n// declare static arrays inside static member functions, is actually\n// more flexible in this regard. It is shown in the CodeProject\n// article.\n//\n// Second, for compilation performance reasons, it is best to separate\n// the macro into a \"parametric\" portion, and the portion that depends\n// on knowing __VA_ARGS__, and factor the former out into a template.\n//\n// Third, this code uses a default parameter in _from_string that may\n// be better not exposed in the public interface.\n\n#define ENUM(EnumName, Underlying, ...) \\\nnamespace data_ ## EnumName { \\\n using _underlying = Underlying; \\\n enum { __VA_ARGS__ }; \\\n \\\n constexpr const size_t _size = \\\n IDENTITY(COUNT(__VA_ARGS__)); \\\n \\\n constexpr const _underlying _values[] = \\\n { IDENTITY(IGNORE_ASSIGN(__VA_ARGS__)) }; \\\n \\\n constexpr const char * const _raw_names[] = \\\n { IDENTITY(STRINGIZE(__VA_ARGS__)) }; \\\n} \\\n \\\nstruct EnumName { \\\n using _underlying = Underlying; \\\n enum _enum : _underlying { __VA_ARGS__ }; \\\n \\\n const char * _to_string() const \\\n { \\\n for (size_t index = 0; index < data_ ## EnumName::_size; \\\n ++index) { \\\n \\\n if (data_ ## EnumName::_values[index] == _value) \\\n return _trimmed_names()[index]; \\\n } \\\n \\\n throw std::runtime_error(\"invalid value\"); \\\n } \\\n \\\n constexpr static EnumName _from_string(const char *s, \\\n size_t index = 0) \\\n { \\\n return \\\n index >= data_ ## EnumName::_size ? \\\n throw std::runtime_error(\"invalid identifier\") : \\\n matches_untrimmed( \\\n data_ ## EnumName::_raw_names[index], s) ? \\\n (EnumName)(_enum)data_ ## EnumName::_values[ \\\n index] : \\\n _from_string(s, index + 1); \\\n } \\\n \\\n EnumName() = delete; \\\n constexpr EnumName(_enum value) : _value(value) { } \\\n constexpr operator _enum() const { return (_enum)_value; } \\\n \\\n private: \\\n _underlying _value; \\\n \\\n static const char * const * _trimmed_names() \\\n { \\\n static char *the_names[data_ ## EnumName::_size]; \\\n static bool initialized = false; \\\n \\\n if (!initialized) { \\\n for (size_t index = 0; index < data_ ## EnumName::_size; \\\n ++index) { \\\n \\\n size_t length = \\\n std::strcspn(data_ ## EnumName::_raw_names[index],\\\n terminators); \\\n \\\n the_names[index] = new char[length + 1]; \\\n \\\n std::strncpy(the_names[index], \\\n data_ ## EnumName::_raw_names[index], \\\n length); \\\n the_names[index][length] = '\\0'; \\\n } \\\n \\\n initialized = true; \\\n } \\\n \\\n return the_names; \\\n } \\\n};\n// The code above was a \"header file\". This is a program that uses it.\n#include <iostream>\n#include \"the_file_above.h\"\n\nENUM(Channel, char, Red = 1, Green, Blue)\n\nconstexpr Channel channel = Channel::_from_string(\"Red\");\n\nint main()\n{\n std::cout << channel._to_string() << std::endl;\n\n switch (channel) {\n case Channel::Red: return 0;\n case Channel::Green: return 1;\n case Channel::Blue: return 2;\n }\n}\n\nstatic_assert(sizeof(Channel) == sizeof(char), \"\");\nRedRedRed"}, {"idx": "webquery-test-8", "doc": "How do you get assembler output from C/C++ source in gcc?", "code": "-S-S-Sgcc -S helloworld.c\nhelloworld.shelloworld.shelloworld.shelloworld.sgcc -S -o my_asm_output.s helloworld.c\nobjdumpobjdumpobjdumpobjdump -S --disassemble helloworld > helloworld.dump\n-S-Sfile helloworldobjdumpobjdumpobjdumpobjdump -drwC -Mintel -S foo.o | lessobjdump -drwC -Mintel -S foo.o | lessobjdump -drwC -Mintel -S foo.o | lessobjdump -drwC -Mintel -S foo.o | less"}, {"idx": "webquery-test-1", "doc": "Struct Constructor in C++?", "code": "classclass"}, {"idx": "webquery-test-2", "doc": "How do I pass a unique_ptr argument to a constructor or a function?", "code": "Base(std::unique_ptr<Base> n)\n : next(std::move(n)) {}\nBase newBase(std::move(nextBase));\nBase fromTemp(std::unique_ptr<Base>(new Base(...));\nnewBasenewBasestd::movestd::movestd::movestd::moveBase::Base(std::unique_ptr<Base> n)Base::Base(std::unique_ptr<Base> n)Base::Base(std::unique_ptr<Base> n)Base::Base(std::unique_ptr<Base> n)Base::Base(std::unique_ptr<Base> n)Base::Base(std::unique_ptr<Base> n)Base(std::unique_ptr<Base> &n)\n : next(std::move(n)) {}\nBase newBase(std::unique_ptr<Base>(new Base)); //Illegal in this case.\nBase newBase(nextBase);\nnextBasenextBaseBase(std::unique_ptr<Base> const &n);\nconst&const&const&constBase(std::unique_ptr<Base> &&n)\n : next(std::move(n)) {}\nBase newBase(std::unique_ptr<Base>(new Base)); //legal now..\nBase newBase(std::unique_ptr<Base>(new Base)); //legal now..\nBase newBase(std::move(nextBase));\nnextBasenextBaseunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptrstd::unique_ptr<Base> newPtr(std::move(oldPtr));\nstd::unique_ptr<Base> &&temporary = std::move(oldPtr);\nstd::unique_ptr<Base> newPtr(temporary);\ntemporarytemporarytemporarytemporarytemporaryunique_ptrunique_ptr"}, {"idx": "webquery-test-3", "doc": "What is array to pointer decay?", "code": "int numbers [5]int numbers [5]int numbers [5]int numbers [5]int numbers [5]sizeofvoid by_value(const T* array) // const T array[] means the same\nvoid by_pointer(const T (*array)[U])\nvoid by_reference(const T (&array)[U])\nsizeof"}, {"idx": "webquery-test-4", "doc": "What are the barriers to understanding pointers and what can be done to overcome them?", "code": "type\n THouse = class\n private\n FName : array[0..9] of Char;\n public\n constructor Create(name: PChar);\n end;\nTHouse.Create('My house');\nvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\nvar\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := h1; // copies the address, not the house\n ...\nvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\n h.Free;\n h := nil;\nvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\n h.Free;\n ... // forgot to clear h here\n h.OpenFrontDoor; // will most likely fail\nhhvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n h := THouse.Create('My house'); // uh-oh, what happened to our first house?\n ...\n h.Free;\n h := nil;\nhprocedure OpenTheFrontDoorOfANewHouse;\nvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n h.OpenFrontDoor;\n // uh-oh, no .Free here, where does the address go?\nend;\nvar\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := h1; // copies the address, not the house\n ...\n h1.Free;\n h1 := nil;\n h2.OpenFrontDoor; // uh-oh, what happened to our house?\nh1h1h1var\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := THouse.Create('My other house somewhere');\n ^-----------------------^\n longer than 10 characters\n 0123456789 <-- 10 characters\nvar\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('Home');\n h2 := THouse.Create('Cabin');\n h1.NextHouse := h2;\nNextHousevar\n h1, h2: THouse;\n h: THouse;\nbegin\n h1 := THouse.Create('Home');\n h2 := THouse.Create('Cabin');\n h1.NextHouse := h2;\n ...\n h := h1;\n while h <> nil do\n begin\n h.LockAllDoors;\n h.CloseAllWindows;\n h := h.NextHouse;\n end;\n"}, {"idx": "webquery-test-5", "doc": "std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?", "code": "std::unique_lockstd::unique_lockstd::unique_lockstd::unique_lockstd::lock_guardclass MyClass{\n std::mutex my_mutex;\n void member_foo() {\n std::lock_guard<mutex_type> lock(this->my_mutex); \n /*\n block of code which needs mutual exclusion (e.g. open the same \n file in multiple threads).\n */\n\n //mutex is automatically released when lock goes out of scope\n } \n};\nstd::lock_guardstd::lock_guardstd::lock_guardstd::lock_guardstd::lock_guardstd::scoped_lockstd::scoped_lock"}, {"idx": "webquery-test-6", "doc": "How do I tokenize a string in C++?", "code": "#include <iostream>\n#include <string>\n#include <boost/foreach.hpp>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int, char**)\n{\n string text = \"token, test string\";\n\n char_separator<char> sep(\", \");\n tokenizer< char_separator<char> > tokens(text, sep);\n BOOST_FOREACH (const string& t, tokens) {\n cout << t << \".\" << endl;\n }\n}\n#include <iostream>\n#include <string>\n#include <boost/tokenizer.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nint main(int, char**)\n{\n string text = \"token, test string\";\n\n char_separator<char> sep(\", \");\n tokenizer<char_separator<char>> tokens(text, sep);\n for (const auto& t : tokens) {\n cout << t << \".\" << endl;\n }\n}\n"}, {"idx": "webquery-test-7", "doc": "In C++, what is a virtual base class?", "code": "class A { public: void Foo() {} };\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\n A\n / \\\nB C\n \\ /\n D\nD d;\nd.Foo(); // is this B's Foo() or C's Foo() ??\nclass A { public: void Foo() {} };\nclass B : public virtual A {};\nclass C : public virtual A {};\nclass D : public B, public C {};\nD d;\nd.Foo(); // no longer ambiguous\n"}, {"idx": "webquery-test-8", "doc": "Differences between C++ string == and compare()?", "code": "operator==template<class charT, class traits, class Allocator>\nbool operator==(const basic_string<charT,traits,Allocator>& lhs,\n const basic_string<charT,traits,Allocator>& rhs) noexcept;\n"}, {"idx": "webquery-test-9", "doc": "std::string to char*", "code": "c_str()std::string str = \"string\";\nconst char *cstr = str.c_str();\nconst char *const char *std::string str = \"string\";\nchar *cstr = new char[str.length() + 1];\nstrcpy(cstr, str.c_str());\n// do stuff\ndelete [] cstr;\nstd::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);\n"}, {"idx": "webquery-test-10", "doc": "Resolve build errors due to circular dependency amongst classes", "code": "// file: A.h\nclass A {\n B _b;\n};\n\n// file: B.h\nclass B {\n A _a;\n};\n\n// file main.cc\n#include \"A.h\"\n#include \"B.h\"\nint main(...) {\n A a;\n}\nAAAAA// file: A.h\nclass A {\n // both these are fine, so are various const versions of the same.\n B& _b_ref;\n B* _b_ptr;\n};\nmain()// file: main.cc\n#include \"A.h\" // <-- Houston, we have a problem\n#include// file: partially_pre_processed_main.cc\nclass A {\n B& _b_ref;\n B* _b_ptr;\n};\n#include \"B.h\"\nint main (...) {\n A a;\n}\nBB// main.cc\nclass B;\n#include \"A.h\"\n#include \"B.h\"\nint main (...) {\n A a;\n}\n#include \"A.h\"#include \"A.h\"#include \"A.h\"// file: A.h\nclass B;\nclass A {\n B* _b; // or any of the other variants.\n};\n#include \"A.h\"// file: B.h\n#include \"A.h\"\nclass B {\n // note that this is cool because the compiler knows by this time\n // how much space A will need.\n A _a; \n}\n"}, {"idx": "webquery-test-11", "doc": "When to use references vs. pointers", "code": "nullptrnullptrnullptrnullptrnullptr"}, {"idx": "webquery-test-1", "doc": "How do I print a double value with full precision using cout?", "code": "std::coutstd::coutdouble d = 3.14159265358979;\ncout.precision(17);\ncout << \"Pi: \" << fixed << d << endl;\n#include <limits>#include <limits>\n\ntypedef std::numeric_limits< double > dbl;\n\ndouble d = 3.14159265358979;\ncout.precision(dbl::max_digits10);\ncout << \"Pi: \" << d << endl;\n"}, {"idx": "webquery-test-2", "doc": "Why does the C++ STL not provide any \"tree\" containers?", "code": "std::mapstd::mapstd::mapstd::map"}, {"idx": "webquery-test-3", "doc": "Compiling C++11 with g++", "code": "$ g++ -std=c++11 your_file.cpp -o your_program$ g++ -std=c++0x your_file.cpp -o your_program"}, {"idx": "webquery-test-4", "doc": "Why should I not #include <bits/stdc++.h>?", "code": "<bits/stdc++.h>#include<string><string><string>"}, {"idx": "webquery-test-5", "doc": "What is this weird colon-member (\" : \") syntax in the constructor?", "code": "Foo(int num): bar(num) \nbarbarFoo(int num): bar(num) {};\nFoo(int num)\n{\n bar = num;\n}\nCost of Member Initialization = Object Construction \nCost of Member Assignment = Object Construction + Assignment\nFoo(int num) : bar() {bar = num;}\nFoo(int num): bar(num){}\nclass MyClass {\npublic:\n // Reference member, has to be Initialized in Member Initializer List\n int &i;\n int b;\n // Non static const member, must be Initialized in Member Initializer List\n const int k;\n\n // Constructor\u2019s parameter name b is same as class data member\n // Other way is to use this->b to refer to data member\n MyClass(int a, int b, int c) : i(a), b(b), k(c) {\n // Without Member Initializer\n // this->b = b;\n }\n};\n\nclass MyClass2 : public MyClass {\npublic:\n int p;\n int q;\n MyClass2(int x, int y, int z, int l, int m) : MyClass(x, y, z), p(l), q(m) {}\n};\n\nint main() {\n int x = 10;\n int y = 20;\n int z = 30;\n MyClass obj(x, y, z);\n\n int l = 40;\n int m = 50;\n MyClass2 obj2(x, y, z, l, m);\n\n return 0;\n}\nMyClass2MyClass2"}, {"idx": "webquery-test-6", "doc": "What is the lifetime of a static variable in a C++ function?", "code": "staticstruct emitter {\n string str;\n emitter(const string& s) : str(s) { cout << \"Created \" << str << endl; }\n ~emitter() { cout << \"Destroyed \" << str << endl; }\n};\n\nvoid foo(bool skip_first) \n{\n if (!skip_first)\n static emitter a(\"in if\");\n static emitter b(\"in foo\");\n}\n\nint main(int argc, char*[])\n{\n foo(argc != 2);\n if (argc == 3)\n foo(false);\n}\n[0][1][1][2]"}, {"idx": "webquery-test-7", "doc": "What is the usefulness of `enable_shared_from_this`?", "code": "shared_ptrshared_ptrshared_ptrshared_ptrshared_ptrclass Y: public enable_shared_from_this<Y>\n{\npublic:\n\n shared_ptr<Y> f()\n {\n return shared_from_this();\n }\n}\n\nint main()\n{\n shared_ptr<Y> p(new Y);\n shared_ptr<Y> q = p->f();\n assert(p == q);\n assert(!(p < q || q < p)); // p and q must share ownership\n}\nf()f()class Y: public enable_shared_from_this<Y>\n{\npublic:\n\n shared_ptr<Y> f()\n {\n return shared_ptr<Y>(this);\n }\n}\nenable_shared_from_this"}, {"idx": "webquery-test-8", "doc": "Fastest way to determine if an integer is between two integers (inclusive) with known sets of values", "code": "// use a < for an inclusive lower bound and exclusive upper bound\n// use <= for an inclusive lower bound and inclusive upper bound\n// alternatively, if the upper bound is inclusive and you can pre-calculate\n// upper-lower, simply add + 1 to upper-lower and use the < operator.\n if ((unsigned)(number-lower) <= (upper-lower))\n in_range(number);\nupper-lowernumbernumbernumbernumbernumbernumber"}, {"idx": "webquery-test-1", "doc": "C++ unordered_map using a custom class type as the key", "code": "std::unordered_mapoperator()operator()operator()operator()operator()struct Key\n{\n std::string first;\n std::string second;\n int third;\n\n bool operator==(const Key &other) const\n { return (first == other.first\n && second == other.second\n && third == other.third);\n }\n};\nnamespace std {\n\n template <>\n struct hash<Key>\n {\n std::size_t operator()(const Key& k) const\n {\n using std::size_t;\n using std::hash;\n using std::string;\n\n // Compute individual hash values for first,\n // second and third and combine them using XOR\n // and bit shifting:\n\n return ((hash<string>()(k.first)\n ^ (hash<string>()(k.second) << 1)) >> 1)\n ^ (hash<int>()(k.third) << 1);\n }\n };\n\n}\nstd::unordered_mapint main()\n{\n std::unordered_map<Key,std::string> m6 = {\n { {\"John\", \"Doe\", 12}, \"example\"},\n { {\"Mary\", \"Sue\", 21}, \"another\"}\n };\n}\nstd::hash<Key>std::hash<Key>std::hash<Key>stdstruct KeyHasher\n{\n std::size_t operator()(const Key& k) const\n {\n using std::size_t;\n using std::hash;\n using std::string;\n\n return ((hash<string>()(k.first)\n ^ (hash<string>()(k.second) << 1)) >> 1)\n ^ (hash<int>()(k.third) << 1);\n }\n};\n\nint main()\n{\n std::unordered_map<Key,std::string,KeyHasher> m6 = {\n { {\"John\", \"Doe\", 12}, \"example\"},\n { {\"Mary\", \"Sue\", 21}, \"another\"}\n };\n}\nhash_valuehash_valuehash_value#include <boost/functional/hash.hpp>\n\nstruct KeyHasher\n{\n std::size_t operator()(const Key& k) const\n {\n using boost::hash_value;\n using boost::hash_combine;\n\n // Start with a hash value of 0 .\n std::size_t seed = 0;\n\n // Modify 'seed' by XORing and bit-shifting in\n // one member of 'Key' after the other:\n hash_combine(seed,hash_value(k.first));\n hash_combine(seed,hash_value(k.second));\n hash_combine(seed,hash_value(k.third));\n\n // Return the result.\n return seed;\n }\n};\nnamespace std\n{\n template <>\n struct hash<Key>\n {\n size_t operator()( const Key& k ) const\n {\n // Compute individual hash values for first, second and third\n // http://stackoverflow.com/a/1646913/126995\n size_t res = 17;\n res = res * 31 + hash<string>()( k.first );\n res = res * 31 + hash<string>()( k.second );\n res = res * 31 + hash<int>()( k.third );\n return res;\n }\n };\n}\n"}, {"idx": "webquery-test-2", "doc": "How do I print out the contents of a vector?", "code": "std::vector<char> path;\n// ...\nfor (char i: path)\n std::cout << i << ' ';\ncharcharcharcharcharcharfor (auto i: path)\n std::cout << i << ' ';\nautoautoautoautoautostd::vector<char> path{'a', 'b', 'c'};\n\nfor (auto i: path) {\n i = '_'; // 'i' is a copy of the element in 'path', so although\n // we can change 'i' here perfectly fine, the elements\n // of 'path' have not changed\n std::cout << i << ' '; // will print: \"_ _ _\"\n}\n\nfor (auto i: path) {\n std::cout << i << ' '; // will print: \"a b c\"\n}\niiifor (const auto i: path) {\n i = '_'; // this will now produce a compiler error\n std::cout << i << ' ';\n}\npathpathfor (auto& i: path) {\n i = '_'; // changes to 'i' will now also change the\n // element in 'path' itself to that value\n std::cout << i << ' ';\n}\npathfor (const auto& i: path)\n std::cout << i << ' ';\nstd::vector<char> path;\n// ...\nfor (std::vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)\n std::cout << *i << ' ';\niteratoriteratoriteratoriteratorfor (auto i = path.begin(); i != path.end(); ++i)\n std::cout << *i << ' ';\niiiiiiiifor (auto i = path.cbegin(); i != path.cend(); ++i) {\n *i = '_'; // will produce a compiler error\n std::cout << *i << ' ';\n}\nusing Path = std::vector<char>; // C++11 onwards only\nPath path; // 'Path' is an alias for std::vector<char>\n// ...\nfor (Path::const_iterator i = path.begin(); i != path.end(); ++i)\n std::cout << *i << ' ';\ntypedeftypedef std::vector<char> Path; // 'Path' now a synonym for std::vector<char>\nPath path;\n// ...\nfor (Path::const_iterator i = path.begin(); i != path.end(); ++i)\n std::cout << *i << ' ';\n*i*i*i*i*istd::vectorfor (int i=0; i<path.size(); ++i)\n std::cout << path[i] << ' ';\nstd::vectorstd::vectorstd::vectortypedef std::vector<char> Path; // 'Path' now a synonym for std::vector<char>\nfor (Path::size_type i=0; i<path.size(); ++i)\n std::cout << path[i] << ' ';\niteratoriteratorstd::copystd::vectorstd::vectorstd::vector#include <iterator> // for std::ostream_iterator\n#include <algorithm> // for std::ranges::copy depending on lib support\n\nstd::vector<char> path;\n// ...\nstd::ranges::copy(path, std::ostream_iterator<char>(std::cout, \" \"));\nstd::ranges::copy#include <iostream>\n#include <vector>\n#include <iterator> // for std::ostream_iterator\n#include <algorithm> // for std::ranges::copy depending on lib support\n\nusing Path = std::vector<char>; // type alias for std::vector<char>\n\nstd::ostream& operator<< (std::ostream& out, const Path& v) {\n if ( !v.empty() ) {\n out << '[';\n std::ranges::copy(v, std::ostream_iterator<char>(out, \", \"));\n out << \"\\b\\b]\"; // use two ANSI backspace characters '\\b' to overwrite final \", \"\n }\n return out;\n}\n\nint main() {\n Path path{'/', 'f', 'o', 'o'};\n\n // will output: \"path: [/, f, o, o]\"\n std::cout << \"path: \" << path << std::endl;\n\n return 0;\n}\nPath"}, {"idx": "webquery-test-3", "doc": "How to round up the result of integer division?", "code": "int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n"}, {"idx": "webquery-test-4", "doc": "What XML parser should I use in C++?", "code": "xmlReaderxmlReadernewnew"}, {"idx": "webquery-test-5", "doc": "How to use Boost in Visual Studio 2010", "code": "C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0C:\\boost_1_47_0Library DirectoriesLibrary DirectoriesLibrary DirectoriesLibrary DirectoriesC:\\bzip2-1.0.6C:\\bzip2-1.0.6C:\\zlib-1.2.5C:\\zlib-1.2.5project-config.jamproject-config.jamproject-config.jamproject-config.jamproject-config.jamproject-config.jamproject-config.jamC:\\icu4c-4_8C:\\icu4c-4_8C:\\icu4c-4_8"}, {"idx": "webquery-test-6", "doc": "Define preprocessor macro through CMake?", "code": "add_definitionsadd_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})\nadd_compile_definitions(WITH_OPENCV2)\nadd_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)\nadd_definitions"}, {"idx": "webquery-test-7", "doc": "When should you use constexpr capability in C++11?", "code": "constexpr int MeaningOfLife ( int a, int b ) { return a * b; }\n\nconst int meaningOfLife = MeaningOfLife( 6, 7 );\nmax( a, b )template< typename Type > constexpr Type max( Type a, Type b ) { return a < b ? b : a; }\nmaxDegreesToRadiansconst float oneeighty = DegreesToRadians( 180.0f );\n"}, {"idx": "webquery-test-8", "doc": "How to implement the factory method pattern in C++ correctly", "code": "Vec2(float x, float y);\nVec2(float angle, float magnitude); // not a valid overload!\nstruct Cartesian {\n inline Cartesian(float x, float y): x(x), y(y) {}\n float x, y;\n};\nstruct Polar {\n inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}\n float angle, magnitude;\n};\nVec2(const Cartesian &cartesian);\nVec2(const Polar &polar);\nVec2 v2(Vec2::Cartesian(3.0f, 4.0f));\nclass Abstract {\n public:\n virtual void do() = 0;\n};\n\nclass Factory {\n public:\n Abstract *create();\n};\n\nFactory f;\nAbstract *a = f.create();\na->do();\n"}, {"idx": "webquery-test-9", "doc": "Combining C++ and C - how does #ifdef __cplusplus work?", "code": "extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\"extern \"C\""}, {"idx": "webquery-test-10", "doc": "Easily measure elapsed time", "code": "//***C++11 Style:***\n#include <chrono>\n\nstd::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();\nstd::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();\n\nstd::cout << \"Time difference = \" << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << \"[\u00b5s]\" << std::endl;\nstd::cout << \"Time difference = \" << std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count() << \"[ns]\" << std::endl;\n"}, {"idx": "webquery-test-1", "doc": "How to implement an STL-style iterator and avoid common pitfalls?", "code": "iterator {\n iterator(const iterator&);\n ~iterator();\n iterator& operator=(const iterator&);\n iterator& operator++(); //prefix increment\n reference operator*() const;\n friend void swap(iterator& lhs, iterator& rhs); //C++11 I think\n};\n\ninput_iterator : public virtual iterator {\n iterator operator++(int); //postfix increment\n value_type operator*() const;\n pointer operator->() const;\n friend bool operator==(const iterator&, const iterator&);\n friend bool operator!=(const iterator&, const iterator&); \n};\n//once an input iterator has been dereferenced, it is \n//undefined to dereference one before that.\n\noutput_iterator : public virtual iterator {\n reference operator*() const;\n iterator operator++(int); //postfix increment\n};\n//dereferences may only be on the left side of an assignment\n//once an output iterator has been dereferenced, it is \n//undefined to dereference one before that.\n\nforward_iterator : input_iterator, output_iterator {\n forward_iterator();\n};\n//multiple passes allowed\n\nbidirectional_iterator : forward_iterator {\n iterator& operator--(); //prefix decrement\n iterator operator--(int); //postfix decrement\n};\n\nrandom_access_iterator : bidirectional_iterator {\n friend bool operator<(const iterator&, const iterator&);\n friend bool operator>(const iterator&, const iterator&);\n friend bool operator<=(const iterator&, const iterator&);\n friend bool operator>=(const iterator&, const iterator&);\n\n iterator& operator+=(size_type);\n friend iterator operator+(const iterator&, size_type);\n friend iterator operator+(size_type, const iterator&);\n iterator& operator-=(size_type); \n friend iterator operator-(const iterator&, size_type);\n friend difference_type operator-(iterator, iterator);\n\n reference operator[](size_type) const;\n};\n\ncontiguous_iterator : random_access_iterator { //C++17\n}; //elements are stored contiguously in memory.\nstd::iterator_traits<youriterator>std::iterator_traits<youriterator>std::iterator_traits<youriterator>std::iterator_traits<youriterator>struct std::iterator_traits<youriterator> { \n typedef ???? difference_type; //almost always ptrdiff_t\n typedef ???? value_type; //almost always T\n typedef ???? reference; //almost always T& or const T&\n typedef ???? pointer; //almost always T* or const T*\n typedef ???? iterator_category; //usually std::forward_iterator_tag or similar\n};\nstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagstd::input_iterator_tagconst_iteratorconst_iteratorconst_iteratorconst_iteratorconst_iterator"}, {"idx": "webquery-test-2", "doc": "Namespace + functions versus static methods on a class", "code": "using#include <string>\n#include <vector>\n\n// Etc.\n{\n using namespace std ;\n // Now, everything from std is accessible without qualification\n string s ; // Ok\n vector v ; // Ok\n}\n\nstring ss ; // COMPILATION ERROR\nvector vv ; // COMPILATION ERROR\n#include <string>\n#include <vector>\n\n{\n using std::string ;\n string s ; // Ok\n vector v ; // COMPILATION ERROR\n}\n\nstring ss ; // COMPILATION ERROR\nvector vv ; // COMPILATION ERROR\nAAAAAAAAusing namespacenamespace A\n{\n void AAA();\n void AAA2();\n}\n\nnamespace B\n{\n void BBB();\n}\n\nnamespace C\n{\n using A::AAA;\n using B::BBB;\n}\n\nnamespace D\n{\n using namespace A;\n using namespace B;\n}\n\nvoid foo()\n{\n C::AAA();\n // C::AAA2(); // ERROR, won't compile\n C::BBB();\n}\n\nvoid bar()\n{\n D::AAA();\n D::AAA2();\n D::BBB();\n}\n"}, {"idx": "webquery-test-3", "doc": "Is 0 a decimal literal or an octal literal?", "code": "0integer-literal: \n decimal-literal integer-suffixopt \n octal-literal integer-suffixopt \n hexadecimal-literal integer-suffixopt \ndecimal-literal: \n nonzero-digit \n decimal-literal digit \noctal-literal: \n 0 <--------------------<Here>\n octal-literal octal-digit\n"}, {"idx": "webquery-test-4", "doc": "C/C++ include header file order", "code": "#include"}, {"idx": "webquery-test-5", "doc": "check if a std::vector contains a certain object?", "code": "vv#include <algorithm>\n\nif(std::find(v.begin(), v.end(), x) != v.end()) {\n /* v contains x */\n} else {\n /* v does not contain x */\n}\nvif(!v.empty()){\n /* v is non-empty */\n} else {\n /* v is empty */\n}\n"}, {"idx": "webquery-test-6", "doc": "Find out if string ends with another string in C++", "code": "std::string::compare#include <iostream>\n\nbool hasEnding (std::string const &fullString, std::string const &ending) {\n if (fullString.length() >= ending.length()) {\n return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));\n } else {\n return false;\n }\n}\n\nint main () {\n std::string test1 = \"binary\";\n std::string test2 = \"unary\";\n std::string test3 = \"tertiary\";\n std::string test4 = \"ry\";\n std::string ending = \"nary\";\n\n std::cout << hasEnding (test1, ending) << std::endl;\n std::cout << hasEnding (test2, ending) << std::endl;\n std::cout << hasEnding (test3, ending) << std::endl;\n std::cout << hasEnding (test4, ending) << std::endl;\n\n return 0;\n}\n"}, {"idx": "webquery-test-7", "doc": "When should I use the new keyword in C++?", "code": "newdeletedeletedeletedeletedeletenewdeletedeletedeletedeletedelete"}, {"idx": "webquery-test-8", "doc": "How to implement classic sorting algorithms in modern C++?", "code": "#include <algorithm> // min_element, iter_swap, \n // upper_bound, rotate, \n // partition, \n // inplace_merge,\n // make_heap, sort_heap, push_heap, pop_heap,\n // is_heap, is_sorted\n#include <cassert> // assert \n#include <functional> // less\n#include <iterator> // distance, begin, end, next\nstd::begin()std::begin()std::begin()std::begin()std::begin()std::begin()std::begin()std::begin()std::begin()std::begin()std::less<>std::less<>template<class It, class Compare = std::less<>>\nvoid xxx_sort(It first, It last, Compare cmp = Compare{});\ntemplate<class It>\nusing value_type_t = typename std::iterator_traits<It>::value_type;\n\ntemplate<class It, class Compare = std::less<value_type_t<It>>>\nvoid xxx_sort(It first, It last, Compare cmp = Compare{});\ntypename xxx<yyy>::typetemplate<class It, class Compare>\nvoid xxx_sort(It first, It last, Compare cmp); // general implementation\n\ntemplate<class It>\nvoid xxx_sort(It first, It last)\n{\n xxx_sort(first, last, std::less<typename std::iterator_traits<It>::value_type>());\n}\nautoautoautoautoautoautoautoautoautoautoauto()()()()()()()()O(N\u00b2)std::min_elementstd::min_elementtemplate<class FwdIt, class Compare = std::less<>>\nvoid selection_sort(FwdIt first, FwdIt last, Compare cmp = Compare{})\n{\n for (auto it = first; it != last; ++it) {\n auto const selection = std::min_element(it, last, cmp);\n std::iter_swap(selection, it); \n assert(std::is_sorted(first, std::next(it), cmp));\n }\n}\nselection_sortselection_sortselection_sortif (std::distance(first, last) <= 1) return;if (std::distance(first, last) <= 1) return;if (std::distance(first, last) <= 1) return;O(N\u00b2)insertion_sortinsertion_sortinsertion_sorttemplate<class FwdIt, class Compare = std::less<>>\nvoid insertion_sort(FwdIt first, FwdIt last, Compare cmp = Compare{})\n{\n for (auto it = first; it != last; ++it) {\n auto const insertion = std::upper_bound(first, it, *it, cmp);\n std::rotate(insertion, it, std::next(it)); \n assert(std::is_sorted(first, std::next(it), cmp));\n }\n}\ninsertion_sortinsertion_sortif (std::distance(first, last) <= 1) return;if (std::distance(first, last) <= 1) return;if (std::distance(first, last) <= 1) return;if (std::distance(first, last) <= 1) return;using RevIt = std::reverse_iterator<BiDirIt>;\nauto const insertion = std::find_if_not(RevIt(it), RevIt(first), \n [=](auto const& elem){ return cmp(*it, elem); }\n).base();\nO(N\u00b2)O(N\u00b2)O(N\u00b2)O(N log N)O(N log N)[first, last)[first, last)[first, last)template<class FwdIt, class Compare = std::less<>>\nvoid quick_sort(FwdIt first, FwdIt last, Compare cmp = Compare{})\n{\n auto const N = std::distance(first, last);\n if (N <= 1) return;\n auto const pivot = *std::next(first, N / 2);\n auto const middle1 = std::partition(first, last, [=](auto const& elem){ \n return cmp(elem, pivot); \n });\n auto const middle2 = std::partition(middle1, last, [=](auto const& elem){ \n return !cmp(pivot, elem);\n });\n quick_sort(first, middle1, cmp); // assert(std::is_sorted(first, middle1, cmp));\n quick_sort(middle2, last, cmp); // assert(std::is_sorted(middle2, last, cmp));\n}\nO(N log N)O(N log N)O(N log N)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N^2)O(N)O(N)[first, last)[first, last)template<class BiDirIt, class Compare = std::less<>>\nvoid merge_sort(BiDirIt first, BiDirIt last, Compare cmp = Compare{})\n{\n auto const N = std::distance(first, last);\n if (N <= 1) return; \n auto const middle = std::next(first, N / 2);\n merge_sort(first, middle, cmp); // assert(std::is_sorted(first, middle, cmp));\n merge_sort(middle, last, cmp); // assert(std::is_sorted(middle, last, cmp));\n std::inplace_merge(first, middle, last, cmp); // assert(std::is_sorted(first, last, cmp));\n}\nstd::inplace_mergestd::inplace_mergestd::inplace_mergeO(N log N)O(N)O(N)template<class RandomIt, class Compare = std::less<>>\nvoid heap_sort(RandomIt first, RandomIt last, Compare cmp = Compare{})\n{\n lib::make_heap(first, last, cmp); // assert(std::is_heap(first, last, cmp));\n lib::sort_heap(first, last, cmp); // assert(std::is_sorted(first, last, cmp));\n}\nstd::make_heapstd::make_heapstd::make_heapstd::make_heapnamespace lib {\n\n// NOTE: is O(N log N), not O(N) as std::make_heap\ntemplate<class RandomIt, class Compare = std::less<>>\nvoid make_heap(RandomIt first, RandomIt last, Compare cmp = Compare{})\n{\n for (auto it = first; it != last;) {\n std::push_heap(first, ++it, cmp); \n assert(std::is_heap(first, it, cmp)); \n }\n}\n\ntemplate<class RandomIt, class Compare = std::less<>>\nvoid sort_heap(RandomIt first, RandomIt last, Compare cmp = Compare{})\n{\n for (auto it = last; it != first;) {\n std::pop_heap(first, it--, cmp);\n assert(std::is_heap(first, it, cmp)); \n } \n}\n\n} // namespace lib\npush_heappush_heappush_heappush_heappush_heappush_heappush_heappush_heappush_heappush_heapO(N)O(N)"}, {"idx": "webquery-test-9", "doc": "How do you make a HTTP request with C++?", "code": "// Edit : rewritten for cURLpp 0.7.3\n// Note : namespace changed, was cURLpp in 0.7.2 ...\n\n#include <curlpp/cURLpp.hpp>\n#include <curlpp/Options.hpp>\n\n// RAII cleanup\n\ncurlpp::Cleanup myCleanup;\n\n// Send request and get a result.\n// Here I use a shortcut to get it in a string stream ...\n\nstd::ostringstream os;\nos << curlpp::options::Url(std::string(\"http://example.com\"));\n\nstring asAskedInQuestion = os.str();\nexamples"}, {"idx": "webquery-test-1", "doc": "Comparison of C++ unit test frameworks", "code": "#include <gtest/gtest.h>\n\nTEST(MyTestSuitName, MyTestCaseName) {\n int actual = 1;\n EXPECT_GT(actual, 0);\n EXPECT_EQ(1, actual) << \"Should be equal to one\";\n}\nASSERT_EQ(5, Foo(i)) << \" where i = \" << i;ASSERT_EQ(5, Foo(i)) << \" where i = \" << i;"}, {"idx": "webquery-test-2", "doc": "Copy a file in a sane, safe and efficient way", "code": "#include <fstream>\n\nint main()\n{\n std::ifstream src(\"from.ogv\", std::ios::binary);\n std::ofstream dst(\"to.ogv\", std::ios::binary);\n\n dst << src.rdbuf();\n}\nboost#include <copyfile.h>\n\nint\ncopyfile(const char *from, const char *to, copyfile_state_t state, copyfile_flags_t flags);\n"}, {"idx": "webquery-test-3", "doc": "How do I build a graphical user interface in C++?", "code": "printf"}, {"idx": "webquery-test-4", "doc": "std::string length() and size() member functions", "code": "size()size()size()size()size()"}, {"idx": "webquery-test-5", "doc": "Why are unnamed namespaces used and what are their benefits?", "code": "namespace unique { /* empty */ }\nusing namespace unique;\nnamespace unique { /* namespace body. stuff in here */ }\n::namehelphelpnamespace { int a1; }\nstatic int a2;\naa"}, {"idx": "webquery-test-6", "doc": "How exactly is std::string_view faster than const std::string&?", "code": "std::string_viewstd::string const&std::string const&std::string const&std::string const&std::string const&void foo( std::string_view bob ) {\n std::cout << bob << \"\\n\";\n}\nint main(int argc, char const*const* argv) {\n foo( \"This is a string long enough to avoid the std::string SBO\" );\n if (argc > 1)\n foo( argv[1] );\n}\nstring_viewstring_viewstring_viewstring_viewstd::stringstd::string_viewstring_viewstd::string_viewstd::stringstd::stringstd::stringstd::string_viewstd::string_viewstd::stringstd::stringstd::stringstd::stringstd::stringstd::string"}, {"idx": "webquery-test-7", "doc": "Why do people say there is modulo bias when using a random number generator?", "code": "rand()rand()rand()rand()RAND_MAXRAND_MAXRAND_MAXrand()rand()rand()rand()rand()rand()rand()%nrand()%nrand()%nrand()%nint x; \ndo {\n x = rand();\n} while (x >= n);\nnnnnnnint x;\n\ndo {\n x = rand();\n} while (x >= (RAND_MAX - RAND_MAX % n));\n\nx %= n;\nnn"}, {"idx": "webquery-test-8", "doc": "Differences between unique_ptr and shared_ptr", "code": "unique_ptrunique_ptrunique_ptrunique_ptrunique_ptrunique_ptr<T> myPtr(new T); // Okay\nunique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr\nunique_ptrunique_ptr<T> myPtr(new T); // Okay\nunique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr\nunique_ptr<T> MyFunction() {\n unique_ptr<T> myPtr(/* ... */);\n\n /* ... */\n\n return myPtr;\n}\nunique_ptrunique_ptrshared_ptrshared_ptrshared_ptr<T> myPtr(new T); // Okay\nshared_ptr<T> myOtherPtr = myPtr; // Sure! Now have two pointers to the resource.\nshared_ptrunique_ptrunique_ptr"}, {"idx": "webquery-test-9", "doc": "C++ Erase vector element by value rather than by position?", "code": "std::remove()#include <algorithm>\n...\nvec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());\n"}, {"idx": "webquery-test-1", "doc": "How can I add reflection to a C++ application?", "code": "int xint x#define REM(...) __VA_ARGS__\n#define EAT(...)\n\n// Retrieve the type\n#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)\n#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)\n#define DETAIL_TYPEOF_HEAD(x, ...) REM x\n#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),\n// Strip off the type\n#define STRIP(x) EAT x\n// Show the type without parenthesis\n#define PAIR(x) REM x\nREFLECTABLEREFLECTABLE\n(\n (const char *) name,\n (int) age\n)\n// A helper metafunction for adding const to a type\ntemplate<class M, class T>\nstruct make_const\n{\n typedef T type;\n};\n\ntemplate<class M, class T>\nstruct make_const<const M, T>\n{\n typedef typename boost::add_const<T>::type type;\n};\n\n\n#define REFLECTABLE(...) \\\nstatic const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \\\nfriend struct reflector; \\\ntemplate<int N, class Self> \\\nstruct field_data {}; \\\nBOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))\n\n#define REFLECT_EACH(r, data, i, x) \\\nPAIR(x); \\\ntemplate<class Self> \\\nstruct field_data<i, Self> \\\n{ \\\n Self & self; \\\n field_data(Self & self) : self(self) {} \\\n \\\n typename make_const<Self, TYPEOF(x)>::type & get() \\\n { \\\n return self.STRIP(x); \\\n }\\\n typename boost::add_const<TYPEOF(x)>::type & get() const \\\n { \\\n return self.STRIP(x); \\\n }\\\n const char * name() const \\\n {\\\n return BOOST_PP_STRINGIZE(STRIP(x)); \\\n } \\\n}; \\\nfields_nfields_nfields_nstruct reflector\n{\n //Get field_data at index N\n template<int N, class T>\n static typename T::template field_data<N, T> get_field_data(T& x)\n {\n return typename T::template field_data<N, T>(x);\n }\n\n // Get the number of fields\n template<class T>\n struct fields\n {\n static const int n = T::fields_n;\n };\n};\nstruct field_visitor\n{\n template<class C, class Visitor, class I>\n void operator()(C& c, Visitor v, I)\n {\n v(reflector::get_field_data<I::value>(c));\n }\n};\n\n\ntemplate<class C, class Visitor>\nvoid visit_each(C & c, Visitor v)\n{\n typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range;\n boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));\n}\nPersonstruct Person\n{\n Person(const char *name, int age)\n :\n name(name),\n age(age)\n {\n }\nprivate:\n REFLECTABLE\n (\n (const char *) name,\n (int) age\n )\n};\nprint_fieldsstruct print_visitor\n{\n template<class FieldData>\n void operator()(FieldData f)\n {\n std::cout << f.name() << \"=\" << f.get() << std::endl;\n }\n};\n\ntemplate<class T>\nvoid print_fields(T & x)\n{\n visit_each(x, print_visitor());\n}\nprint_fieldsprint_fieldsint main()\n{\n Person p(\"Tom\", 82);\n print_fields(p);\n return 0;\n}\nname=Tom\nage=82\n"}, {"idx": "webquery-test-2", "doc": "Difference between angle bracket < > and double quotes \" \" while including header files in C++?", "code": "\"\" # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n # include <h-char-sequence> new-line\n\"\"\"\""}, {"idx": "webquery-test-3", "doc": "How do I best silence a warning about unused variables?", "code": "(void)var;void foo(int param1, int param2)\n{\n (void)param2;\n bar(param1);\n}\n#define UNUSED(expr) do { (void)(expr); } while (0)\n...\n\nvoid foo(int param1, int param2)\n{\n UNUSED(param2);\n bar(param1);\n}\n"}, {"idx": "webquery-test-4", "doc": "How can I pad an int with leading zeros when using cout << operator?", "code": "#include <iomanip>\n#include <iostream>\n\nint main()\n{\n std::cout << std::setfill('0') << std::setw(5) << 25;\n}\n00025\nsetfillsetfillsetfill"}, {"idx": "webquery-test-5", "doc": "NULL vs nullptr (Why was it replaced?)", "code": "nullptrnullptrnullptrnullptr0f(int);\nf(foo *);\n"}, {"idx": "webquery-test-6", "doc": "Why does C++11's lambda require \"mutable\" keyword for capture-by-value, by default?", "code": "mutable"}, {"idx": "webquery-test-7", "doc": "What is this smiley-with-beard expression: \"<:]{%>\"?", "code": "[] {};\n<: = [\n%> = }\n"}, {"idx": "webquery-test-8", "doc": "Strange definitions of TRUE and FALSE macros", "code": "'/' / '/''/' / '/''/' / '/''/' / '/''/' / '/''/' / '/''-' - '-''-' - '-''-' - '-''-' - '-'11#include <stdio.h>\n\n#define TRUE '/'/'/'\n#define FALSE '-'-'-'\n\nint main() {\n printf (\"%d\\n\", 2 * FALSE);\n return 0;\n}\ncharchar#define TRUE ('/'/'/')\n#define FALSE ('-'-'-')\n"}, {"idx": "webquery-test-9", "doc": "What open source C++ static analysis tools are available?", "code": "brew install cppcheck\n"}, {"idx": "webquery-test-1", "doc": "Is there any use for unique_ptr with array?", "code": "std::vectorstd::vectorstd::vectorunique_ptr<T[]>unique_ptr<T[]>"}, {"idx": "webquery-test-2", "doc": "Forward declaring an enum in C++", "code": "enum Enum1; // Illegal in C++03 and C++11; no size is explicitly specified.\nenum Enum2 : unsigned int; // Legal in C++11.\nenum class Enum3; // Legal in C++11, because enum class declarations have a default type of \"int\".\nenum class Enum4: unsigned int; // Legal C++11.\nenum Enum2 : unsigned short; // Illegal in C++11, because Enum2 was previously declared with a different type.\n"}, {"idx": "webquery-test-3", "doc": ".c vs .cc vs. .cpp vs .hpp vs .h vs .cxx", "code": ".c.c.c.C.C.C.C.C.C.C.H.H.H.H.H.H.ii.ii.ii.ii.ii.ii.ii.ixx.ixx.ixx.ixx"}, {"idx": "webquery-test-4", "doc": "When do I use a dot, arrow, or double colon to refer to members of a class in C++?", "code": "::::::::::::::::a::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::ba::bclassclassclassclass"}, {"idx": "webquery-test-5", "doc": "How to convert a char array to a string?", "code": "stringchar arr[ ] = \"This is a test\";\n\nstring str(arr);\n\n\n// You can also assign directly to a string.\nstr = \"This is another string\";\n\n// or\nstr = arr;\n"}, {"idx": "webquery-test-6", "doc": "How to correctly implement custom iterators and const_iterators?", "code": "std::iteratorstd::iteratorstd::iteratorstd::iteratorstd::iteratorstd::iterator"}, {"idx": "webquery-test-7", "doc": "Why would I ever use push_back instead of emplace_back?", "code": "push_backpush_backpush_backpush_backpush_backpush_backstd::vector<T> v;\nv.push_back(x);\nv.emplace_back(x);\npush_backpush_backpush_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backemplace_backstd::vector<std::unique_ptr<T>> v;\nT a;\nv.emplace_back(std::addressof(a)); // compiles\nv.push_back(std::addressof(a)); // fails to compile\nstd::unique_ptr<T>std::unique_ptr<T>std::unique_ptr<T>std::unique_ptr<T>std::unique_ptr<T>std::unique_ptr<T>std::vector<T *>std::vector<T *>std::vector<T *>std::vector<T *>std::vector<T *>std::vector<T *>std::vector<T *>std::vector<T *>push_back"}, {"idx": "webquery-test-1", "doc": "Range based loop: get item by value or reference to const?", "code": "auto const &for (auto const &x : vec)\nauto &auto xauto xauto x"}, {"idx": "webquery-test-2", "doc": "Why is f(i = -1, i = -1) undefined behavior?", "code": "f(i=-1, i=-1)\nclear i\nclear i\ndecr i\ndecr i\n"}, {"idx": "webquery-test-3", "doc": "Can you remove elements from a std::list while iterating through it?", "code": "std::list<item*>::iterator i = items.begin();\nwhile (i != items.end())\n{\n bool isActive = (*i)->update();\n if (!isActive)\n {\n items.erase(i++); // alternatively, i = items.erase(i);\n }\n else\n {\n other_code_involving(*i);\n ++i;\n }\n}\n"}, {"idx": "webquery-test-4", "doc": "What is the \"assert\" function?", "code": "assertassert(length >= 0); // die if length is negative.\nassert(length >= 0 && \"Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith\");\nassert((\"Length can't possibly be negative! Tell jsmith\", length >= 0));\nassertassert// BAD\nassert(x++);\n\n// GOOD\nassert(x); \nx++;\n\n// Watch out! Depends on the function:\nassert(foo());\n\n// Here's a safer way:\nint ret = foo();\nassert(ret);\n"}, {"idx": "webquery-test-5", "doc": "How to write a large buffer into a binary file in C++, fast?", "code": "#include <stdio.h>\nconst unsigned long long size = 8ULL*1024ULL*1024ULL;\nunsigned long long a[size];\n\nint main()\n{\n FILE* pFile;\n pFile = fopen(\"file.binary\", \"wb\");\n for (unsigned long long j = 0; j < 1024; ++j){\n //Some calculations to fill a[]\n fwrite(a, 1, size*sizeof(unsigned long long), pFile);\n }\n fclose(pFile);\n return 0;\n}\n#include <fstream>\n#include <chrono>\n#include <vector>\n#include <cstdint>\n#include <numeric>\n#include <random>\n#include <algorithm>\n#include <iostream>\n#include <cassert>\n\nstd::vector<uint64_t> GenerateData(std::size_t bytes)\n{\n assert(bytes % sizeof(uint64_t) == 0);\n std::vector<uint64_t> data(bytes / sizeof(uint64_t));\n std::iota(data.begin(), data.end(), 0);\n std::shuffle(data.begin(), data.end(), std::mt19937{ std::random_device{}() });\n return data;\n}\n\nlong long option_1(std::size_t bytes)\n{\n std::vector<uint64_t> data = GenerateData(bytes);\n\n auto startTime = std::chrono::high_resolution_clock::now();\n auto myfile = std::fstream(\"file.binary\", std::ios::out | std::ios::binary);\n myfile.write((char*)&data[0], bytes);\n myfile.close();\n auto endTime = std::chrono::high_resolution_clock::now();\n\n return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();\n}\n\nlong long option_2(std::size_t bytes)\n{\n std::vector<uint64_t> data = GenerateData(bytes);\n\n auto startTime = std::chrono::high_resolution_clock::now();\n FILE* file = fopen(\"file.binary\", \"wb\");\n fwrite(&data[0], 1, bytes, file);\n fclose(file);\n auto endTime = std::chrono::high_resolution_clock::now();\n\n return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();\n}\n\nlong long option_3(std::size_t bytes)\n{\n std::vector<uint64_t> data = GenerateData(bytes);\n\n std::ios_base::sync_with_stdio(false);\n auto startTime = std::chrono::high_resolution_clock::now();\n auto myfile = std::fstream(\"file.binary\", std::ios::out | std::ios::binary);\n myfile.write((char*)&data[0], bytes);\n myfile.close();\n auto endTime = std::chrono::high_resolution_clock::now();\n\n return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();\n}\n\nint main()\n{\n const std::size_t kB = 1024;\n const std::size_t MB = 1024 * kB;\n const std::size_t GB = 1024 * MB;\n\n for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << \"option1, \" << size / MB << \"MB: \" << option_1(size) << \"ms\" << std::endl;\n for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << \"option2, \" << size / MB << \"MB: \" << option_2(size) << \"ms\" << std::endl;\n for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << \"option3, \" << size / MB << \"MB: \" << option_3(size) << \"ms\" << std::endl;\n\n return 0;\n}\nstd::fstreamstd::fstream"}, {"idx": "webquery-test-6", "doc": "What is the difference between \"long\", \"long long\", \"long int\", and \"long long int\" in C++?", "code": "longlonglonglonglonglong longlong long3.9.1 Fundamental types7.1.6.2 Simple type specifiers7.1.6.2 Simple type specifiersSpecifier(s) Type\n------------- -------------\nlong long int long long int\nlong long long long int\nlong int long int\nlong long int\nlonglonglonglong1.2 Normative references1.2 Normative referenceslong doublelong double"}, {"idx": "webquery-test-1", "doc": "Are there benefits of passing by pointer over passing by reference in C++?", "code": "nothingstring s = &str1 + &str2;string s = &str1 + &str2;"}, {"idx": "webquery-test-2", "doc": "std::lock_guard or std::scoped_lock?", "code": "scoped_lockscoped_lockscoped_lockscoped_locklock_guard"}, {"idx": "webquery-test-3", "doc": "Why use iterators instead of array indices?", "code": "T elem = some_vector[i];\noperator[](std::size_t)size()std::for_each()std::for_each()"}, {"idx": "webquery-test-4", "doc": "How to pass objects to functions in C++?", "code": "constconstconststd::optionalstd::optionalconstconstconstconstconstconst"}, {"idx": "webquery-test-5", "doc": "insert vs emplace vs operator[] in c++ map", "code": "operator[]operator[]operator[]operator[]insertinsertinsertinsertinsertoperator[]operator[]operator[]// assume m is std::map<int,int> already has an element with key 5 and value 0\nm[5] = 10; // postcondition: m[5] == 10\nm.insert(std::make_pair(5,15)); // m[5] is still 10\ninsertinsertinsertinsertinsertK t; V u;\nstd::map<K,V> m; // std::map<K,V>::value_type is std::pair<const K,V>\n\nm.insert( std::pair<const K,V>(t,u) ); // 1\nm.insert( std::map<K,V>::value_type(t,u) ); // 2\nm.insert( std::make_pair(t,u) ); // 3\nstd::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::pair<const K,V>std::make_pairstd::make_pairtemplate <typename T, typename U>\nstd::pair<T,U> make_pair(T const & t, U const & u );\nstd::make_pairstd::make_pairstd::make_pairstd::make_pairstd::make_pairstd::make_pairstd::make_pairm.insert( std::make_pair<const K,V>(t,u) ); // 4\ninsertinsertinsertinsertemplacem.emplace(t,u); // 5\nstd::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>std::pair<const K, V>emplace"}, {"idx": "webquery-test-6", "doc": "Count character occurrences in a string in C++", "code": "#include <algorithm>\n\nstd::string s = \"a_b_c\";\nstd::string::difference_type n = std::count(s.begin(), s.end(), '_');\n"}, {"idx": "webquery-test-7", "doc": "How to properly overload the << operator for an ostream?", "code": "namespace Math\n{\n class Matrix\n {\n public:\n\n [...]\n\n friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {\n [...]\n }\n };\n}\nMathMath"}, {"idx": "webquery-test-8", "doc": "Is it possible to use std::string in a constexpr?", "code": "std::stringconstexpr std::size_t n = std::string(\"hello, world\").size();\nstring_viewconstexpr std::string_view sv = \"hello, world\";\nstring_viewstring_viewstring_view"}, {"idx": "webquery-test-9", "doc": "C++ sorting and keeping track of indexes", "code": "C++#include <iostream>\n#include <vector>\n#include <numeric> // std::iota\n#include <algorithm> // std::sort, std::stable_sort\n\nusing namespace std;\n\ntemplate <typename T>\nvector<size_t> sort_indexes(const vector<T> &v) {\n\n // initialize original index locations\n vector<size_t> idx(v.size());\n iota(idx.begin(), idx.end(), 0);\n\n // sort indexes based on comparing values in v\n // using std::stable_sort instead of std::sort\n // to avoid unnecessary index re-orderings\n // when v contains elements of equal values \n stable_sort(idx.begin(), idx.end(),\n [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});\n\n return idx;\n}\nfor (auto i: sort_indexes(v)) {\n cout << v[i] << endl;\n}\n"}, {"idx": "webquery-test-1", "doc": "Running my program says \"bash: ./program Permission denied\"", "code": "chmod u+x program_namechmod u+x program_namechmod u+x namenoexecnoexec"}, {"idx": "webquery-test-2", "doc": "What is memory fragmentation?", "code": "----------------------------------\n| |\n----------------------------------\n----------------------------------\n|aaaabbccccccddeeee |\n----------------------------------\n----------------------------------\n| eeee |\n----------------------------------\n----------------------------------\n|ffffffffffffffeeeeff |\n----------------------------------\n------------------------------------------------------...\n| eeeeffffffffffffffff \n------------------------------------------------------...\nmallocmallocAlloc"}, {"idx": "webquery-test-3", "doc": "How do I make CMake output into a 'bin' dir?", "code": "CMAKE_RUNTIME_OUTPUT_DIRECTORYset(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)\nset(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)\nset_target_properties( targets...\n PROPERTIES\n ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/lib\"\n LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/lib\"\n RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/bin\"\n)\n_[CONFIG]_[CONFIG]_[CONFIG]_[CONFIG]_[CONFIG]"}, {"idx": "webquery-test-4", "doc": "How to remove from a map while iterating it?", "code": "for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)\n{\n if (must_delete)\n {\n m.erase(it++); // or \"it = m.erase(it)\" since C++11\n }\n else\n {\n ++it;\n }\n}\nforfor (std::map<K,V>::iterator it = m.begin(); it != m.end(); ) { /* ... */ }\ndelete pdelete p"}, {"idx": "webquery-test-5", "doc": "How do I convert between big-endian and little-endian values in C++?", "code": "unsigned short _byteswap_ushort(unsigned short value);\nunsigned long _byteswap_ulong(unsigned long value);\nunsigned __int64 _byteswap_uint64(unsigned __int64 value);\nuint32_t __builtin_bswap32 (uint32_t x)\nuint64_t __builtin_bswap64 (uint64_t x)\n"}, {"idx": "webquery-test-6", "doc": "Why does an overridden function in the derived class hide other overloads of the base class?", "code": "BBBBBBBBBBBBBBBBBBBBclass Base {\n int x;\npublic:\n virtual void copy(Base* p) { x = p-> x; }\n};\n\nclass Derived : public Base{\n int xx;\npublic:\n virtual void copy(Derived* p) { xx = p->xx; Base::copy(p); }\n};\n\nvoid f(Base a, Derived b)\n{\n a.copy(&b); // ok: copy Base part of b\n b.copy(&a); // error: copy(Base*) is hidden by copy(Derived*)\n}\n"}, {"idx": "webquery-test-1", "doc": "What is std::decay and when it should be used?", "code": "std::atomicstd::decaydecay<T>::typedecay<T>::typestd::make_pairtemplate <class T1, class T2> \ninline pair<T1,T2> make_pair(T1 x, T2 y)\n{ \n return pair<T1,T2>(x, y); \n}\nstd::pair<std::string, int> p = make_pair(\"foo\", 0);\nT1T1decaytemplate <class T1, class T2> \ninline pair< typename decay<T1>::type, typename decay<T2>::type > \nmake_pair(T1&& x, T2&& y)\n{ \n return pair< typename decay<T1>::type, \n typename decay<T2>::type >(std::forward<T1>(x), \n std::forward<T2>(y)); \n}\nmake_pairmake_pairmake_pair"}, {"idx": "webquery-test-2", "doc": "Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?", "code": "foofoofoofoo&&***foofoofoofoofoofoo**&*foofoofoofoofoofoofoo&&&&foo&&foo&&foo&&foo&&foo***"}, {"idx": "webquery-test-3", "doc": "Replace part of a string with another string", "code": "findfindbool replace(std::string& str, const std::string& from, const std::string& to) {\n size_t start_pos = str.find(from);\n if(start_pos == std::string::npos)\n return false;\n str.replace(start_pos, from.length(), to);\n return true;\n}\n\nstd::string string(\"hello $name\");\nreplace(string, \"$name\", \"Somename\");\nreplaceAllvoid replaceAll(std::string& str, const std::string& from, const std::string& to) {\n if(from.empty())\n return;\n size_t start_pos = 0;\n while((start_pos = str.find(from, start_pos)) != std::string::npos) {\n str.replace(start_pos, from.length(), to);\n start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'\n }\n}\n"}, {"idx": "webquery-test-4", "doc": "How do you properly use namespaces in C++?", "code": "namespace MyNamespace\n{\n class MyClass\n {\n };\n}\nMyNamespace::MyClass* pClass = new MyNamespace::MyClass();\nusing namespace MyNamespace;\n\nMyClass* pClass = new MyClass();\n"}, {"idx": "webquery-test-5", "doc": "What is the correct way of using C++11's range-based for?", "code": "for (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (auto elem : container)vector<int> v = {1, 3, 5, 7, 9};\n\nfor (auto x : v)\n cout << x << ' ';\nintint1 3 5 7 9\n// A sample test class, with custom copy semantics.\nclass X\n{\npublic:\n X() \n : m_data(0) \n {}\n \n X(int data)\n : m_data(data)\n {}\n \n ~X() \n {}\n \n X(const X& other) \n : m_data(other.m_data)\n { cout << \"X copy ctor.\\n\"; }\n \n X& operator=(const X& other)\n {\n m_data = other.m_data; \n cout << \"X copy assign.\\n\";\n return *this;\n }\n \n int Get() const\n {\n return m_data;\n }\n \nprivate:\n int m_data;\n};\n\nostream& operator<<(ostream& os, const X& x)\n{\n os << x.Get();\n return os;\n}\nfor (auto x : v) {...}vector<X> v = {1, 3, 5, 7, 9};\n\ncout << \"\\nElements:\\n\";\nfor (auto x : v)\n{\n cout << x << ' ';\n}\n[... copy constructor calls for vector<X> initialization ...]\n\nElements:\nX copy ctor.\n1 X copy ctor.\n3 X copy ctor.\n5 X copy ctor.\n7 X copy ctor.\n9\nauto xauto xstd::stringconstconstvector<X> v = {1, 3, 5, 7, 9};\n\ncout << \"\\nElements:\\n\";\nfor (const auto& x : v)\n{ \n cout << x << ' ';\n}\n [... copy constructor calls for vector<X> initialization ...]\n\nElements:\n1 3 5 7 9\nintintfor (auto elem : container) \nconstfor (const auto& elem : container) \nforforforelemvector<int> v = {1, 3, 5, 7, 9};\nfor (auto x : v) // <-- capture by value (copy)\n x *= 10; // <-- a local temporary copy (\"x\") is modified,\n // *not* the original vector element.\n\nfor (auto x : v)\n cout << x << ' ';\n1 3 5 7 9\nfor (const auto& x : v)TestRangeFor.cpp:138:11: error: assignment of read-only reference 'x'\n x *= 10;\n ^\nconstvector<int> v = {1, 3, 5, 7, 9};\nfor (auto& x : v)\n x *= 10;\n\nfor (auto x : v)\n cout << x << ' ';\n10 30 50 70 90\nfor (auto& elem : container)for (auto& elem : container)vector<string> v = {\"Bob\", \"Jeff\", \"Connie\"};\n\n// Modify elements in place: use \"auto &\"\nfor (auto& x : v)\n x = \"Hi \" + x + \"!\";\n \n// Output elements (*observing* --> use \"const auto&\")\nfor (const auto& x : v)\n cout << x << ' ';\n \nHi Bob! Hi Jeff! Hi Connie!\nvector<bool>vector<bool> v = {true, false, false, true};\nfor (auto& x : v)\n x = !x;\nTestRangeFor.cpp:168:20: error: invalid initialization of non-const reference of\n type 'std::_Bit_reference&' from an rvalue of type 'std::_Bit_iterator::referen\nce {aka std::_Bit_reference}'\n for (auto& x : v)\n ^\nstd::vectorstd::vectorstd::vectorvector<bool>vector<bool>vector<bool>vector<bool>vector<bool>for (auto&& x : v)\n x = !x;\nvector<bool> v = {true, false, false, true};\n\n// Invert boolean status\nfor (auto&& x : v) // <-- note use of \"auto&&\" for proxy iterators\n x = !x;\n\n// Print new element values\ncout << boolalpha; \nfor (const auto& x : v)\n cout << x << ' ';\n \nfalse true true false\nfor (auto&& elem : container)for (auto&& elem : container)for (auto&& elem : container)for (const auto& elem : container)for (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (const auto& elem : container) // capture by const reference\nfor (auto elem : container)TTTTfor (auto&& elem : container)for (auto&& elem : container)for (auto&& elem : container)for (const auto& elem : container)\nfor (const auto& elem : container)\n"}, {"idx": "webquery-test-6", "doc": "Can the use of C++11's 'auto' improve performance?", "code": "autostd::map<Key, Val> m;\n// ...\n\nfor (std::pair<Key, Val> const& item : m) {\n // do stuff\n}\nstd::map<Key, Val>::value_typestd::map<Key, Val>::value_typestd::map<Key, Val>::value_typestd::pair<Key, Val> const& item = *iter;\nint const& i = 2.0; // perfectly OK\nconst Keyconst Keystd::pair<Key, Val> __tmp = *iter; // construct a temporary of the correct type\nstd::pair<Key, Val> const& item = __tmp; // then, take a reference to it\n__tmp__tmpfor (auto const& item : m) {\n // do stuff\n}\n"}, {"idx": "webquery-test-7", "doc": "Passing an array by reference", "code": "(&array)(&array)void foo(int * x);\nvoid foo(int x[100]);\nvoid foo(int x[]);\nint *void foo(int (&x)[100]);\nsizeofsizeofvoid foo(int & x[100]); // error\n"}, {"idx": "webquery-test-8", "doc": "Which kind of pointer do I use when?", "code": "shared_ptrshared_ptrshared_ptrshared_ptrshared_arrayshared_arrayintrusive_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrscoped_arrayscoped_arrayscoped_arrayscoped_arrayscoped_arrayscoped_arrayscoped_arrayscoped_arrayscoped_arraystd::auto_ptrstd::auto_ptrauto_ptrauto_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrif(!wptr.expired())\n something_assuming_the_resource_is_still_alive();\n"}, {"idx": "webquery-test-9", "doc": "std::vector performance regression when enabling C++11", "code": "-fltocontainer.push_back(Item());$ g++ -std=c++11 -O3 -flto regr.cpp && perf stat -r 10 ./a.out \n\n Performance counter stats for './a.out' (10 runs):\n\n 35.426793 task-clock # 0.986 CPUs utilized ( +- 1.75% )\n 4 context-switches # 0.116 K/sec ( +- 5.69% )\n 0 CPU-migrations # 0.006 K/sec ( +- 66.67% )\n 19,801 page-faults # 0.559 M/sec \n 99,028,466 cycles # 2.795 GHz ( +- 1.89% ) [77.53%]\n 50,721,061 stalled-cycles-frontend # 51.22% frontend cycles idle ( +- 3.74% ) [79.47%]\n 25,585,331 stalled-cycles-backend # 25.84% backend cycles idle ( +- 4.90% ) [73.07%]\n 141,947,224 instructions # 1.43 insns per cycle \n # 0.36 stalled cycles per insn ( +- 0.52% ) [88.72%]\n 37,697,368 branches # 1064.092 M/sec ( +- 0.52% ) [88.75%]\n 26,700 branch-misses # 0.07% of all branches ( +- 3.91% ) [83.64%]\n\n 0.035943226 seconds time elapsed ( +- 1.79% )\n\n\n\n$ g++ -std=c++98 -O3 -flto regr.cpp && perf stat -r 10 ./a.out \n\n Performance counter stats for './a.out' (10 runs):\n\n 35.510495 task-clock # 0.988 CPUs utilized ( +- 2.54% )\n 4 context-switches # 0.101 K/sec ( +- 7.41% )\n 0 CPU-migrations # 0.003 K/sec ( +-100.00% )\n 19,801 page-faults # 0.558 M/sec ( +- 0.00% )\n 98,463,570 cycles # 2.773 GHz ( +- 1.09% ) [77.71%]\n 50,079,978 stalled-cycles-frontend # 50.86% frontend cycles idle ( +- 2.20% ) [79.41%]\n 26,270,699 stalled-cycles-backend # 26.68% backend cycles idle ( +- 8.91% ) [74.43%]\n 141,427,211 instructions # 1.44 insns per cycle \n # 0.35 stalled cycles per insn ( +- 0.23% ) [87.66%]\n 37,366,375 branches # 1052.263 M/sec ( +- 0.48% ) [88.61%]\n 26,621 branch-misses # 0.07% of all branches ( +- 5.28% ) [83.26%]\n\n 0.035953916 seconds time elapsed \ng++ -std=c++11 -O3 -S regr.cppg++ -std=c++11 -O3 -S regr.cppg++ -std=c++11 -O3 -S regr.cppItem.aItem.a.L42:\n testq %rbx, %rbx # container$D13376$_M_impl$_M_finish\n je .L3 #,\n movl $0, (%rbx) #, container$D13376$_M_impl$_M_finish_136->a\n movl $0, 4(%rbx) #, container$D13376$_M_impl$_M_finish_136->b\n.L3:\n addq $8, %rbx #, container$D13376$_M_impl$_M_finish\n subq $1, %rbp #, ivtmp.106\n je .L41 #,\n.L14:\n cmpq %rbx, %rdx # container$D13376$_M_impl$_M_finish, container$D13376$_M_impl$_M_end_of_storage\n jne .L42 #,\n.L49:\n testq %rax, %rax # D.15772\n je .L26 #,\n movq 16(%rsp), %rdx # D.13379, D.13379\n movq %rdx, (%rax) # D.13379, *D.15772_60\n.L26:\n addq $8, %rax #, tmp75\n subq $1, %rbx #, ivtmp.117\n movq %rax, 40(%rsp) # tmp75, container.D.13376._M_impl._M_finish\n je .L48 #,\n.L28:\n movq 40(%rsp), %rax # container.D.13376._M_impl._M_finish, D.15772\n cmpq 48(%rsp), %rax # container.D.13376._M_impl._M_end_of_storage, D.15772\n movl $0, 16(%rsp) #, D.13379.a\n movl $0, 20(%rsp) #, D.13379.b\n jne .L49 #,\n leaq 16(%rsp), %rsi #,\n leaq 32(%rsp), %rdi #,\n call _ZNSt6vectorI4ItemSaIS0_EE19_M_emplace_back_auxIIS0_EEEvDpOT_ #\ncallleaq 16(%rsp), %rsi #,\nleaq 32(%rsp), %rdi #,\ncall _ZNSt6vectorI4ItemSaIS0_EE19_M_emplace_back_auxIIS0_EEEvDpOT_ #\nmovl $0, 16(%rsp) #, D.13379.a\nmovl $0, 20(%rsp) #, D.13379.b\ncallcallcall-finline-limit $ g++ -std=c++11 -O3 -finline-limit=105 regr.cpp && perf stat -r 10 ./a.out\n\n Performance counter stats for './a.out' (10 runs):\n\n 84.739057 task-clock # 0.993 CPUs utilized ( +- 1.34% )\n 8 context-switches # 0.096 K/sec ( +- 2.22% )\n 1 CPU-migrations # 0.009 K/sec ( +- 64.01% )\n 19,801 page-faults # 0.234 M/sec \n 266,809,312 cycles # 3.149 GHz ( +- 0.58% ) [81.20%]\n 206,804,948 stalled-cycles-frontend # 77.51% frontend cycles idle ( +- 0.91% ) [81.25%]\n 129,078,683 stalled-cycles-backend # 48.38% backend cycles idle ( +- 1.37% ) [69.49%]\n 183,130,306 instructions # 0.69 insns per cycle \n # 1.13 stalled cycles per insn ( +- 0.85% ) [85.35%]\n 38,759,720 branches # 457.401 M/sec ( +- 0.29% ) [85.43%]\n 24,527 branch-misses # 0.06% of all branches ( +- 2.66% ) [83.52%]\n\n 0.085359326 seconds time elapsed ( +- 1.31% )\n\n $ g++ -std=c++11 -O3 -finline-limit=106 regr.cpp && perf stat -r 10 ./a.out\n\n Performance counter stats for './a.out' (10 runs):\n\n 37.790325 task-clock # 0.990 CPUs utilized ( +- 2.06% )\n 4 context-switches # 0.098 K/sec ( +- 5.77% )\n 0 CPU-migrations # 0.011 K/sec ( +- 55.28% )\n 19,801 page-faults # 0.524 M/sec \n 104,699,973 cycles # 2.771 GHz ( +- 2.04% ) [78.91%]\n 58,023,151 stalled-cycles-frontend # 55.42% frontend cycles idle ( +- 4.03% ) [78.88%]\n 30,572,036 stalled-cycles-backend # 29.20% backend cycles idle ( +- 5.31% ) [71.40%]\n 140,669,773 instructions # 1.34 insns per cycle \n # 0.41 stalled cycles per insn ( +- 1.40% ) [88.14%]\n 38,117,067 branches # 1008.646 M/sec ( +- 0.65% ) [89.38%]\n 27,519 branch-misses # 0.07% of all branches ( +- 4.01% ) [86.16%]\n\n 0.038187580 seconds time elapsed ( +- 2.05% )\n-flto"}, {"idx": "webquery-test-1", "doc": "How can I declare and define multiple variables in one line using C++?", "code": "int column = 0, row = 0, index = 0;\n"}, {"idx": "webquery-test-2", "doc": "smart pointers (boost) explained", "code": "RAIIunique_ptrscoped_ptrshared_ptrweak_ptrintrusive_ptrunique_ptrunique_ptr<type> p(new type);\nunique_ptr<type> q(p); // not legal!\nunique_ptr<type> r(move(p)); // legal. p is now empty, but r owns the object\nunique_ptr<type> s(function_returning_a_unique_ptr()); // legal!\n"}, {"idx": "webquery-test-3", "doc": "Are members of a C++ struct initialized to 0 by default?", "code": "Snapshot s; // receives no initialization\nSnapshot s = {}; // value initializes all members\nstruct Parent { Snapshot s; };\nParent p; // receives no initialization\nParent p = {}; // value initializes all members\np.s.{x,y}struct Snapshot {\n int x;\n double y;\n Snapshot():x(0),y(0) { }\n // other ctors / functions...\n};\nx(), y()"}, {"idx": "webquery-test-4", "doc": "Accessing an array out of bounds gives no error, why?", "code": "std::vectorstd::vectorstd::vector"}, {"idx": "webquery-test-5", "doc": "What is the best way to concatenate two vectors?", "code": "AB.reserve( A.size() + B.size() ); // preallocate memory\nAB.insert( AB.end(), A.begin(), A.end() );\nAB.insert( AB.end(), B.begin(), B.end() );\n"}, {"idx": "webquery-test-6", "doc": "Can't use modulus on doubles?", "code": "%%#include <cmath>\n\nint main()\n{\n double x = 6.3;\n double y = 2.0;\n double z = std::fmod(x,y);\n\n}\n"}, {"idx": "webquery-test-7", "doc": "Is it better in C++ to pass by value or pass by reference-to-const?", "code": "charcharcharchar"}, {"idx": "webquery-test-1", "doc": "How to append a char to a std::string?", "code": "y += d;\n+="}, {"idx": "webquery-test-2", "doc": "make_unique and perfect forwarding", "code": "make_uniquestd::make_unique"}, {"idx": "webquery-test-3", "doc": "How to call erase with a reverse iterator", "code": "&*(reverse_iterator(i)) == &*(i - 1)\nm_CursorStack.erase( --(i.base()) );\nim_CursorStack.erase( std::next(i).base() );\nistd::advance(i, 1);\nm_CursorStack.erase( i.base() );\n"}, {"idx": "webquery-test-4", "doc": "Separating class code into a header and cpp file", "code": "#ifndef #ifndef // A2DD.h\n#ifndef A2DD_H\n#define A2DD_H\n\nclass A2DD\n{\n int gx;\n int gy;\n\npublic:\n A2DD(int x,int y);\n int getSum();\n\n};\n\n#endif\n// A2DD.cpp\n#include \"A2DD.h\"\n\nA2DD::A2DD(int x,int y)\n{\n gx = x;\n gy = y;\n}\n\nint A2DD::getSum()\n{\n return gx + gy;\n}\n\n \n"}, {"idx": "webquery-test-5", "doc": "Struct inheritance in C++", "code": "structstructstructstructstructstruct"}, {"idx": "webquery-test-6", "doc": "Why is it wrong to use std::auto_ptr<> with standard containers?", "code": "std::auto_ptrclass X\n{\n};\n\nstd::vector<std::auto_ptr<X> > vecX;\nvecX.push_back(new X);\n\nstd::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL.\nstd::unique_ptrstd::unique_ptrstd::unique_ptr"}, {"idx": "webquery-test-1", "doc": "Unresolved external symbol in object files", "code": "// A.hpp\nclass A\n{\npublic:\n void myFunc(); // Function declaration\n};\n\n// A.cpp\n\n// Function definition\nvoid A::myFunc()\n{\n // do stuff\n}\nA::void myFunc() { /* do stuff */ }void myFunc() { /* do stuff */ }"}, {"idx": "webquery-test-2", "doc": "How to enable C++11/C++0x support in Eclipse CDT?", "code": "-std=c++0x-std=c++0x-std=c++0x"}, {"idx": "webquery-test-3", "doc": "Lambda capture as const reference?", "code": "static_caststatic_cast[&best_string = static_cast<const std::string&>(best_string)](const string& s)\n{\n best_string = s; // fails\n};\nstd::as_const[&best_string = std::as_const(best_string)](const string& s)\n{\n best_string = s; // fails\n};\n"}, {"idx": "webquery-test-4", "doc": "What is the reason behind cbegin/cend?", "code": "std::vector<int> vec;\nstd::for_eachstd::for_each(vec.begin(), vec.end(), SomeFunctor());\nSomeFunctorSomeFunctorSomeFunctorconst std::vector<int> &vec_ref = vec;\nstd::for_each(vec_ref.begin(), vec_ref.end(), SomeFunctor());\ncbegin/cendstd::for_each(vec.cbegin(), vec.cend(), SomeFunctor());\nSomeFunctorSomeFunctorSomeFunctorSomeFunctorSomeFunctorstd::as_conststd::as_constfor(auto &item : std::as_const(vec))\nconst&"}, {"idx": "webquery-test-5", "doc": "Return type of '?:' (ternary conditional operator)", "code": "C++11?:"}, {"idx": "webquery-test-6", "doc": "Undefined reference to static class member", "code": "class Foo { /* ... */ };\n\nconst int Foo::MEMBER;\n\nint main() { /* ... */ }\n"}, {"idx": "webquery-test-7", "doc": "Is std::vector copying the objects with a push_back?", "code": "std::vector<T>::push_back()std::vector<T>::push_back()std::vector<T>::push_back()"}, {"idx": "webquery-test-1", "doc": "In STL maps, is it better to use map::insert than []?", "code": "map[key] = value;\nvaluevaluevaluevaluemap::insert()using std::cout; using std::endl;\ntypedef std::map<int, std::string> MyMap;\nMyMap map;\n// ...\nstd::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));\nif ( ! res.second ) {\n cout << \"key \" << key << \" already exists \"\n << \" with value \" << (res.first)->second << endl;\n} else {\n cout << \"created key \" << key << \" with value \" << value << endl;\n}\nmap[key] = value"}, {"idx": "webquery-test-2", "doc": "Why do you use typedef when declaring an enum in C++?", "code": "TokenType my_type;\nenum TokenType my_type;\n"}, {"idx": "webquery-test-3", "doc": "Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation?", "code": "write()write()std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)std::basic_streambuf<char>::xsputn(char const*, int)xsputnxsputnxsputnwrite"}, {"idx": "webquery-test-4", "doc": "How to build and use Google TensorFlow C++ api", "code": "tensorflow/coretensorflow/coreOpKernelOpKernel"}, {"idx": "webquery-test-5", "doc": "How do I install g++ for Fedora?", "code": "gcc-c++"}, {"idx": "webquery-test-6", "doc": "Pure virtual function with implementation", "code": "virtualvirtualvirtualvirtualvirtualclass B : public A {\n\n virtual void f() {\n // class B doesn't have anything special to do for f()\n // so we'll call A's\n\n // note that A's declaration of f() would have to be public \n // or protected to avoid a compile time problem\n\n A::f();\n }\n\n};\n"}, {"idx": "webquery-test-7", "doc": "c++11 Return value optimization or move?", "code": "Foo f()\n{\n Foo result;\n mangle(result);\n return result;\n}\nreturn"}, {"idx": "webquery-test-1", "doc": "How do I reverse a C++ vector?", "code": "std::reversestd::reverse#include <vector>\n#include <algorithm>\n\nint main() {\n std::vector<int> a;\n std::reverse(a.begin(), a.end());\n return 0;\n}\n"}, {"idx": "webquery-test-2", "doc": "Why do we require requires requires?", "code": "requiresrequiresrequiresrequiresrequiresrequiresrequiresrequiresrequiresrequires (foo)void bar() requires (foo)\n{\n //stuff\n}\nfoofoofoofoofoofoofoo"}, {"idx": "webquery-test-3", "doc": "Rounding up to the nearest multiple of a number", "code": "int roundUp(int numToRound, int multiple)\n{\n if (multiple == 0)\n return numToRound;\n\n int remainder = numToRound % multiple;\n if (remainder == 0)\n return numToRound;\n\n return numToRound + multiple - remainder;\n}\nint roundUp(int numToRound, int multiple)\n{\n if (multiple == 0)\n return numToRound;\n\n int remainder = abs(numToRound) % multiple;\n if (remainder == 0)\n return numToRound;\n\n if (numToRound < 0)\n return -(abs(numToRound) - remainder);\n else\n return numToRound + multiple - remainder;\n}\n"}, {"idx": "webquery-test-4", "doc": "How do I clear the std::queue efficiently?", "code": "void clear( std::queue<int> &q )\n{\n std::queue<int> empty;\n std::swap( q, empty );\n}\n"}, {"idx": "webquery-test-5", "doc": "Is it better to use std::memcpy() or std::copy() in terms to performance?", "code": "std::copystd::copymemcpymemcpymemcpymemcpymemcpymemcpymemcpystd::copy memcpy % increase\n6.11 6.29 2.86%\n6.09 6.28 3.03%\n6.10 6.29 3.02%\n6.08 6.27 3.03%\n6.08 6.27 3.03%\n-Ofast -march=native -funsafe-loop-optimizationsstd::copy memcpy % difference\n5.52 5.56 +0.72%\n5.56 5.55 -0.18%\n5.57 5.53 -0.72%\n5.57 5.52 -0.91%\n5.56 5.57 +0.18%\n5.56 5.57 +0.18%\n5.56 5.53 -0.54%\n5.53 5.57 +0.72%\n5.59 5.57 -0.36%\n5.57 5.56 -0.18%\nstd::copystd::copystd::copystd::copystd::copy memcpy % difference\n5.54 5.57 +0.54%\n5.50 5.53 +0.54%\n5.54 5.58 +0.72%\n5.50 5.57 +1.26%\n5.54 5.58 +0.72%\n5.54 5.57 +0.54%\n5.54 5.56 +0.36%\n5.54 5.58 +0.72%\n5.51 5.58 +1.25%\n5.54 5.57 +0.54%\nstd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copy"}, {"idx": "webquery-test-6", "doc": "Why is 'this' a pointer and not a reference?", "code": "thisthisthisthisthis"}, {"idx": "webquery-test-7", "doc": "printf with std::string?", "code": "printfprintfprintfstd::coutstd::coutstd::cout << \"Follow this command: \" << myString;\nc_str()c_str()c_str()#include <iostream>\n#include <string>\n#include <stdio.h>\n\nint main()\n{\n using namespace std;\n\n string myString = \"Press ENTER to quit program!\";\n cout << \"Come up and C++ me some time.\" << endl;\n printf(\"Follow this command: %s\", myString.c_str()); //note the use of c_str\n cin.get();\n\n return 0;\n}\nprintfprintfprintfprintfprintf"}, {"idx": "webquery-test-8", "doc": "shared_ptr to an array : should it be used?", "code": "shared_ptrshared_ptrshared_ptrshared_ptrshared_ptr<int[]> sp(new int[10]);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\nelement_typeusing element_type = remove_extent_t<T>;\noperator[] element_type& operator[](ptrdiff_t i) const;\n element_type& operator[](ptrdiff_t i) const;\n element_type& operator[](ptrdiff_t i) const;\n element_type& operator[](ptrdiff_t i) const;\n element_type& operator[](ptrdiff_t i) const;\n element_type& operator[](ptrdiff_t i) const;\nshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrtemplate< typename T >\nstruct array_deleter\n{\n void operator ()( T const * p)\n { \n delete[] p; \n }\n};\nstd::shared_ptr<int> sp(new int[10], array_deleter<int>());\nshared_ptrshared_ptrstd::default_deletestd::default_deletestd::default_deleteunique_ptrstd::unique_ptr<int[]> up(new int[10]); // this will correctly call delete[]\nshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrelement_type typedef typename remove_extent<T>::type element_type;\noperator[] element_type& operator[](ptrdiff_t i) const noexcept;\nunique_ptrunique_ptrunique_ptrunique_ptr template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n template<class Y> explicit shared_ptr(Y* p);\n"}, {"idx": "webquery-test-1", "doc": "How to initialise memory with new operator in C++?", "code": "new int[10]();\n(0)TT(expression-list)"}, {"idx": "webquery-test-2", "doc": "Static variables in member functions", "code": "class Aclass Aclass AAAAA o1, o2, o3;\no1.foo(); // i = 1\no2.foo(); // i = 2\no3.foo(); // i = 3\no1.foo(); // i = 4\n"}, {"idx": "webquery-test-3", "doc": "What is the idiomatic way in CMAKE to add the -fPIC compiler option?", "code": "set(CMAKE_POSITION_INDEPENDENT_CODE ON)\nadd_library(lib1 lib1.cpp)\nset_property(TARGET lib1 PROPERTY POSITION_INDEPENDENT_CODE ON)\nCMAKE_POSITION_INDEPENDENT_CODE"}, {"idx": "webquery-test-4", "doc": "C++ templates that accept only certain types", "code": "<type_traits>#include <type_traits>\n\ntemplate<typename T>\nclass observable_list {\n static_assert(std::is_base_of<list, T>::value, \"T must inherit from list\");\n // code here..\n};\nobservable_listobservable_listobservable_listobservable_listobservable_listobservable_listobservable_listobservable_liststatic_assert#include <type_traits>\n\ntemplate<typename...>\nstruct void_ {\n using type = void;\n};\n\ntemplate<typename... Args>\nusing Void = typename void_<Args...>::type;\n\ntemplate<typename T, typename = void>\nstruct has_const_iterator : std::false_type {};\n\ntemplate<typename T>\nstruct has_const_iterator<T, Void<typename T::const_iterator>> : std::true_type {};\n\nstruct has_begin_end_impl {\n template<typename T, typename Begin = decltype(std::declval<const T&>().begin()),\n typename End = decltype(std::declval<const T&>().end())>\n static std::true_type test(int);\n template<typename...>\n static std::false_type test(...);\n};\n\ntemplate<typename T>\nstruct has_begin_end : decltype(has_begin_end_impl::test<T>(0)) {};\n\ntemplate<typename T>\nclass observable_list {\n static_assert(has_const_iterator<T>::value, \"Must have a const_iterator typedef\");\n static_assert(has_begin_end<T>::value, \"Must have begin and end member functions\");\n // code here...\n};\n"}, {"idx": "webquery-test-5", "doc": "Does the default constructor initialize built-in types?", "code": "CCCCCclass C { \npublic:\n int x;\n};\nC::xC c; // Compiler-provided default constructor is used\n// Here `c.x` contains garbage\nxxC c = C(); // Does not use default constructor for `C()` part\n // Uses value-initialization feature instead\nassert(c.x == 0);\n\nC *pc = new C(); // Does not use default constructor for `C()` part\n // Uses value-initialization feature instead\nassert(pc->x == 0);\n()()()()C c = {}; // Does not use any `C` constructors at all. Same as C c{}; in C++11.\nassert(c.x == 0);\n\nC d{}; // C++11 style aggregate initialization.\nassert(d.x == 0);\n"}, {"idx": "webquery-test-6", "doc": "Programmatically get the cache line size?", "code": "/sys/devices/system/cpu/cpu0/cache/\ncoherency_line_size\nlevel\nnumber_of_sets\nphysical_line_partition\nshared_cpu_list\nshared_cpu_map\nsize\ntype\nways_of_associativity\ncoherency_line_size"}, {"idx": "webquery-test-1", "doc": "Using member variable in lambda capture list inside a member function", "code": "gridgridgridgridgridgridauto lambda = [this](){ std::cout << grid[0][0] << \"\\n\"; }\npuzzlevector<vector<int> > tmp(grid);\nauto lambda = [tmp](){}; // capture the local copy per copy\n"}, {"idx": "webquery-test-2", "doc": "Is the order of iterating through std::map known (and guaranteed by the standard)?", "code": "*begin()*begin()*begin()*begin()*begin()*begin()"}, {"idx": "webquery-test-3", "doc": "Rotating a point about another point (2D)", "code": "(cx,cy)POINT rotate_point(float cx,float cy,float angle,POINT p)\n{\n float s = sin(angle);\n float c = cos(angle);\n\n // translate point back to origin:\n p.x -= cx;\n p.y -= cy;\n\n // rotate point\n float xnew = p.x * c - p.y * s;\n float ynew = p.x * s + p.y * c;\n\n // translate point back:\n p.x = xnew + cx;\n p.y = ynew + cy;\n return p;\n}\n"}, {"idx": "webquery-test-4", "doc": "How does the Comma Operator work", "code": "keywords = \"and\", \"or\", \"not\", \"xor\";\n(((keywords = \"and\"), \"or\"), \"not\"), \"xor\";\nkeywords.operator =(\"and\")keywords.operator =(\"and\")keywords.operator =(\"and\").operator ,(\"or\").operator ,(\"not\").operator ,(\"xor\");\n"}, {"idx": "webquery-test-5", "doc": "What does \"Memory allocated at compile time\" really mean?", "code": "int array[100];\nintint array[] = { 1 , 2 , 3 , 4 };\nint a[4];\nint b[] = { 1 , 2 , 3 , 4 };\n\nint main()\n{}\na:\n .zero 16\nb:\n .long 1\n .long 2\n .long 3\n .long 4\nmain:\n pushq %rbp\n movq %rsp, %rbp\n movl $0, %eax\n popq %rbp\n ret\na"}, {"idx": "webquery-test-6", "doc": "Modulo operator with negative values", "code": "(-7/3) => -2\n-2 * 3 => -6\nso a%b => -1\n\n(7/-3) => -2\n-2 * -3 => 6\nso a%b => 1\n"}, {"idx": "webquery-test-7", "doc": "Converting an int to std::string", "code": "int i = 3;\nstd::string str = std::to_string(i);\n"}, {"idx": "webquery-test-1", "doc": "What's the difference between std::move and std::forward", "code": "std::movestd::movestd::forwardvoid overloaded( int const &arg ) { std::cout << \"by lvalue\\n\"; }\nvoid overloaded( int && arg ) { std::cout << \"by rvalue\\n\"; }\n\ntemplate< typename t >\n/* \"t &&\" with \"t\" being template param is special, and adjusts \"t\" to be\n (for example) \"int &\" or non-ref \"int\" so std::forward knows what to do. */\nvoid forwarding( t && arg ) {\n std::cout << \"via std::forward: \";\n overloaded( std::forward< t >( arg ) );\n std::cout << \"via std::move: \";\n overloaded( std::move( arg ) ); // conceptually this would invalidate arg\n std::cout << \"by simple passing: \";\n overloaded( arg );\n}\n\nint main() {\n std::cout << \"initial caller passes rvalue:\\n\";\n forwarding( 5 );\n std::cout << \"initial caller passes lvalue:\\n\";\n int x = 5;\n forwarding( x );\n}\nstatic_cast"}, {"idx": "webquery-test-2", "doc": "What happens when a computer program runs?", "code": "+---------+\n| stack | function-local variables, return addresses, return values, etc.\n| | often grows downward, commonly accessed via \"push\" and \"pop\" (but can be\n| | accessed randomly, as well; disassemble a program to see)\n+---------+\n| shared | mapped shared libraries (C libraries, math libs, etc.)\n| libs |\n+---------+\n| hole | unused memory allocated between the heap and stack \"chunks\", spans the\n| | difference between your max and min memory, minus the other totals\n+---------+\n| heap | dynamic, random-access storage, allocated with 'malloc' and the like.\n+---------+\n| bss | Uninitialized global variables; must be in read-write memory area\n+---------+\n| data | data segment, for globals and static variables that are initialized\n| | (can further be split up into read-only and read-write areas, with\n| | read-only areas being stored elsewhere in ROM on some systems)\n+---------+\n| text | program code, this is the actual executable code that is running.\n+---------+\n+-----------+ top of memory\n| extended | above the high memory area, and up to your total memory; needed drivers to\n| | be able to access it.\n+-----------+ 0x110000\n| high | just over 1MB->1MB+64KB, used by 286s and above.\n+-----------+ 0x100000\n| upper | upper memory area, from 640kb->1MB, had mapped memory for video devices, the\n| | DOS \"transient\" area, etc. some was often free, and could be used for drivers\n+-----------+ 0xA0000\n| USER PROC | user process address space, from the end of DOS up to 640KB\n+-----------+\n|command.com| DOS command interpreter\n+-----------+ \n| DOS | DOS permanent area, kept as small as possible, provided routines for display,\n| kernel | *basic* hardware access, etc.\n+-----------+ 0x600\n| BIOS data | BIOS data area, contained simple hardware descriptions, etc.\n+-----------+ 0x400\n| interrupt | the interrupt vector table, starting from 0 and going to 1k, contained \n| vector | the addresses of routines called when interrupts occurred. e.g.\n| table | interrupt 0x21 checked the address at 0x21*4 and far-jumped to that \n| | location to service the interrupt.\n+-----------+ 0x0\nnewnewnewint mul( int x, int y ) {\n return x * y; // this stores the result of MULtiplying the two variables \n // from the stack into the return value address previously \n // allocated, then issues a RET, which resets the stack frame\n // based on the arg list, and returns to the address set by\n // the CALLer.\n}\n\nint main() {\n int x = 2, y = 3; // these variables are stored on the stack\n mul( x, y ); // this pushes y onto the stack, then x, then a return address,\n // allocates space on the stack for a return value, \n // then issues an assembly CALL instruction.\n}\ngcc -S foo.cf( g( h( i ) ) ); \n"}, {"idx": "webquery-test-3", "doc": "What is Objective C++?", "code": ".mm"}, {"idx": "webquery-test-4", "doc": "Is there still a reason to use `int` in C++ code?", "code": "gsl::indexgsl::indexgsl::indexnamespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }namespace gsl { using index = ptrdiff_t; }ptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_tptrdiff_t"}, {"idx": "webquery-test-5", "doc": "How to print to console when using Qt", "code": "stderr#include<QDebug>\n\n//qInfo is qt5.5+ only.\nqInfo() << \"C++ Style Info Message\";\nqInfo( \"C Style Info Message\" );\n\nqDebug() << \"C++ Style Debug Message\";\nqDebug( \"C Style Debug Message\" );\n\nqWarning() << \"C++ Style Warning Message\";\nqWarning( \"C Style Warning Message\" );\n\nqCritical() << \"C++ Style Critical Error Message\";\nqCritical( \"C Style Critical Error Message\" );\n\n// qFatal does not have a C++ style method.\nqFatal( \"C Style Fatal Error Message\" );\nQT_NO_DEBUG_OUTPUTQTextStream& qStdOut()\n{\n static QTextStream ts( stdout );\n return ts;\n}\nqStdOut() << \"std out!\";\n"}, {"idx": "webquery-test-6", "doc": "How to determine the version of the C++ standard used by the compiler?", "code": "__cplusplus__cplusplus__cplusplusgccgcc199711L199711L199711L__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplus__cplusplusgccstd::copy_ifstd::copy_if"}, {"idx": "webquery-test-7", "doc": "Tool to track #include dependencies", "code": "-M"}, {"idx": "webquery-test-8", "doc": "C++: const reference, before vs after type-specifier", "code": "const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&const T&"}, {"idx": "webquery-test-9", "doc": "CMake: Project structure with unit tests", "code": "cd test && ctest -Ncd test && ctest -Ncd test && ctest -Ncmake ..cmake_minimum_required (VERSION 2.8)\nproject (TEST)\nadd_subdirectory (src) \nadd_subdirectory (test)\nenable_testing ()\nadd_test (NAME MyTest COMMAND Test)\nadd_library (Sqr sqr.cpp sqr.h)\nadd_executable (demo main.cpp)\ntarget_link_libraries (demo Sqr)\nadd_library (Sqr sqr.cpp sqr.h)\nadd_executable (demo main.cpp)\ntarget_link_libraries (demo Sqr)\n"}, {"idx": "webquery-test-10", "doc": "Why is it considered a bad practice to omit curly braces?", "code": "if(foo)\n // bar();\ndoSomethingElse();\nif(foo) bar();\n"}, {"idx": "webquery-test-11", "doc": "Meaning of acronym SSO in the context of std::string", "code": "mallocmallocmallocstd::stringstd::stringstd::stringstd::stringstd::stringstd::stringstd::string::size_typestd::string::size_typestd::string::size_typestd::string::size_typeclass string {\npublic:\n // all 83 member functions\nprivate:\n std::unique_ptr<char[]> m_data;\n size_type m_size;\n size_type m_capacity;\n std::array<char, 16> m_sso;\n};\nstd::stringstd::stringstd::stringstd::stringstd::stringclass string {\npublic:\n // all 83 member functions\nprivate:\n size_type m_size;\n union {\n class {\n // This is probably better designed as an array-like class\n std::unique_ptr<char[]> m_data;\n size_type m_capacity;\n } m_large;\n std::array<char, sizeof(m_large)> m_small;\n };\n};\n"}, {"idx": "webquery-test-12", "doc": "How to enable C++17 compiling in Visual Studio?", "code": "/std:c++14/std:c++14/std:c++20/std:c++latest"}, {"idx": "webquery-test-13", "doc": "When should I use std::thread::detach?", "code": "std::threadstd::threadt.join()t.join()joinjoinmainjoinjoinjoinjoin"}, {"idx": "webquery-test-1", "doc": "What does iterator->second mean?", "code": "std::vector<X>std::vector<X>std::vector<X>std::vector<X>std::mapstd::mapstd::mapstd::map<std::string, int> m = /* fill it */;\nauto it = m.begin();\n*it*itstd::pairstd::pairstd::pairstd::pairstd::pairstd::pairstd::pairstd::pairstd::pairstd::mapstd::mapstd::mapstd::mapstd::mapstd::mapstd::mapstd::map"}, {"idx": "webquery-test-2", "doc": "What happens to a detached thread when main() exits?", "code": "main()<atomic><atomic><atomic>*_at_thread_exit*_at_thread_exit*_at_thread_exitnotify_all()_at_thread_exit_at_thread_exit"}, {"idx": "webquery-test-3", "doc": "Thread pooling in C++11", "code": "ThreadPoolclass ThreadPool {\npublic:\n void Start();\n void QueueJob(const std::function<void()>& job);\n void Stop();\n void busy();\n\nprivate:\n void ThreadLoop();\n\n bool should_terminate = false; // Tells threads to stop looking for jobs\n std::mutex queue_mutex; // Prevents data races to the job queue\n std::condition_variable mutex_condition; // Allows threads to wait on new jobs or termination \n std::vector<std::thread> threads;\n std::queue<std::function<void()>> jobs;\n};\nThreadPool::Startnum_threadsvoid ThreadPool::Start() {\n const uint32_t num_threads = std::thread::hardware_concurrency(); // Max # of threads the system supports\n threads.resize(num_threads);\n for (uint32_t i = 0; i < num_threads; i++) {\n threads.at(i) = std::thread(ThreadLoop);\n }\n}\nThreadPool::ThreadLoopwhile (true)void ThreadPool::ThreadLoop() {\n while (true) {\n std::function<void()> job;\n {\n std::unique_lock<std::mutex> lock(queue_mutex);\n mutex_condition.wait(lock, [this] {\n return !jobs.empty() || should_terminate;\n });\n if (should_terminate) {\n return;\n }\n job = jobs.front();\n jobs.pop();\n }\n job();\n }\n}\nThreadPool::QueueJobvoid ThreadPool::QueueJob(const std::function<void()>& job) {\n {\n std::unique_lock<std::mutex> lock(queue_mutex);\n jobs.push(job);\n }\n mutex_condition.notify_one();\n}\nthread_pool->QueueJob([] { /* ... */ });\nThreadPool::busyvoid ThreadPool::busy() {\n bool poolbusy;\n {\n std::unique_lock<std::mutex> lock(queue_mutex);\n poolbusy = jobs.empty();\n }\n return poolbusy;\n}\nThreadPool::Stopvoid ThreadPool::Stop() {\n {\n std::unique_lock<std::mutex> lock(queue_mutex);\n should_terminate = true;\n }\n mutex_condition.notify_all();\n for (std::thread& active_thread : threads) {\n active_thread.join();\n }\n threads.clear();\n}\nstd::unique_lockstd::unique_lockstd::unique_lock"}, {"idx": "webquery-test-4", "doc": "C++ valarray vs. vector", "code": "valarrayvalarrayslicesliceslicesliceslicesliceslicevalarrayvalarray"}, {"idx": "webquery-test-5", "doc": "Naming convention - underscore in C++ and C# variables", "code": "private string _name;\npublic string Name\n{\n get { return this._name; }\n set { this._name = value; }\n}\npublic string Name { get; set; }\n"}, {"idx": "webquery-test-6", "doc": "Const before or const after?", "code": "constconst*****constvoid * function1(void)void * function1(void)void * function1(void)void * function1(void)"}, {"idx": "webquery-test-7", "doc": "How to get std::vector pointer to the raw data?", "code": "&something&something&something&something&something&something[0]&something[0]&something[0]&something[0]std::vectorstd::vectorstd::vector"}, {"idx": "webquery-test-8", "doc": "Can I hint the optimizer by giving the range of an integer?", "code": "gccgccif (value < 0 || value > 36) __builtin_unreachable();\n#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)\nassume(x >= 0 && x <= 10);\ngcc#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)\n\nint func(int x){\n assume(x >=0 && x <= 10);\n\n if (x > 11){\n return 2;\n }\n else{\n return 17;\n }\n}\nfunc(int):\n mov eax, 17\n ret\n#if defined(NDEBUG)\n#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)\n#else\n#include <cassert>\n#define assume(cond) assert(cond)\n#endif\nNDEBUGNDEBUGNDEBUGassertassertassert"}, {"idx": "webquery-test-1", "doc": "What does void mean in C, C++, and C#?", "code": "int myFunc(void)int myFunc(void)int myFunc(void)voidvoidvoid"}, {"idx": "webquery-test-2", "doc": "How do you exit from a void function in C++?", "code": "return;\nif (condition) return;\nvoid"}, {"idx": "webquery-test-3", "doc": "Using smart pointers for class members", "code": "unique_ptrunique_ptrDeviceSettingsSettingsSettingsstd::unique_ptrstd::unique_ptrgetDevice()#include <memory>\n\nclass Device {\n};\n\nclass Settings {\n std::unique_ptr<Device> device;\npublic:\n Settings(std::unique_ptr<Device> d) {\n device = std::move(d);\n }\n\n Device* getDevice() {\n return device.get();\n }\n};\n\nint main() {\n std::unique_ptr<Device> device(new Device());\n Settings settings(std::move(device));\n // ...\n Device *myDevice = settings.getDevice();\n // do something with myDevice...\n}\nnewnewdevicedevicedevicedevicedeviceSettingsSettingsSettingsSettingsSettingsSettings#include <memory>\n\nclass Device {\n};\n\nclass Settings {\n std::shared_ptr<Device> device;\npublic:\n Settings(std::shared_ptr<Device> const& d) {\n device = d;\n }\n\n std::shared_ptr<Device> getDevice() {\n return device;\n }\n};\n\nint main() {\n std::shared_ptr<Device> device = std::make_shared<Device>();\n Settings settings(device);\n // ...\n std::shared_ptr<Device> myDevice = settings.getDevice();\n // do something with myDevice...\n}\nweak_ptrweak_ptrweak_ptrweak_ptrweak_ptr"}, {"idx": "webquery-test-4", "doc": "What are the complexity guarantees of the standard containers?", "code": "vector<T> v; Make an empty vector. O(1)\nvector<T> v(n); Make a vector with N elements. O(n)\nvector<T> v(n, value); Make a vector with N elements, initialized to value. O(n)\nvector<T> v(begin, end); Make a vector and copy the elements from begin to end. O(n)\nv[i] Return (or set) the I'th element. O(1)\nv.at(i) Return (or set) the I'th element, with bounds checking. O(1)\nv.size() Return current number of elements. O(1)\nv.empty() Return true if vector is empty. O(1)\nv.begin() Return random access iterator to start. O(1)\nv.end() Return random access iterator to end. O(1)\nv.front() Return the first element. O(1)\nv.back() Return the last element. O(1)\nv.capacity() Return maximum number of elements. O(1)\nv.push_back(value) Add value to end. O(1) (amortized)\nv.insert(iterator, value) Insert value at the position indexed by iterator. O(n)\nv.pop_back() Remove value from end. O(1)\nv.assign(begin, end) Clear the container and copy in the elements from begin to end. O(n)\nv.erase(iterator) Erase value indexed by iterator. O(n)\nv.erase(begin, end) Erase the elements from begin to end. O(n)\n"}, {"idx": "webquery-test-5", "doc": "Using custom std::set comparator", "code": "auto cmp = [](int a, int b) { return ... };\nstd::set<int, decltype(cmp)> s;\nauto cmp = [](int a, int b) { return ... };\nstd::set<int, decltype(cmp)> s(cmp);\nbool cmp(int a, int b) {\n return ...;\n}\nstd::set<int, decltype(cmp)*> s(cmp);\nstd::set<int, decltype(&cmp)> s(&cmp);\n()struct cmp {\n bool operator() (int a, int b) const {\n return ...\n }\n};\n\n// ...\n// later\nstd::set<int, cmp> s;\nbool cmp(int a, int b) {\n return ...;\n}\nstd::integral_constant#include <type_traits>\nusing Cmp = std::integral_constant<decltype(&cmp), &cmp>;\nstd::set<X, Cmp> set;\n"}, {"idx": "webquery-test-6", "doc": "What do linkers do?", "code": "printf(\"Hello Kristina!\\n\");\nprintf"}, {"idx": "webquery-test-7", "doc": "Why should I avoid std::enable_if in function signatures", "code": "enable_if"}, {"idx": "webquery-test-8", "doc": "Should I pass an std::function by const-reference?", "code": "std::future<void> run_in_ui_thread( std::function<void()> )\nfuturestd::future<void> run_in_ui_thread( std::function<void()> ) // (A)\nstd::future<void> run_in_ui_thread( std::function<void()> const& ) // (B)\nrun_in_ui_thread( [=]{\n // code goes here\n} ).wait();\nstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionrun_in_ui_threadrun_in_ui_threadrun_in_ui_threadrun_in_ui_threadstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::function<> const&std::function<> const&std::function<> const&std::function"}, {"idx": "webquery-test-1", "doc": "How to run specific test cases in GoogleTest", "code": "--gtest_filter=Test_Cases1*--gtest_filter=Test_Cases1*--gtest_filter=Test_Cases1*--gtest_list_tests--gtest_list_tests"}, {"idx": "webquery-test-2", "doc": "TensorFlow, why was python the chosen language?", "code": "h1 = tf.nn.relu(tf.matmul(l1, W1) + b1)\nh2 = ...\nsess.run(eval_results)\n"}, {"idx": "webquery-test-3", "doc": "How can I reliably get an object's address when operator& is overloaded?", "code": "std::addressofconstconst"}, {"idx": "webquery-test-4", "doc": "Explain Morris inorder tree traversal without using stacks or recursion", "code": " X\n / \\\n Y Z\n / \\ / \\\nA B C D\nXXXXXXXXXX Y\n / \\\n A B\n \\\n X\n / \\\n (Y) Z\n / \\\n C D\n(Y)(Y) A\n \\\n Y\n / \\\n(A) B\n \\\n X\n / \\\n (Y) Z\n / \\\n C D\nAAAAABBBBB"}, {"idx": "webquery-test-5", "doc": "What is the difference between const_iterator and non-const iterator in the C++ STL?", "code": "const_iteratorconst_iteratorconstconst"}, {"idx": "webquery-test-6", "doc": "Differences between std::make_unique and std::unique_ptr with new", "code": "make_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_uniquemake_shared"}, {"idx": "webquery-test-7", "doc": "How does `void_t` work", "code": "has_member<A>::valuehas_member<A>::valuetemplate< class , class = void >\nstruct has_member;\n<A><A><A>has_membertemplate< class T >\nstruct has_member< T , void_t< decltype( T::member ) > > : true_type\n{ };\nA, voidA, voidA, voidTTTTTTTTvoid_t< decltype( T::member ) >void_t< decltype( T::member ) >decltypedecltypedecltypedecltypedecltypedecltypedecltypedecltypetemplate<>\nstruct has_member< A, void_t< decltype( A::member ) > > : true_type\n{ };\nvoid_t< decltype( A::member ) >template<>\nstruct has_member<A, void> : true_type\n{ };\nhas_member<A>::valuetemplate< class , class = int > // <-- int here instead of void\nstruct has_member : false_type\n{ };\n\ntemplate< class T >\nstruct has_member< T , void_t< decltype( T::member ) > > : true_type\n{ };\ntemplate<>\nstruct has_member<A, void> : true_type\n{ };\nhas_member<A>::valuehas_member<A>::value"}, {"idx": "webquery-test-8", "doc": "Why use prefixes on member variables in C++ classes", "code": "MyClass::MyClass(int numItems)\n{\n mNumItems = numItems;\n for (int iItem = 0; iItem < mNumItems; iItem++)\n {\n Item *pItem = new Item();\n itemList[iItem] = pItem;\n }\n}\nfor (int i = 0; i < 100; i++)\n for (int j = 0; j < 5; j++)\n list[i].score += other[j].score;\nfor (int iCompany = 0; iCompany < numCompanies; iCompany++)\n for (int iUser = 0; iUser < numUsers; iUser++)\n companyList[iCompany].score += userList[iUser].score;\nthis->this->this->"}, {"idx": "webquery-test-1", "doc": "Why can't I forward-declare a class in a namespace using double colons?", "code": "class Namespace::Class;Namespace::ClassNamespaceNamespacenamespace Namespace\n{\n};\n\nclass Namespace::Class;\nnamespace Namespace\n{\n class Class;\n};\n"}, {"idx": "webquery-test-2", "doc": "What are the advantages of using nullptr?", "code": "void f(char const *ptr);\nvoid f(int v);\n\nf(NULL); //which function will be called?\nf(char const *)f(char const *)nullptrf(nullptr); //first function is called\nnullptrtemplate<typename T, T *ptr>\nstruct something{}; //primary template\n\ntemplate<>\nstruct something<nullptr_t, nullptr>{}; //partial specialization for nullptr\nnullptrnullptrtemplate<typename T>\nvoid f(T *ptr); //function to handle non-nullptr argument\n\nvoid f(nullptr_t); //an overload to handle nullptr argument!!!\nNULLNULLNULLNULL"}, {"idx": "webquery-test-3", "doc": "How do I use a custom deleter with a std::unique_ptr member?", "code": "createcreateBar* create();\nvoid destroy(Bar*);\nFooclass Foo {\n\n std::unique_ptr<Bar, void(*)(Bar*)> ptr_;\n\n // ...\n\npublic:\n\n Foo() : ptr_(create(), destroy) { /* ... */ }\n\n // ...\n};\ndestroy"}, {"idx": "webquery-test-4", "doc": "GoogleTest: How to skip a test?", "code": "DISABLED_DISABLED_// Tests that Foo does Abc.\nTEST(FooTest, DISABLED_DoesAbc) { ... }\n\nclass DISABLED_BarTest : public testing::Test { ... };\n\n// Tests that Bar does Xyz.\nTEST_F(DISABLED_BarTest, DoesXyz) { ... }\nGTEST_SKIP()TEST(SkipTest, DoesSkip) {\n GTEST_SKIP() << \"Skipping single test\";\n EXPECT_EQ(0, 1); // Won't fail; it won't be executed\n}\n\nclass SkipFixture : public ::testing::Test {\n protected:\n void SetUp() override {\n GTEST_SKIP() << \"Skipping all tests for this fixture\";\n }\n};\n\n// Tests for SkipFixture won't be executed.\nTEST_F(SkipFixture, SkipsOneTest) {\n EXPECT_EQ(5, 7); // Won't fail\n}\n"}, {"idx": "webquery-test-5", "doc": "Is there any overhead to declaring a variable within a loop? (C++)", "code": "var"}, {"idx": "webquery-test-6", "doc": "Does delete on a pointer to a subclass call the base class destructor?", "code": "class A\n{\n char *someHeapMemory;\npublic:\n A() : someHeapMemory(new char[1000]) {}\n ~A() { delete[] someHeapMemory; }\n};\n\nclass B\n{\n A* APtr;\npublic:\n B() : APtr(new A()) {}\n ~B() { delete APtr; }\n};\n\nclass C\n{\n A Amember;\npublic:\n C() : Amember() {}\n ~C() {} // A is freed / destructed automatically.\n};\n\nint main()\n{\n B* BPtr = new B();\n delete BPtr; // Calls ~B() which calls ~A() \n C *CPtr = new C();\n delete CPtr;\n B b;\n C c;\n} // b and c are freed/destructed automatically\nauto_ptrauto_ptrauto_ptrclass A\n{\n shared_array<char> someHeapMemory;\npublic:\n A() : someHeapMemory(new char[1000]) {}\n ~A() { } // someHeapMemory is delete[]d automatically\n};\n\nclass B\n{\n shared_ptr<A> APtr;\npublic:\n B() : APtr(new A()) {}\n ~B() { } // APtr is deleted automatically\n};\n\nint main()\n{\n shared_ptr<B> BPtr = new B();\n} // BPtr is deleted automatically\n"}, {"idx": "webquery-test-7", "doc": "C++ static virtual members?", "code": "Object::GetTypeInformation()"}, {"idx": "webquery-test-8", "doc": "What happens to global and static variables in a shared library when it is dynamically linked?", "code": "staticexternexternextern#ifdef COMPILING_THE_DLL\n#define MY_DLL_EXPORT extern \"C\" __declspec(dllexport)\n#else\n#define MY_DLL_EXPORT extern \"C\" __declspec(dllimport)\n#endif\n\nMY_DLL_EXPORT int my_global;\n.so.so.soLoadLibrary()LoadLibrary()LoadLibrary()LoadLibrary()LoadLibrary()LoadLibrary()LoadLibrary()LoadLibrary()"}, {"idx": "webquery-test-9", "doc": "When should I use C++14 automatic return type deduction?", "code": "autoautoauto"}, {"idx": "webquery-test-10", "doc": "Checking if a folder exists (and creating folders) in Qt, C++", "code": "QDir(\"Folder\").exists();\nQDir().mkdir(\"MyFolder\");\n"}, {"idx": "webquery-test-11", "doc": "What is this crazy C++11 syntax ==> struct : bar {} foo {};?", "code": "struct foo { virtual void f() = 0; }; // normal abstract type\nfoo obj;\n// error: cannot declare variable 'obj' to be of abstract type 'foo'\nstruct foo { foo() { cout << \"!\"; } }; // just a definition\n\nstruct foo { foo() { cout << \"!\"; } } instance; // so much more\n// Output: \"!\"\nstruct { virtual void f() = 0; } instance; // unnamed abstract type\n// error: cannot declare variable 'instance' to be of abstract type '<anonymous struct>'\ninstanceinstancestruct {} foo;\nstruct bar {}; // base UDT\nstruct : bar {} foo; // anonymous derived UDT, and instance thereof\nint x{0};\nint x{};\nstruct : bar {} foo {};\n"}, {"idx": "webquery-test-1", "doc": "Efficient way to return a std::vector in c++", "code": "std::vector<X> f();\nstd::vector"}, {"idx": "webquery-test-2", "doc": "std::function and std::bind: what are they, and when should they be used?", "code": "std::bindff(a,b,c);\ng(a,b) := f(a, 4, b);\nggstd::bindstd::bindauto g = bind(f, _1, 4, _2);\n// raise every value in vec to the power of 7\nstd::transform(vec.begin(), vec.end(), some_output, std::bind(std::pow, _1, 7));\npowbindauto memcpy_with_the_parameters_in_the_right_flipping_order = bind(memcpy, _2, _1, _3);\nnot2(bind(less<T>, _2, _1));\nstd::less_equalstd::less_equalstd::less_equal"}, {"idx": "webquery-test-3", "doc": "initialize a vector to zeros C++/C++11", "code": "std::vector<int> vector1(length, 0);\nstd::vector<double> vector2(length, 0.0);\n"}, {"idx": "webquery-test-4", "doc": "Is short-circuiting logical operators mandated? And evaluation order?", "code": "||||a && b\na || b\na ? b : c\na , b\n||||"}, {"idx": "webquery-test-5", "doc": "print call stack in C or C++", "code": "void *"}, {"idx": "webquery-test-6", "doc": "Purpose of returning by const value?", "code": "+(a + b).expensive();\n"}, {"idx": "webquery-test-7", "doc": "Why is processing an unsorted array the same speed as processing a sorted array with modern x86-64 clang?", "code": "-O3-O3-O3-O3sum += data[c] & -(data[c] >= 128);\nsumdatadatadatadatadata"}, {"idx": "webquery-test-8", "doc": "C++ semantics of `static const` vs `const`", "code": "constconstconstconstconstconstconst"}, {"idx": "webquery-test-9", "doc": "while (1) Vs. for (;;) Is there a speed difference?", "code": "$ perl -MO=Concise -e 'for(;;) { print \"foo\\n\" }'\na <@> leave[1 ref] vKP/REFC ->(end)\n1 <0> enter ->2\n2 <;> nextstate(main 2 -e:1) v ->3\n9 <2> leaveloop vK/2 ->a\n3 <{> enterloop(next->8 last->9 redo->4) v ->4\n- <@> lineseq vK ->9\n4 <;> nextstate(main 1 -e:1) v ->5\n7 <@> print vK ->8\n5 <0> pushmark s ->6\n6 <$> const[PV \"foo\\n\"] s ->7\n8 <0> unstack v ->4\n-e syntax OK\n\n$ perl -MO=Concise -e 'while(1) { print \"foo\\n\" }'\na <@> leave[1 ref] vKP/REFC ->(end)\n1 <0> enter ->2\n2 <;> nextstate(main 2 -e:1) v ->3\n9 <2> leaveloop vK/2 ->a\n3 <{> enterloop(next->8 last->9 redo->4) v ->4\n- <@> lineseq vK ->9\n4 <;> nextstate(main 1 -e:1) v ->5\n7 <@> print vK ->8\n5 <0> pushmark s ->6\n6 <$> const[PV \"foo\\n\"] s ->7\n8 <0> unstack v ->4\n-e syntax OK\n#include <stdio.h>\n\nvoid t_while() {\n while(1)\n printf(\"foo\\n\");\n}\n\nvoid t_for() {\n for(;;)\n printf(\"foo\\n\");\n}\n\n .file \"test.c\"\n .section .rodata\n.LC0:\n .string \"foo\"\n .text\n.globl t_while\n .type t_while, @function\nt_while:\n.LFB2:\n pushq %rbp\n.LCFI0:\n movq %rsp, %rbp\n.LCFI1:\n.L2:\n movl $.LC0, %edi\n call puts\n jmp .L2\n.LFE2:\n .size t_while, .-t_while\n.globl t_for\n .type t_for, @function\nt_for:\n.LFB3:\n pushq %rbp\n.LCFI2:\n movq %rsp, %rbp\n.LCFI3:\n.L5:\n movl $.LC0, %edi\n call puts\n jmp .L5\n.LFE3:\n .size t_for, .-t_for\n .section .eh_frame,\"a\",@progbits\n.Lframe1:\n .long .LECIE1-.LSCIE1\n.LSCIE1:\n .long 0x0\n .byte 0x1\n .string \"zR\"\n .uleb128 0x1\n .sleb128 -8\n .byte 0x10\n .uleb128 0x1\n .byte 0x3\n .byte 0xc\n .uleb128 0x7\n .uleb128 0x8\n .byte 0x90\n .uleb128 0x1\n .align 8\n.LECIE1:\n.LSFDE1:\n .long .LEFDE1-.LASFDE1\n.LASFDE1:\n .long .LASFDE1-.Lframe1\n .long .LFB2\n .long .LFE2-.LFB2\n .uleb128 0x0\n .byte 0x4\n .long .LCFI0-.LFB2\n .byte 0xe\n .uleb128 0x10\n .byte 0x86\n .uleb128 0x2\n .byte 0x4\n .long .LCFI1-.LCFI0\n .byte 0xd\n .uleb128 0x6\n .align 8\n.LEFDE1:\n.LSFDE3:\n .long .LEFDE3-.LASFDE3\n.LASFDE3:\n .long .LASFDE3-.Lframe1\n .long .LFB3\n .long .LFE3-.LFB3\n .uleb128 0x0\n .byte 0x4\n .long .LCFI2-.LFB3\n .byte 0xe\n .uleb128 0x10\n .byte 0x86\n .uleb128 0x2\n .byte 0x4\n .long .LCFI3-.LCFI2\n .byte 0xd\n .uleb128 0x6\n .align 8\n.LEFDE3:\n .ident \"GCC: (Ubuntu 4.3.3-5ubuntu4) 4.3.3\"\n .section .note.GNU-stack,\"\",@progbits\n"}, {"idx": "webquery-test-10", "doc": "What does the thread_local mean in C++11?", "code": "strtokstrtokstrtokerrnoerrno"}, {"idx": "webquery-test-1", "doc": "What is the difference between packaged_task and async", "code": "//! sleeps for one second and returns 1\nauto sleep = [](){\n std::this_thread::sleep_for(std::chrono::seconds(1));\n return 1;\n};\npackaged_taskstd::packaged_task<int()> task(sleep);\n\nauto f = task.get_future();\ntask(); // invoke the function\n\n// You have to wait until task returns. Since task calls sleep\n// you will have to wait at least 1 second.\nstd::cout << \"You can see this after 1 second\\n\";\n\n// However, f.get() will be available, since task has already finished.\nstd::cout << f.get() << std::endl;\nstd::asyncstd::asyncstd::asyncauto f = std::async(std::launch::async, sleep);\nstd::cout << \"You can see this immediately!\\n\";\n\n// However, the value of the future will be available after sleep has finished\n// so f.get() can block up to 1 second.\nstd::cout << f.get() << \"This will be shown after a second!\\n\";\nasyncasyncstd::async(do_work1); // ~future blocks\nstd::async(do_work2); // ~future blocks\n\n/* output: (assuming that do_work* log their progress)\n do_work1() started;\n do_work1() stopped;\n do_work2() started;\n do_work2() stopped;\n*/\nfuture{\n auto pizza = std::async(get_pizza);\n /* ... */\n if(need_to_go)\n return; // ~future will block\n else\n eat(pizza.get());\n} \nasyncasyncasyncasyncstd::asyncstd::asyncstd::packaged_task<int(int,int)> task(...);\nauto f = task.get_future();\nstd::thread myThread(std::move(task),2,3);\n\nstd::cout << f.get() << \"\\n\";\npackaged_taskpackaged_taskstd::packaged_task<int(int,int)> task(...);\nauto f = task.get_future();\nstd::cout << f.get() << \"\\n\"; // oops!\ntask(2,3);\nstd::asyncstd::asyncstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_taskstd::packaged_task"}, {"idx": "webquery-test-2", "doc": "When to use std::forward to forward arguments?", "code": "template <typename T> void f(T && x)\n{\n g(std::forward<T>(x));\n}\n\ntemplate <typename ...Args> void f(Args && ...args)\n{\n g(std::forward<Args>(args)...);\n}\nT = U&T = U&T = U&T = U&T = U&T = U&"}, {"idx": "webquery-test-3", "doc": "Is there a way to specify how many characters of a string to print out using printf()?", "code": "printf (\"Here are the first 8 chars: %.8s\\n\", \"A string that is more than 8 chars\");\nprintf (\"Here are the first %d chars: %.*s\\n\", 8, 8, \"A string that is more than 8 chars\");\nprintf (\"Here are the first 8 chars: %*.*s\\n\",\n 8, 8, \"A string that is more than 8 chars\");\nprintf(\"Data: %*.*s Other info: %d\\n\", minlen, maxlen, string, info);\nprintf()"}, {"idx": "webquery-test-4", "doc": "bool to int conversion", "code": "int x = 4<5;\nboolboolfalsefalseboolboolboolboolboolboolboolbool_Bool_Bool_Bool_Bool_Bool_Boolboolboolboolboolbool"}, {"idx": "webquery-test-5", "doc": "In practice, why would different compilers compute different values of int x = ++i + ++i;?", "code": "int i = 1;\nint x = ++i + ++i;\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n5. read i as tmp2\n6. read i as tmp3\n7. add 1 to tmp3\n8. store tmp3 in i\n9. read i as tmp4\n10. add tmp2 and tmp4, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n6. read i as tmp3\n3. add 1 to tmp1\n7. add 1 to tmp3\n4. store tmp1 in i\n8. store tmp3 in i\n5. read i as tmp2\n9. read i as tmp4\n10. add tmp2 and tmp4, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n6. read i as tmp3\n3. add 1 to tmp1\n7. add 1 to tmp3\n8. store tmp3 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n6. read i as tmp3\n7. add 1 to tmp3\n8. store tmp3 in i\n10. add tmp3 and tmp3, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n5. read i as tmp2\n6. read i as tmp3\n7. add 1 to tmp3\n8. store tmp3 in i\n9. read i as tmp4\n10. add tmp2 and tmp4, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n6. read i as tmp3\n7. add 1 to tmp3\n8. store tmp3 in i\n5. read i as tmp2\n9. read i as tmp4\n10. add tmp2 and tmp4, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n6. read i as tmp3\n7. add 1 to tmp3\n8. store tmp3 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n6. read i as tmp1\n7. add 1 to tmp1\n8. store tmp1 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n4. store tmp1 in i\n7. add 1 to tmp1\n8. store tmp1 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3. add 1 to tmp1\n7. add 1 to tmp1\n8. store tmp1 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3+7. add 2 to tmp1\n8. store tmp1 in i\n5. read i as tmp2\n10. add tmp2 and tmp2, as tmp5\n11. store tmp5 in x\n1. store 1 in i\n2. read i as tmp1\n3+7. add 2 to tmp1\n8. store tmp1 in i\n10. add tmp1 and tmp1, as tmp5\n11. store tmp5 in x\n"}, {"idx": "webquery-test-6", "doc": "C++ convert from 1 char to string?", "code": "std::string s(1, c); std::cout << s << std::endl;\nstd::cout << std::string(1, c) << std::endl;\nstd::string s; s.push_back(c); std::cout << s << std::endl;\n"}, {"idx": "webquery-test-7", "doc": "How can I initialize base class member variables in derived class constructor?", "code": "aaaaaaaaaaclass A \n{\nprotected:\n A(int a, int b) : a(a), b(b) {} // Accessible to derived classes\n // Change \"protected\" to \"public\" to allow others to instantiate A.\nprivate:\n int a, b; // Keep these variables private in A\n};\n\nclass B : public A \n{\npublic:\n B() : A(0, 0) // Calls A's constructor, initializing a and b in A to 0.\n {\n } \n};\n"}, {"idx": "webquery-test-8", "doc": "How can I get a file's size in C++?", "code": "#include <fstream>\n\nstd::ifstream::pos_type filesize(const char* filename)\n{\n std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);\n return in.tellg(); \n}\n"}, {"idx": "webquery-test-9", "doc": "How to determine the Boost version on a system?", "code": "BOOST_VERSION"}, {"idx": "webquery-test-10", "doc": "How to avoid overflow in expr. A * B - C * D", "code": "A*BA*B - C*D = A(D+E) - (A+F)D\n = AD + AE - AD - DF\n = AE - DF\n ^smaller quantities E & F\n\nE = B - D (hence, far smaller than B)\nF = C - A (hence, far smaller than C)\n MAX * MAX - (MAX - 1) * (MAX + 1)\n A B C D\n\nE = B - D = -1\nF = C - A = -1\n\nAE - DF = {MAX * -1} - {(MAX + 1) * -1} = -MAX + MAX + 1 = 1\n"}, {"idx": "webquery-test-1", "doc": "What are the differences between -std=c++11 and -std=gnu++11?", "code": "-Wpedantic-std=c++11-std=c++11"}, {"idx": "webquery-test-2", "doc": "Parsing a comma-delimited std::string", "code": ",#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nint main()\n{\n std::string str = \"1,2,3,4,5,6\";\n std::vector<int> vect;\n\n std::stringstream ss(str);\n\n for (int i; ss >> i;) {\n vect.push_back(i); \n if (ss.peek() == ',')\n ss.ignore();\n }\n\n for (std::size_t i = 0; i < vect.size(); i++)\n std::cout << vect[i] << std::endl;\n}\n"}, {"idx": "webquery-test-3", "doc": "Benefits of header-only libraries", "code": "#include#include"}, {"idx": "webquery-test-4", "doc": "What is the advantage of using forwarding references in range-based for loops?", "code": "#include <vector>\n\nint main()\n{\n std::vector<bool> v(10);\n for (auto& e : v)\n e = true;\n}\nvector<bool>::referencevector<bool>::reference#include <vector>\n\nint main()\n{\n std::vector<bool> v(10);\n for (auto&& e : v)\n e = true;\n}\n#include <vector>\n\nint main()\n{\n std::vector<bool> v(10);\n // using auto&& so that I can handle the rvalue reference\n // returned for the vector<bool> case\n for (auto&& e : v)\n e = true;\n}\nautoautoauto"}, {"idx": "webquery-test-5", "doc": "How does std::forward work?", "code": "std::forwardstd::forwardstd::vector<T> vstd::vector<T> vvoid set(const std::vector<T> & v) { _v = v; }\nmakeAndFillVector()_v = makeAndFillVector();\nset()set(makeAndFillVector()); // set will still make a copy\nset()set(const std::vector<T> & lv) { _v = v; }\nset(std::vector<T> && rv) { _v = std::move(rv); }\nTTTTTtemplate<class T>\nvoid perfectSet(T && t);\nTstd::vector<T> v;\nperfectSet(v);\nvperfectSet(makeAndFillVector());\nset()set()template<class T>\nvoid perfectSet(T && t) {\n set(std::forward<T>(t));\n}\nvoid perfectSet(T && t) {\n set(t);\n set(t); // t still unchanged\n}\nvoid perfectSet(T && t) {\n set(std::forward<T>(t));\n set(t); // t is now empty\n}\ntttt"}, {"idx": "webquery-test-6", "doc": "CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found", "code": "CMake Error at ... (project):\n No CMAKE_C_COMPILER could be found.\n-- Configuring incomplete, errors occurred!\nSee also \".../CMakeFiles/CMakeOutput.log\".\nSee also \".../CMakeFiles/CMakeError.log\".\nCMake Error: your CXX compiler: \"CMAKE_CXX_COMPILER-NOTFOUND\" was not found.\nPlease set CMAKE_CXX_COMPILER to a valid compiler path or name.\n...\n-- Configuring incomplete, errors occurred!\n > rmdir /s /q VS2015\n > mkdir VS2015\n > cd VS2015\n > rmdir /s /q VS2015\n > mkdir VS2015\n > cd VS2015\n > cmake ..\n -- Building for: Visual Studio 14 2015\n ...\n > cmake ..\n -- Building for: Visual Studio 14 2015\n ...\n > cmake ..\n -- Building for: Visual Studio 14 2015\n ...\n > cmake ..\n -- Building for: Visual Studio 14 2015\n ...\n > cmake ..\n -- Building for: Visual Studio 14 2015\n ...\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\n > cmake --help\n > cmake -G \"Visual Studio 14 2015\" ..\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\[Version];InstallDirbashbashbashbashbashbashbashbashbashbashbashbashararararararar"}, {"idx": "webquery-test-7", "doc": "Is \"long long\" = \"long long int\" = \"long int long\" = \"int long long\"?", "code": "long static long const int x = 10;\nconstexprconstexprconstexpr long static long const int x = 10;\nsignedsignedconstexpr long static long const int signed x = 10;\nconst long const long static const int const signed x = 10;\n"}, {"idx": "webquery-test-8", "doc": "Should operator<< be implemented as a friend or as a member function?", "code": "#include <iostream>\n\nclass Paragraph\n{\n public:\n explicit Paragraph(std::string const& init)\n :m_para(init)\n {}\n\n std::string const& to_str() const\n {\n return m_para;\n }\n\n bool operator==(Paragraph const& rhs) const\n {\n return m_para == rhs.m_para;\n }\n bool operator!=(Paragraph const& rhs) const\n {\n // Define != operator in terms of the == operator\n return !(this->operator==(rhs));\n }\n bool operator<(Paragraph const& rhs) const\n {\n return m_para < rhs.m_para;\n }\n private:\n friend std::ostream & operator<<(std::ostream &os, const Paragraph& p);\n std::string m_para;\n};\n\nstd::ostream & operator<<(std::ostream &os, const Paragraph& p)\n{\n return os << p.to_str();\n}\n\n\nint main()\n{\n Paragraph p(\"Plop\");\n Paragraph q(p);\n\n std::cout << p << std::endl << (p == q) << std::endl;\n}\n"}, {"idx": "webquery-test-9", "doc": "How should one use std::optional?", "code": "std::optional<int> try_parse_int(std::string s)\n{\n //try to parse an int from the given string,\n //and return \"nothing\" if you fail\n}\nstd::optionalbool try_parse_int(std::string s, int& i);\nint* try_parse_int(std::string s); //return nullptr if fail\nclass Contact\n{\n std::optional<std::string> home_phone;\n std::optional<std::string> work_phone;\n std::optional<std::string> mobile_phone;\n};\nstd::unique_ptr<std::string>std::unique_ptr<std::string>template<typename Key, typename Value>\nclass Lookup\n{\n std::optional<Value> get(Key key);\n};\nLookup<std::string, std::string> location_lookup;\nstd::string location = location_lookup.get(\"waldo\").value_or(\"unknown\");\nstd::vector<std::pair<std::string, double>> search(\n std::string query,\n std::optional<int> max_count,\n std::optional<double> min_match_score);\nmax_countmax_count-1-1-1-1std::optional<int> find_in_string(std::string s, std::string query);\nssboost::optionalboost::optionalboost::optional"}, {"idx": "webquery-test-10", "doc": "Is it smart to replace boost::thread and boost::mutex with c++11 equivalents?", "code": "std::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncstd::asyncintintintintintintintvoid f1(std::unique_ptr<int>);\nstd::thread t1(f1,std::unique_ptr<int>(new int(42)));\n-std=c++0x"}, {"idx": "webquery-test-11", "doc": "Optimizing away a \"while(1);\" in C++0x", "code": "while (complicated_condition()) {\n x = complicated_but_externally_invisible_operation(x);\n}\ncomplex_io_operation();\ncout << \"Results:\" << endl;\ncout << x << endl;\ncomplex_io_operationcomplex_io_operation"}, {"idx": "webquery-test-1", "doc": "Is there auto type inferring in Java?", "code": "varvar list = new ArrayList<String>(); // infers ArrayList<String>\nvar stream = list.stream(); // infers Stream<String>\n"}, {"idx": "webquery-test-2", "doc": "Can a recursive function be inline?", "code": "inlineinlineinline int factorial(int n)\n{\n if (n <= 1)\n {\n return 1;\n }\n else\n {\n return n * factorial(n - 1);\n }\n}\n\nint f(int x)\n{\n return factorial(x);\n}\nint factorial(int n)\n{\n if (n <= 1)\n {\n return 1;\n }\n else\n {\n return n * factorial(n - 1);\n }\n}\n\nint f(int x)\n{\n if (x <= 1)\n {\n return 1;\n }\n else\n {\n int x2 = x - 1;\n if (x2 <= 1)\n {\n return x * 1;\n }\n else\n {\n int x3 = x2 - 1;\n if (x3 <= 1)\n {\n return x * x2 * 1;\n }\n else\n {\n return x * x2 * x3 * factorial(x3 - 1);\n }\n }\n }\n}\n"}, {"idx": "webquery-test-3", "doc": "Is it safe to parse a /proc/ file?", "code": "/proc/proc/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/uptime/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/net/tcp/proc/proc/proc/proc/proc/proc/net/tcp"}, {"idx": "webquery-test-4", "doc": "Superiority of unnamed namespace over static?", "code": "staticnamespacenamespace//legal code\nstatic int sample_function() { /* function body */ }\nstatic int sample_variable;\n//illegal code\nstatic class sample_class { /* class body */ };\nstatic struct sample_struct { /* struct body */ };\nnamespace//legal code\nnamespace \n{ \n class sample_class { /* class body */ };\n struct sample_struct { /* struct body */ };\n}\nnamespacenamespace"}, {"idx": "webquery-test-5", "doc": "Declaring pointers; asterisk on the left or right of the space between the type and name?", "code": "someType* somePtr;\nsomePtrsomePtrsomeType *somePtr;\nsomePtrsomePtrsomeType * somePtr"}, {"idx": "webquery-test-6", "doc": "Is the operation \"false < true\" well defined?", "code": "5.9truetruetrueboolean-literal:\n false\n true\n5.954.5false < false\nfalse < true\ntrue < false\ntrue < true\n0 < 0\n0 < 1\n1 < 0\n1 < 1\n"}, {"idx": "webquery-test-7", "doc": "How to display a dynamically allocated array in the Visual Studio debugger?", "code": "char *a = new char[10];\na,10\n"}, {"idx": "webquery-test-8", "doc": "Overloading member access operators ->, .*", "code": "->operator->operator->struct client\n { int a; };\n\nstruct proxy {\n client *target;\n client *operator->() const\n { return target; }\n};\n\nstruct proxy2 {\n proxy *target;\n proxy &operator->() const\n { return * target; }\n};\n\nvoid f() {\n client x = { 3 };\n proxy y = { & x };\n proxy2 z = { & y };\n\n std::cout << x.a << y->a << z->a; // print \"333\"\n}\n->*+++.*.*->->->->"}, {"idx": "webquery-test-1", "doc": "How can I catch a ctrl-c event?", "code": "signalsignal#include <signal.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n\nvoid my_handler(int s){\n printf(\"Caught signal %d\\n\",s);\n exit(1); \n\n}\n\nint main(int argc,char** argv)\n{\n\n struct sigaction sigIntHandler;\n\n sigIntHandler.sa_handler = my_handler;\n sigemptyset(&sigIntHandler.sa_mask);\n sigIntHandler.sa_flags = 0;\n\n sigaction(SIGINT, &sigIntHandler, NULL);\n\n pause();\n\n return 0; \n}\n"}, {"idx": "webquery-test-2", "doc": "Unresolved external symbol on static class members", "code": "inlineunsigned char test::X;\nunsigned char test::Y;\nunsigned char test::X = 4;\n"}, {"idx": "webquery-test-3", "doc": "Why can I use auto on a private type?", "code": "autotemplate <typename T>\nvoid fun(T t) {}\n\nint main() {\n Foo f;\n fun(f.Baz()); // ok\n}\n"}, {"idx": "webquery-test-1", "doc": "What platforms have something other than 8-bit char?", "code": "charcharCHAR_BIT == 8CHAR_BIT == 8CHAR_BITCHAR_BIT"}, {"idx": "webquery-test-2", "doc": "Initialize parent's protected members with initialization list (C++)", "code": "class Parent\n{\nprotected:\n Parent( const std::string& something ) : something( something )\n {}\n\n std::string something;\n}\n\nclass Child : public Parent\n{\nprivate:\n Child() : Parent(\"Hello, World!\")\n {\n }\n}\n"}, {"idx": "webquery-test-3", "doc": "C++ convert hex string to signed integer", "code": "std::stringstreamunsigned int x; \nstd::stringstream ss;\nss << std::hex << \"fffefffe\";\nss >> x;\n-65538#include <sstream>\n#include <iostream>\n\nint main() {\n unsigned int x; \n std::stringstream ss;\n ss << std::hex << \"fffefffe\";\n ss >> x;\n // output it as a signed type\n std::cout << static_cast<int>(x) << std::endl;\n}\nstd::stringstd::string s = \"0xfffefffe\";\nunsigned int x = std::stoul(s, nullptr, 16);\nlexical_cast<>lexical_cast<>try {\n unsigned int x = lexical_cast<int>(\"0x0badc0de\");\n} catch(bad_lexical_cast &) {\n // whatever you want to do...\n}\ntemplate<typename T2, typename T1>\ninline T2 lexical_cast(const T1 &in) {\n T2 out;\n std::stringstream ss;\n ss << in;\n ss >> out;\n return out;\n}\n// though this needs the 0x prefix so it knows it is hex\nunsigned int x = lexical_cast<unsigned int>(\"0xdeadbeef\"); \n"}, {"idx": "webquery-test-4", "doc": "How can I pass std::unique_ptr into a function", "code": "void MyFunc(unique_ptr<A> & arg)\n{\n cout << arg->GetVal() << endl;\n}\n\nint main(int argc, char* argv[])\n{\n unique_ptr<A> ptr = unique_ptr<A>(new A(1234));\n MyFunc(ptr);\n}\nvoid MyFunc(unique_ptr<A> arg)\n{\n cout << arg->GetVal() << endl;\n}\n\nint main(int argc, char* argv[])\n{\n unique_ptr<A> ptr = unique_ptr<A>(new A(1234));\n MyFunc(move(ptr));\n assert(ptr == nullptr)\n}\n"}, {"idx": "webquery-test-5", "doc": "what is the difference between const_iterator and iterator?", "code": "const_iteratorconst_iteratorconst_iteratorconst_iteratorconst_iteratorconst_iteratorstd::string"}, {"idx": "webquery-test-6", "doc": "How do you copy the contents of an array to a std::vector in C++ without looping?", "code": "vector<int> dataVec;\n\nint dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\nunsigned dataArraySize = sizeof(dataArray) / sizeof(int);\n\n// Method 1: Copy the array to the vector using back_inserter.\n{\n copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve\n{\n dataVec.reserve(dataVec.size() + dataArraySize);\n copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 3: Memcpy\n{\n dataVec.resize(dataVec.size() + dataArraySize);\n memcpy(&dataVec[dataVec.size() - dataArraySize], &dataArray[0], dataArraySize * sizeof(int));\n}\n\n// Method 4: vector::insert\n{\n dataVec.insert(dataVec.end(), &dataArray[0], &dataArray[dataArraySize]);\n}\n\n// Method 5: vector + vector\n{\n vector<int> dataVec2(&dataArray[0], &dataArray[dataArraySize]);\n dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());\n}\nvector<char> v(50); // Ensure there's enough space\nstrcpy(&v[0], \"prefer vectors to c arrays\");\n"}, {"idx": "webquery-test-7", "doc": "How to pass optional arguments to a method in C++?", "code": "void myfunc(int blah, int mode = 0)\n{\n if (mode == 0)\n do_something();\n else\n do_something_else();\n}\nmyfunc(10); // Mode will be set to default 0\nmyfunc(10, 1); // Mode will be set to 1\n"}, {"idx": "webquery-test-8", "doc": "What is the purpose of a single pound/hash sign (#) on its own line in the C/C++ preprocessor?", "code": "## new-line# new-line"}, {"idx": "webquery-test-9", "doc": "How does delete[] know it's an array?", "code": "delete[]delete[]Foo* foo = new Foo;\nfoofoodelete[] bar;\ndelete bar;\n"}, {"idx": "webquery-test-10", "doc": "Qt: How do I handle the event of the user pressing the 'X' (close) button?", "code": "QMainWindowQMainWindow#include <QCloseEvent>\nvoid MainWindow::closeEvent (QCloseEvent *event)\n{\n QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,\n tr(\"Are you sure?\\n\"),\n QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,\n QMessageBox::Yes);\n if (resBtn != QMessageBox::Yes) {\n event->ignore();\n } else {\n event->accept();\n }\n}\nQDialogQDialogQDialogvoid MyDialog::reject()\n{\n QMessageBox::StandardButton resBtn = QMessageBox::Yes;\n if (changes) {\n resBtn = QMessageBox::question( this, APP_NAME,\n tr(\"Are you sure?\\n\"),\n QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,\n QMessageBox::Yes);\n }\n if (resBtn == QMessageBox::Yes) {\n QDialog::reject();\n }\n}\n"}, {"idx": "webquery-test-1", "doc": "Difference between `const shared_ptr<T>` and `shared_ptr<const T>`?", "code": "shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<const T> p;shared_ptr<T> p; ---> T * p; : nothing is const\nconst shared_ptr<T> p; ---> T * const p; : p is const\nshared_ptr<const T> p; ---> const T * p; <=> T const * p; : *p is const\nconst shared_ptr<const T> p; ---> const T * const p; <=> T const * const p; : p and *p are const.\nweak_ptrweak_ptr"}, {"idx": "webquery-test-2", "doc": "Difference between CC, gcc and g++?", "code": "/usr/ucb"}, {"idx": "webquery-test-3", "doc": "What's the best way to iterate over two or more containers simultaneously", "code": "forforfor(unsigned i : indices(containerA)) {\n containerA[i] = containerB[i];\n}\nindicesforzipfor (auto& [a, b] : zip(containerA, containerB)) {\n a = b;\n}\nzipzipfor (auto&& items : zip(containerA, containerB))\n get<0>(items) = get<1>(items);\n"}, {"idx": "webquery-test-4", "doc": "Is effective C++ still effective?", "code": "#defines"}, {"idx": "webquery-test-5", "doc": "How many and which are the uses of \"const\" in C++?", "code": "ScopeGuard const& guard = MakeGuard(&cleanUpFunction);\nstruct ScopeGuard { \n ~ScopeGuard() { } // not virtual\n};\n\ntemplate<typename T> struct Derived : ScopeGuard { \n T t; \n Derived(T t):t(t) { }\n ~Derived() {\n t(); // call function\n }\n};\n\ntemplate<typename T> Derived<T> MakeGuard(T t) { return Derived<T>(t); }\nstruct SmartPtr {\n int getCopies() const { return mCopiesMade; }\n};\nstruct MyString {\n char * getData() { /* copy: caller might write */ return mData; }\n char const* getData() const { return mData; }\n};\nint main() {\n string const a = \"1234\";\n string const b = a;\n // outputs the same address for COW strings\n cout << (void*)&a[0] << \", \" << (void*)&b[0];\n}\nstd::stringstd::stringstd::stringstd::stringint main() {\n string const a = \"1234\";\n string b = a;\n // outputs different addresses!\n cout << (void*)&a[0] << \", \" << (void*)&b[0];\n}\nstruct MyClass {\n MyClass(MyClass const& that) { /* make copy of that */ }\n};\ndouble const PI = 3.1415;\nvoid PrintIt(Object const& obj) {\n // ...\n}\n"}, {"idx": "webquery-test-6", "doc": "What new capabilities do user-defined literals add to C++?", "code": "// C89:\nMyComplex z1 = { 1, 2 } ;\n\n// C99: You'll note I is a macro, which can lead\n// to very interesting situations...\ndouble complex z1 = 1 + 2*I;\n\n// C++:\nstd::complex<double> z1(1, 2) ;\n\n// C++11: You'll note that \"i\" won't ever bother\n// you elsewhere\nstd::complex<double> z1 = 1 + 2_i ;\nPoint p = 25_x + 13_y + 3_z ; // 3D point\ncss::Font::Size p0 = 12_pt ; // Ok\ncss::Font::Size p1 = 50_percent ; // Ok\ncss::Font::Size p2 = 15_px ; // Ok\ncss::Font::Size p3 = 10_em ; // Ok\ncss::Font::Size p4 = 15 ; // ERROR : Won't compile !\n1974/01/06AD\n ^ ^ ^\n\"1974-01-06\"_AD ; // ISO-like notation\n\"06/01/1974\"_AD ; // french-date-like notation\n\"jan 06 1974\"_AD ; // US-date-like notation\n19740106_AD ; // integer-date-like notation\n"}, {"idx": "webquery-test-7", "doc": "What is going on with 'gets(stdin)' on the site coderbyte?", "code": "gets(stdin)foo(input)foo(input)foo(input)foo(input)foo(input)foo(input)foo(input)stdinstdin"}, {"idx": "webquery-test-8", "doc": "What happens if I define a 0-size array in C/C++?", "code": "gcc -std=c99 -pedantic"}, {"idx": "webquery-test-9", "doc": "Cast to int vs floor", "code": "floor()floor()"}, {"idx": "webquery-test-10", "doc": "How do I compile a Visual Studio project from the command-line?", "code": "msbuild project.sln /Flags...\nvcexpress project.sln /build /Flags...\nos.system(\"msbuild project.sln /p:Configuration=Debug\")\n"}, {"idx": "webquery-test-1", "doc": "When and why will a compiler initialise memory to 0xCD, 0xDD, etc. on malloc/free/new/delete?", "code": "Value Name Description \n------ -------- -------------------------\n0xCD Clean Memory Allocated memory via malloc or new but never \n written by the application. \n\n0xDD Dead Memory Memory that has been released with delete or free. \n It is used to detect writing through dangling pointers. \n\n0xED or Aligned Fence 'No man's land' for aligned allocations. Using a \n0xBD different value here than 0xFD allows the runtime\n to detect not only writing outside the allocation,\n but to also identify mixing alignment-specific\n allocation/deallocation routines with the regular\n ones.\n\n0xFD Fence Memory Also known as \"no mans land.\" This is used to wrap \n the allocated memory (surrounding it with a fence) \n and is used to detect indexing arrays out of \n bounds or other accesses (especially writes) past\n the end (or start) of an allocated block.\n\n0xFD or Buffer slack Used to fill slack space in some memory buffers \n0xFE (unused parts of `std::string` or the user buffer \n passed to `fread()`). 0xFD is used in VS 2005 (maybe \n some prior versions, too), 0xFE is used in VS 2008 \n and later.\n\n0xCC When the code is compiled with the /GZ option,\n uninitialized variables are automatically assigned \n to this value (at byte level). \n\n\n// the following magic values are done by the OS, not the C runtime:\n\n0xAB (Allocated Block?) Memory allocated by LocalAlloc(). \n\n0xBAADF00D Bad Food Memory allocated by LocalAlloc() with LMEM_FIXED,but \n not yet written to. \n\n0xFEEEFEEE OS fill heap memory, which was marked for usage, \n but wasn't allocated by HeapAlloc() or LocalAlloc(). \n Or that memory just has been freed by HeapFree(). \n/*\n * The following values are non-zero, constant, odd, large, and atypical\n * Non-zero values help find bugs assuming zero filled data.\n * Constant values are good, so that memory filling is deterministic\n * (to help make bugs reproducible). Of course, it is bad if\n * the constant filling of weird values masks a bug.\n * Mathematically odd numbers are good for finding bugs assuming a cleared\n * lower bit.\n * Large numbers (byte values at least) are less typical and are good\n * at finding bad addresses.\n * Atypical values (i.e. not too often) are good since they typically\n * cause early detection in code.\n * For the case of no man's land and free blocks, if you store to any\n * of these locations, the memory integrity checker will detect it.\n *\n * _bAlignLandFill has been changed from 0xBD to 0xED, to ensure that\n * 4 bytes of that (0xEDEDEDED) would give an inaccessible address under 3gb.\n */\n\nstatic unsigned char _bNoMansLandFill = 0xFD; /* fill no-man's land with this */\nstatic unsigned char _bAlignLandFill = 0xED; /* fill no-man's land for aligned routines */\nstatic unsigned char _bDeadLandFill = 0xDD; /* fill free objects with this */\nstatic unsigned char _bCleanLandFill = 0xCD; /* fill new objects with this */\nstd::stringstd::stringstd::stringstd::string0xFD0xFD0xFD0xFD"}, {"idx": "webquery-test-2", "doc": "Passing references to pointers in C++", "code": "string s;\nstring* _s = &s;\nmyfunc(_s);\n"}, {"idx": "webquery-test-3", "doc": "how does array[100] = {0} set the entire array to 0?", "code": "char array[100] = {};\n"}, {"idx": "webquery-test-4", "doc": "C/C++ maximum stack size of program on mainstream OSes", "code": "ulimit -sulimit -sstd::stack<Node> dfs;\ndfs.push(start);\ndo {\n Node top = dfs.top();\n if (top is what we are looking for) {\n break;\n }\n dfs.pop();\n for (outgoing nodes from top) {\n dfs.push(outgoing node);\n }\n} while (!dfs.empty())\n"}, {"idx": "webquery-test-5", "doc": "How to convert boost path type to string?", "code": "myPath.string()"}, {"idx": "webquery-test-6", "doc": "Easiest way to flip a boolean value?", "code": "myVal = !myVal;\nswitch(wParam) {\n case VK_F11:\n flipVal = !flipVal;\n break;\n\n case VK_F12:\n otherVal = !otherVal;\n break;\n\n default:\n break;\n}\n"}, {"idx": "webquery-test-7", "doc": "What does 'const static' mean in C and C++?", "code": "constconstconstnamespacestatic const int sci = 0; // sci is explicitly static\nconst int ci = 1; // ci is implicitly static\nextern const int eci = 2; // eci is explicitly extern\nextern int ei = 3; // ei is explicitly extern\nint i = 4; // i is implicitly extern\nstatic int si = 5; // si is explicitly static\nstaticstaticstaticclassstaticstatic"}, {"idx": "webquery-test-8", "doc": "Passing variable arguments to another function that accepts a variable argument list", "code": "va_list#include <stdarg.h>\n\nstatic void exampleV(int b, va_list args);\n\nvoid exampleA(int a, int b, ...) // Renamed for consistency\n{\n va_list args;\n do_something(a); // Use argument a somehow\n va_start(args, b);\n exampleV(b, args);\n va_end(args);\n}\n\nvoid exampleB(int b, ...)\n{\n va_list args;\n va_start(args, b);\n exampleV(b, args);\n va_end(args);\n}\n\nstatic void exampleV(int b, va_list args)\n{\n ...whatever you planned to have exampleB do...\n ...except it calls neither va_start nor va_end...\n}\n"}, {"idx": "webquery-test-9", "doc": "C/C++ NaN constant (literal)?", "code": "NANNANstd::numeric_limits<double>::quiet_NaN()std::numeric_limits<double>::quiet_NaN()isnan()isnan()isnan()isnan()"}, {"idx": "webquery-test-10", "doc": "What is the meaning of the term arena in relation to memory?", "code": "char * arena = malloc(HUGE_NUMBER);\n\nunsigned int current = 0;\n\nvoid * my_malloc(size_t n) { current += n; return arena + current - n; }\n"}, {"idx": "webquery-test-11", "doc": "What is the difference between exit() and abort()?", "code": "abort()abort()abort()A a;\nvoid test() { \n static A b;\n A c;\n exit(0);\n}\naaaamain()main()main()main()struct exit_exception { \n int c; \n exit_exception(int c):c(c) { } \n};\n\nint main() {\n try {\n // put all code in here\n } catch(exit_exception& e) {\n exit(e.c);\n }\n}\nexit()exit()"}, {"idx": "webquery-test-1", "doc": "C++ wait for user input", "code": "getch()getch()getch()getch()getch()getch()getch()getch()getch()"}, {"idx": "webquery-test-2", "doc": "Why isn't vector<bool> a STL container?", "code": "vector<bool>operator[]operator[]operator[]operator[]operator[]dequedeque"}, {"idx": "webquery-test-3", "doc": "C++ where to initialize static const", "code": "class foo {\n static const string s; // Can never be initialized here.\n static const char* cs; // Same with C strings.\n\n static const int i = 3; // Integral types can be initialized here (*)...\n static const int j; // ... OR in cpp.\n};\n#include \"foo.h\"\nconst string foo::s = \"foo string\";\nconst char* foo::cs = \"foo C string\";\n// No definition for i. (*)\nconst int foo::j = 4;\nii"}, {"idx": "webquery-test-4", "doc": "Position of least significant bit that is set", "code": "unsigned int v; // find the number of trailing zeros in 32-bit v \nint r; // result goes here\nstatic const int MultiplyDeBruijnBitPosition[32] = \n{\n 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, \n 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9\n};\nr = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];\n"}, {"idx": "webquery-test-5", "doc": "Restore the state of std::cout after manipulating it", "code": "#include <iostream>#include <iostream>std::ios_base::fmtflags f( cout.flags() );\n\n//Your code here...\n\ncout.flags( f );\n"}, {"idx": "webquery-test-6", "doc": "Type erasure techniques", "code": "void*struct Class {\n struct vtable {\n void (*dtor)(Class*);\n void (*func)(Class*,double);\n } * vtbl\n};\nshared_ptr<void>shared_ptr<void>shared_ptr<void>{\n const shared_ptr<void> sp( new A );\n} // calls A::~A() here\nvoid*"}, {"idx": "webquery-test-1", "doc": "Explicit template instantiation - when is it used?", "code": "// StringAdapter.h\ntemplate<typename T>\nclass StringAdapter\n{\n public:\n StringAdapter(T* data);\n void doAdapterStuff();\n private:\n std::basic_string<T> m_data;\n};\ntypedef StringAdapter<char> StrAdapter;\ntypedef StringAdapter<wchar_t> WStrAdapter;\n// StringAdapter.cpp\n#include \"StringAdapter.h\"\n\ntemplate<typename T>\nStringAdapter<T>::StringAdapter(T* data)\n :m_data(data)\n{}\n\ntemplate<typename T>\nvoid StringAdapter<T>::doAdapterStuff()\n{\n /* Manipulate a string */\n}\n\n// Explicitly instantiate only the classes you want to be defined.\n// In this case I only want the template to work with characters but\n// I want to support both char and wchar_t with the same code.\ntemplate class StringAdapter<char>;\ntemplate class StringAdapter<wchar_t>;\n#include \"StringAdapter.h\"\n\n// Note: Main can not see the definition of the template from here (just the declaration)\n// So it relies on the explicit instantiation to make sure it links.\nint main()\n{\n StrAdapter x(\"hi There\");\n x.doAdapterStuff();\n}\n"}, {"idx": "webquery-test-2", "doc": "Choosing between std::map and std::unordered_map", "code": "mapmapmapmapmapmap"}, {"idx": "webquery-test-3", "doc": "Writing your own STL Container", "code": "iterator_categoryiterator_categoryiterator_categoryiterator_categoryiterator_categoryiterator_categorytemplate <class T, class A = std::allocator<T> >\nclass X {\npublic:\n typedef A allocator_type;\n typedef typename A::value_type value_type; \n typedef typename A::reference reference;\n typedef typename A::const_reference const_reference;\n typedef typename A::difference_type difference_type;\n typedef typename A::size_type size_type;\n\n class iterator { \n public:\n typedef typename A::difference_type difference_type;\n typedef typename A::value_type value_type;\n typedef typename A::reference reference;\n typedef typename A::pointer pointer;\n typedef std::random_access_iterator_tag iterator_category; //or another tag\n\n iterator();\n iterator(const iterator&);\n ~iterator();\n\n iterator& operator=(const iterator&);\n bool operator==(const iterator&) const;\n bool operator!=(const iterator&) const;\n bool operator<(const iterator&) const; //optional\n bool operator>(const iterator&) const; //optional\n bool operator<=(const iterator&) const; //optional\n bool operator>=(const iterator&) const; //optional\n\n iterator& operator++();\n iterator operator++(int); //optional\n iterator& operator--(); //optional\n iterator operator--(int); //optional\n iterator& operator+=(size_type); //optional\n iterator operator+(size_type) const; //optional\n friend iterator operator+(size_type, const iterator&); //optional\n iterator& operator-=(size_type); //optional \n iterator operator-(size_type) const; //optional\n difference_type operator-(iterator) const; //optional\n\n reference operator*() const;\n pointer operator->() const;\n reference operator[](size_type) const; //optional\n };\n class const_iterator {\n public:\n typedef typename A::difference_type difference_type;\n typedef typename A::value_type value_type;\n typedef typename const A::reference reference;\n typedef typename const A::pointer pointer;\n typedef std::random_access_iterator_tag iterator_category; //or another tag\n\n const_iterator ();\n const_iterator (const const_iterator&);\n const_iterator (const iterator&);\n ~const_iterator();\n\n const_iterator& operator=(const const_iterator&);\n bool operator==(const const_iterator&) const;\n bool operator!=(const const_iterator&) const;\n bool operator<(const const_iterator&) const; //optional\n bool operator>(const const_iterator&) const; //optional\n bool operator<=(const const_iterator&) const; //optional\n bool operator>=(const const_iterator&) const; //optional\n\n const_iterator& operator++();\n const_iterator operator++(int); //optional\n const_iterator& operator--(); //optional\n const_iterator operator--(int); //optional\n const_iterator& operator+=(size_type); //optional\n const_iterator operator+(size_type) const; //optional\n friend const_iterator operator+(size_type, const const_iterator&); //optional\n const_iterator& operator-=(size_type); //optional \n const_iterator operator-(size_type) const; //optional\n difference_type operator-(const_iterator) const; //optional\n\n reference operator*() const;\n pointer operator->() const;\n reference operator[](size_type) const; //optional\n };\n\n typedef std::reverse_iterator<iterator> reverse_iterator; //optional\n typedef std::reverse_iterator<const_iterator> const_reverse_iterator; //optional\n\n X();\n X(const X&);\n ~X();\n\n X& operator=(const X&);\n bool operator==(const X&) const;\n bool operator!=(const X&) const;\n bool operator<(const X&) const; //optional\n bool operator>(const X&) const; //optional\n bool operator<=(const X&) const; //optional\n bool operator>=(const X&) const; //optional\n\n iterator begin();\n const_iterator begin() const;\n const_iterator cbegin() const;\n iterator end();\n const_iterator end() const;\n const_iterator cend() const;\n reverse_iterator rbegin(); //optional\n const_reverse_iterator rbegin() const; //optional\n const_reverse_iterator crbegin() const; //optional\n reverse_iterator rend(); //optional\n const_reverse_iterator rend() const; //optional\n const_reverse_iterator crend() const; //optional\n\n reference front(); //optional\n const_reference front() const; //optional\n reference back(); //optional\n const_reference back() const; //optional\n template<class ...Args>\n void emplace_front(Args&&...); //optional\n template<class ...Args>\n void emplace_back(Args&&...); //optional\n void push_front(const T&); //optional\n void push_front(T&&); //optional\n void push_back(const T&); //optional\n void push_back(T&&); //optional\n void pop_front(); //optional\n void pop_back(); //optional\n reference operator[](size_type); //optional\n const_reference operator[](size_type) const; //optional\n reference at(size_type); //optional\n const_reference at(size_type) const; //optional\n\n template<class ...Args>\n iterator emplace(const_iterator, Args&&...); //optional\n iterator insert(const_iterator, const T&); //optional\n iterator insert(const_iterator, T&&); //optional\n iterator insert(const_iterator, size_type, T&); //optional\n template<class iter>\n iterator insert(const_iterator, iter, iter); //optional\n iterator insert(const_iterator, std::initializer_list<T>); //optional\n iterator erase(const_iterator); //optional\n iterator erase(const_iterator, const_iterator); //optional\n void clear(); //optional\n template<class iter>\n void assign(iter, iter); //optional\n void assign(std::initializer_list<T>); //optional\n void assign(size_type, const T&); //optional\n\n void swap(X&);\n size_type size() const;\n size_type max_size() const;\n bool empty() const;\n\n A get_allocator() const; //optional\n};\ntemplate <class T, class A = std::allocator<T> >\nvoid swap(X<T,A>&, X<T,A>&); //optional\n#include <cassert>\nstruct verify;\nclass tester {\n friend verify;\n static int livecount;\n const tester* self;\npublic:\n tester() :self(this) {++livecount;}\n tester(const tester&) :self(this) {++livecount;}\n ~tester() {assert(self==this);--livecount;}\n tester& operator=(const tester& b) {\n assert(self==this && b.self == &b);\n return *this;\n }\n void cfunction() const {assert(self==this);}\n void mfunction() {assert(self==this);}\n};\nint tester::livecount=0;\nstruct verify {\n ~verify() {assert(tester::livecount==0);}\n}verifier;\ntestertestertestertestertester"}, {"idx": "webquery-test-4", "doc": "C++ template constructor", "code": "Foo<int> f = Foo<int>();\n<int><int>"}, {"idx": "webquery-test-5", "doc": "Windows threading: _beginthread vs _beginthreadex vs CreateThread C++", "code": "CreateThread()_beginthread()_beginthread()_beginthread()_beginthread()_beginthread()_beginthreadex()"}, {"idx": "webquery-test-6", "doc": "\"using namespace\" in c++ headers", "code": "using namespaceusing namespaceusing namespaceusing namespace#include"}, {"idx": "webquery-test-7", "doc": "Operator overloading : member function vs. non-member function?", "code": "s1 + s2s1 + s2doubledoubledoublefriendfriendfriendclass Sample\n{\n public:\n Sample operator + (const Sample& op2); //works with s1 + s2\n Sample operator + (double op2); //works with s1 + 10.0\n\n //Make it `friend` only when it needs to access private members. \n //Otherwise simply make it **non-friend non-member** function.\n friend Sample operator + (double op1, const Sample& op2); //works with 10.0 + s2\n}\n"}, {"idx": "webquery-test-8", "doc": "Why does std::getline() skip input after a formatted extraction?", "code": "std::getline()std::getline()\"10\\n\"\nageageageagecin.ignore()std::getline()std::getline()std::cin >> age;\nstd::cin.ignore();\nstd::getline(std::cin, name);\n\nassert(std::cin); \n// Success!\nstd::wsstd::wsstd::cin >> age;\nstd::getline(std::cin >> std::ws, name);\n\nassert(std::cin);\n// Success!\nstd::cin >> std::wsstd::cin >> std::wsstd::cin >> std::wsignore()ignore()operator>>()operator>>()operator>>()operator>>()// Unformatted I/O\nstd::string age, name;\nstd::getline(std::cin, age);\nstd::getline(std::cin, name);\n// Formatted I/O\nint age;\nstd::string firstName, lastName;\nstd::cin >> age >> firstName >> lastName;\n"}, {"idx": "webquery-test-9", "doc": "Most elegant way to write a one-shot 'if'", "code": "std::exchangeif (static bool do_once = true; std::exchange(do_once, false))\nif (static bool do_once; !std::exchange(do_once, true))\nstruct Once {\n bool b = true;\n explicit operator bool() { return std::exchange(b, false); }\n};\nif (static Once once; once)\n_if (static Once _; _)\n// GCC, Clang, icc only; use [[likely]] in C++20 instead\n#define likely(x) __builtin_expect(!!(x), 1)\n\nstruct Once {\n bool b = false;\n explicit operator bool()\n {\n if (likely(b))\n return false;\n\n b = true;\n return true;\n }\n};\n"}, {"idx": "webquery-test-10", "doc": "declaring a priority_queue in c++ with a custom comparator", "code": "CompareCompareclass Foo\n{\n\n};\n\nclass Compare\n{\npublic:\n bool operator() (Foo, Foo)\n {\n return true;\n }\n};\n\nint main()\n{\n std::priority_queue<Foo, std::vector<Foo>, Compare> pq;\n return 0;\n}\nstd::functionclass Foo\n{\n\n};\n\nbool Compare(Foo, Foo)\n{\n return true;\n}\n\nint main()\n{\n std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);\n return 0;\n}\n"}, {"idx": "webquery-test-11", "doc": "using extern template (C++11)", "code": "extern template// header.h\n\ntemplate<typename T>\nvoid ReallyBigFunction()\n{\n // Body\n}\n\n// source1.cpp\n\n#include \"header.h\"\nvoid something1()\n{\n ReallyBigFunction<int>();\n}\n\n// source2.cpp\n\n#include \"header.h\"\nvoid something2()\n{\n ReallyBigFunction<int>();\n}\nsource1.o\n void something1()\n void ReallyBigFunction<int>() // Compiled first time\n\nsource2.o\n void something2()\n void ReallyBigFunction<int>() // Compiled second time\nvoid ReallyBigFunction<int>()externsource2.cpp// source2.cpp\n\n#include \"header.h\"\nextern template void ReallyBigFunction<int>();\nvoid something2()\n{\n ReallyBigFunction<int>();\n}\nsource1.o\n void something1()\n void ReallyBigFunction<int>() // compiled just one time\n\nsource2.o\n void something2()\n // No ReallyBigFunction<int> here because of the extern\nvector<int>vector<int>"}, {"idx": "webquery-test-12", "doc": "Python-equivalent of short-form \"if\" in C++", "code": "a = '123' if b else '456'\n"}, {"idx": "webquery-test-13", "doc": "How to initialize const member variable in a class?", "code": "constconstT1() : t( 100 ){}\nt = 100"}, {"idx": "webquery-test-1", "doc": "What are coroutines in C++20?", "code": "function Generator() {\n for (i = 0 to 100)\n produce i\n}\nGeneratorGeneratorco_returnco_returnco_returngenerator<int> get_integers( int start=0, int step=1 ) {\n for (int current=start; true; current+= step)\n co_yield current;\n}\nco_yieldco_yieldco_yieldco_yieldco_awaitco_awaitstd::future<std::expected<std::string>> load_data( std::string resource )\n{\n auto handle = co_await open_resouce(resource);\n while( auto line = co_await read_line(handle)) {\n if (std::optional<std::string> r = parse_data_from_line( line ))\n co_return *r;\n }\n co_return std::unexpected( resource_lacks_data(resource) );\n}\nload_dataload_dataopen_resourceopen_resourceopen_resourceopen_resourceco_returnco_returnco_returnco_returnmodified_optional<int> add( modified_optional<int> a, modified_optional<int> b ) {\n co_return (co_await a) + (co_await b);\n}\nstd::optional<int> add( std::optional<int> a, std::optional<int> b ) {\n if (!a) return std::nullopt;\n if (!b) return std::nullopt;\n return *a + *b;\n}\n"}, {"idx": "webquery-test-2", "doc": "C++ Returning reference to local variable", "code": "int& func1()\n{\n int i;\n i = 1;\n return i;\n}\nfunc1()func1()int main()\n{\n int& p = func1();\n /* p is garbage */\n}\ndeletedeleteint* func2()\n{\n int* p;\n p = new int;\n *p = 1;\n return p;\n}\n\nint main()\n{\n int* p = func2();\n /* pointee still exists */\n delete p; // get rid of it\n}\ndeleteint func3()\n{\n return 1;\n}\n\nint main()\n{\n int v = func3();\n // do whatever you want with the returned value\n}\nfunc3()class big_object \n{ \npublic:\n big_object(/* constructor arguments */);\n ~big_object();\n big_object(const big_object& rhs);\n big_object& operator=(const big_object& rhs);\n /* public methods */\nprivate:\n /* data members */\n};\n\nbig_object func4()\n{\n return big_object(/* constructor arguments */);\n}\n\nint main()\n{\n // no copy is actually made, if your compiler supports RVO\n big_object o = func4(); \n}\nint main()\n{\n // This works! The returned temporary will last as long as the reference exists\n const big_object& o = func4(); \n // This does *not* work! It's not legal C++ because reference is not const.\n // big_object& o = func4(); \n}\n"}, {"idx": "webquery-test-3", "doc": "Passing a std::array of unknown size to a function", "code": "std::vectortemplate<std::size_t SIZE>\nvoid mulArray(std::array<int, SIZE>& arr, const int multiplier) {\n for(auto& e : arr) {\n e *= multiplier;\n }\n}\n"}, {"idx": "webquery-test-4", "doc": "When is a C++ destructor called?", "code": "// pointer is destroyed because it goes out of scope,\n// but not the object it pointed to. memory leak\nif (1) {\n Foo *myfoo = new Foo(\"foo\");\n}\n\n\n// pointer is destroyed because it goes out of scope,\n// object it points to is deleted. no memory leak\nif(1) {\n Foo *myfoo = new Foo(\"foo\");\n delete myfoo;\n}\n\n// no memory leak, object goes out of scope\nif(1) {\n Foo myfoo(\"foo\");\n}\n"}, {"idx": "webquery-test-5", "doc": "Significance of a .inl file in C++", "code": ".inl.inl#include#include.inl"}, {"idx": "webquery-test-6", "doc": "Is there a simple way to convert C++ enum to string?", "code": "#include <iostream>\n\nenum Colours {\n# define X(a) a,\n# include \"colours.def\"\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\n# include \"colours.def\"\n# undef X\n 0\n};\n\nstd::ostream& operator<<(std::ostream& os, enum Colours c)\n{\n if (c >= ColoursCount || c < 0) return os << \"???\";\n return os << colours_str[c];\n}\n\nint main()\n{\n std::cout << Red << Blue << Green << Cyan << Yellow << Magenta << std::endl;\n}\nX(Red)\nX(Green)\nX(Blue)\nX(Cyan)\nX(Yellow)\nX(Magenta)\n#define X(a, b) a,\n#define X(a, b) b,\n\nX(Red, \"red\")\nX(Green, \"green\")\n// etc.\n"}, {"idx": "webquery-test-7", "doc": "abort, terminate or exit?", "code": "abortabortabortabortabortabortabortabortabortabortabortabortabortstd::terminatestd::terminatestd::terminatestd::terminatestd::terminatemainmain"}, {"idx": "webquery-test-8", "doc": "Why is `std::move` named `std::move`?", "code": "std::move(x)std::move(x)movemovetemplate <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(static_cast<T&&>(a));\n a = static_cast<T&&>(b);\n b = static_cast<T&&>(tmp);\n}\n&&&&swapswapswapstatic_cast<T&&>template <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(move(a));\n a = move(b);\n b = move(tmp);\n}\nmovemoveswaptemplate <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(cast_to_rvalue(a));\n a = cast_to_rvalue(b);\n b = cast_to_rvalue(tmp);\n}\nmoveswaptemplate <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(set_value_category_to_xvalue(a));\n a = set_value_category_to_xvalue(b);\n b = set_value_category_to_xvalue(tmp);\n}\ntemplate <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(move(a));\n a = move(b);\n b = move(tmp);\n}\ntemplate <class T>\nvoid\nswap(T& a, T& b)\n{\n T tmp(static_cast<T&&>(a));\n a = static_cast<T&&>(b);\n b = static_cast<T&&>(tmp);\n}\nmovemovestd::movestd::movetemplate <class T>\ninline\nconstexpr\ntypename std::remove_reference<T>::type&&\nset_value_category_to_xvalue(T&& t) noexcept\n{\n return static_cast<typename std::remove_reference<T>::type&&>(t);\n}\ntemplate <class T>\ninline\nconstexpr\nauto&&\nset_value_category_to_xvalue(T&& t) noexcept\n{\n return static_cast<std::remove_reference_t<T>&&>(t);\n}\nstatic_cast<T&&>movetestvoid\ntest(int& i, int& j)\n{\n i = j;\n}\nclang++ -std=c++14 test.cpp -O3 -S__Z4testRiS_: ## @_Z4testRiS_\n .cfi_startproc\n## BB#0:\n pushq %rbp\nLtmp0:\n .cfi_def_cfa_offset 16\nLtmp1:\n .cfi_offset %rbp, -16\n movq %rsp, %rbp\nLtmp2:\n .cfi_def_cfa_register %rbp\n movl (%rsi), %eax\n movl %eax, (%rdi)\n popq %rbp\n retq\n .cfi_endproc\nvoid\ntest(int& i, int& j)\n{\n i = std::move(j);\n}\nstd::movestruct X\n{\n X& operator=(const X&);\n};\n\nvoid\ntest(X& i, X& j)\n{\n i = j;\n}\n__Z4testR1XS0_: ## @_Z4testR1XS0_\n .cfi_startproc\n## BB#0:\n pushq %rbp\nLtmp0:\n .cfi_def_cfa_offset 16\nLtmp1:\n .cfi_offset %rbp, -16\n movq %rsp, %rbp\nLtmp2:\n .cfi_def_cfa_register %rbp\n popq %rbp\n jmp __ZN1XaSERKS_ ## TAILCALL\n .cfi_endproc\n__ZN1XaSERKS___ZN1XaSERKS___ZN1XaSERKS_void\ntest(X& i, X& j)\n{\n i = std::move(j);\n}\nstd::movestd::movestd::movestd::moveXstruct X\n{\n X& operator=(const X&);\n X& operator=(X&&);\n};\n__Z4testR1XS0_: ## @_Z4testR1XS0_\n .cfi_startproc\n## BB#0:\n pushq %rbp\nLtmp0:\n .cfi_def_cfa_offset 16\nLtmp1:\n .cfi_offset %rbp, -16\n movq %rsp, %rbp\nLtmp2:\n .cfi_def_cfa_register %rbp\n popq %rbp\n jmp __ZN1XaSEOS_ ## TAILCALL\n .cfi_endproc\n__ZN1XaSEOS___ZN1XaSEOS___ZN1XaSEOS___ZN1XaSEOS_std::move"}, {"idx": "webquery-test-9", "doc": "Purpose of Trigraph sequences in C++?", "code": "?'\\?'\n printf( \"What?\\?!\\n\" ); \n\n printf( \"What?\" \"?!\\n\" ); \n"}, {"idx": "webquery-test-10", "doc": "Why do std::shared_ptr<void> work", "code": "std::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrtemplate <typename T>\nvoid delete_deleter( void * p ) {\n delete static_cast<T*>(p);\n}\n\ntemplate <typename T>\nclass my_unique_ptr {\n std::function< void (void*) > deleter;\n T * p;\n template <typename U>\n my_unique_ptr( U * p, std::function< void(void*) > deleter = &delete_deleter<U> ) \n : p(p), deleter(deleter) \n {}\n ~my_unique_ptr() {\n deleter( p ); \n }\n};\n\nint main() {\n my_unique_ptr<void> p( new double ); // deleter == &delete_deleter<double>\n}\n// ~my_unique_ptr calls delete_deleter<double>(p)\nshared_ptrshared_ptrshared_ptrshared_ptr"}, {"idx": "webquery-test-11", "doc": "Do c++11 lambdas capture variables they don't use?", "code": "my_huge_vectorthis[=]my_huge_vector==my_huge_vector"}, {"idx": "webquery-test-1", "doc": "const before parameter vs const after function name c++", "code": "CircleCircleCircleCircleCircleCircleconstconstconstconstconstconststruct X\n{\n void foo() const // <== The implicit \"this\" pointer is const-qualified!\n {\n _x = 42; // ERROR! The \"this\" pointer is implicitly const\n _y = 42; // OK (_y is mutable)\n }\n\n void bar(X& obj) const // <== The implicit \"this\" pointer is const-qualified!\n {\n obj._x = 42; // OK! obj is a reference to non-const\n _x = 42; // ERROR! The \"this\" pointer is implicitly const\n }\n\n void bar(X const& obj) // <== The implicit \"this\" pointer is NOT const-qualified!\n {\n obj._x = 42; // ERROR! obj is a reference to const\n obj._y = 42; // OK! obj is a reference to const, but _y is mutable\n _x = 42; // OK! The \"this\" pointer is implicitly non-const\n }\n\n int _x;\n mutable int _y;\n};\n"}, {"idx": "webquery-test-2", "doc": "How can I output the value of an enum class in C++11", "code": "std::cout << static_cast<std::underlying_type<A>::type>(a) << std::endl;\ntemplate <typename Enumeration>\nauto as_integer(Enumeration const value)\n -> typename std::underlying_type<Enumeration>::type\n{\n return static_cast<typename std::underlying_type<Enumeration>::type>(value);\n}\nstd::cout << as_integer(a) << std::endl;\n"}, {"idx": "webquery-test-3", "doc": "How to clear stringstream?", "code": "strstrparser.str( std::string() );\nparser.clear();\n>>"}, {"idx": "webquery-test-4", "doc": "Any optimization for random access on a very big array when the value in 95% of cases is either 0 or 1?", "code": "(idx << 8) | value)std::vector<uint8_t> main_arr;\nstd::vector<uint32_t> sec_arr;\n\nuint8_t lookup(unsigned idx) {\n // extract the 2 bits of our interest from the main array\n uint8_t v = (main_arr[idx>>2]>>(2*(idx&3)))&3;\n // usual (likely) case: value between 0 and 2\n if(v != 3) return v;\n // bad case: lookup the index<<8 in the secondary array\n // lower_bound finds the first >=, so we don't need to mask out the value\n auto ptr = std::lower_bound(sec_arr.begin(), sec_arr.end(), idx<<8);\n#ifdef _DEBUG\n // some coherency checks\n if(ptr == sec_arr.end()) std::abort();\n if((*ptr >> 8) != idx) std::abort();\n#endif\n // extract our 8-bit value from the 32 bit (index, value) thingie\n return (*ptr) & 0xff;\n}\n\nvoid populate(uint8_t *source, size_t size) {\n main_arr.clear(); sec_arr.clear();\n // size the main storage (round up)\n main_arr.resize((size+3)/4);\n for(size_t idx = 0; idx < size; ++idx) {\n uint8_t in = source[idx];\n uint8_t &target = main_arr[idx>>2];\n // if the input doesn't fit, cap to 3 and put in secondary storage\n if(in >= 3) {\n // top 24 bits: index; low 8 bit: value\n sec_arr.push_back((idx << 8) | in);\n in = 3;\n }\n // store in the target according to the position\n target |= in << ((idx & 3)*2);\n }\n}\n#include <algorithm>\n#include <vector>\n#include <stdint.h>\n#include <chrono>\n#include <stdio.h>\n#include <math.h>\n\nusing namespace std::chrono;\n\n/// XorShift32 generator; extremely fast, 2^32-1 period, way better quality\n/// than LCG but fail some test suites\nstruct XorShift32 {\n /// This stuff allows to use this class wherever a library function\n /// requires a UniformRandomBitGenerator (e.g. std::shuffle)\n typedef uint32_t result_type;\n static uint32_t min() { return 1; }\n static uint32_t max() { return uint32_t(-1); }\n\n /// PRNG state\n uint32_t y;\n\n /// Initializes with seed\n XorShift32(uint32_t seed = 0) : y(seed) {\n if(y == 0) y = 2463534242UL;\n }\n\n /// Returns a value in the range [1, 1<<32)\n uint32_t operator()() {\n y ^= (y<<13);\n y ^= (y>>17);\n y ^= (y<<15);\n return y;\n }\n\n /// Returns a value in the range [0, limit); this conforms to the RandomFunc\n /// requirements for std::random_shuffle\n uint32_t operator()(uint32_t limit) {\n return (*this)()%limit;\n }\n};\n\nstruct mean_variance {\n double rmean = 0.;\n double rvariance = 0.;\n int count = 0;\n\n void operator()(double x) {\n ++count;\n double ormean = rmean;\n rmean += (x-rmean)/count;\n rvariance += (x-ormean)*(x-rmean);\n }\n\n double mean() const { return rmean; }\n double variance() const { return rvariance/(count-1); }\n double stddev() const { return std::sqrt(variance()); }\n};\n\nstd::vector<uint8_t> main_arr;\nstd::vector<uint32_t> sec_arr;\n\nuint8_t lookup(unsigned idx) {\n // extract the 2 bits of our interest from the main array\n uint8_t v = (main_arr[idx>>2]>>(2*(idx&3)))&3;\n // usual (likely) case: value between 0 and 2\n if(v != 3) return v;\n // bad case: lookup the index<<8 in the secondary array\n // lower_bound finds the first >=, so we don't need to mask out the value\n auto ptr = std::lower_bound(sec_arr.begin(), sec_arr.end(), idx<<8);\n#ifdef _DEBUG\n // some coherency checks\n if(ptr == sec_arr.end()) std::abort();\n if((*ptr >> 8) != idx) std::abort();\n#endif\n // extract our 8-bit value from the 32 bit (index, value) thingie\n return (*ptr) & 0xff;\n}\n\nvoid populate(uint8_t *source, size_t size) {\n main_arr.clear(); sec_arr.clear();\n // size the main storage (round up)\n main_arr.resize((size+3)/4);\n for(size_t idx = 0; idx < size; ++idx) {\n uint8_t in = source[idx];\n uint8_t &target = main_arr[idx>>2];\n // if the input doesn't fit, cap to 3 and put in secondary storage\n if(in >= 3) {\n // top 24 bits: index; low 8 bit: value\n sec_arr.push_back((idx << 8) | in);\n in = 3;\n }\n // store in the target according to the position\n target |= in << ((idx & 3)*2);\n }\n}\n\nvolatile unsigned out;\n\nint main() {\n XorShift32 xs;\n std::vector<uint8_t> vec;\n int size = 10000000;\n for(int i = 0; i<size; ++i) {\n uint32_t v = xs();\n if(v < 1825361101) v = 0; // 42.5%\n else if(v < 4080218931) v = 1; // 95.0%\n else if(v < 4252017623) v = 2; // 99.0%\n else {\n while((v & 0xff) < 3) v = xs();\n }\n vec.push_back(v);\n }\n populate(vec.data(), vec.size());\n mean_variance lk_t, arr_t;\n for(int i = 0; i<50; ++i) {\n {\n unsigned o = 0;\n auto beg = high_resolution_clock::now();\n for(int i = 0; i < size; ++i) {\n o += lookup(xs() % size);\n }\n out += o;\n int dur = (high_resolution_clock::now()-beg)/microseconds(1);\n fprintf(stderr, \"lookup: %10d \u00b5s\\n\", dur);\n lk_t(dur);\n }\n {\n unsigned o = 0;\n auto beg = high_resolution_clock::now();\n for(int i = 0; i < size; ++i) {\n o += vec[xs() % size];\n }\n out += o;\n int dur = (high_resolution_clock::now()-beg)/microseconds(1);\n fprintf(stderr, \"array: %10d \u00b5s\\n\", dur);\n arr_t(dur);\n }\n }\n\n fprintf(stderr, \" lookup | \u00b1 | array | \u00b1 | speedup\\n\");\n printf(\"%7.0f | %4.0f | %7.0f | %4.0f | %0.2f\\n\",\n lk_t.mean(), lk_t.stddev(),\n arr_t.mean(), arr_t.stddev(),\n arr_t.mean()/lk_t.mean());\n return 0;\n}\n-O3 -static CPU | cache | lookup (\u00b5s) | array (\u00b5s) | speedup (x)\nXeon E5-1650 v3 @ 3.50GHz | 15360 KB | 60011 \u00b1 3667 | 29313 \u00b1 2137 | 0.49\nXeon E5-2697 v3 @ 2.60GHz | 35840 KB | 66571 \u00b1 7477 | 33197 \u00b1 3619 | 0.50\nCeleron G1610T @ 2.30GHz | 2048 KB | 172090 \u00b1 629 | 162328 \u00b1 326 | 0.94\nCore i3-3220T @ 2.80GHz | 3072 KB | 111025 \u00b1 5507 | 114415 \u00b1 2528 | 1.03\nCore i5-7200U @ 2.50GHz | 3072 KB | 92447 \u00b1 1494 | 95249 \u00b1 1134 | 1.03\nXeon X3430 @ 2.40GHz | 8192 KB | 111303 \u00b1 936 | 127647 \u00b1 1503 | 1.15\nCore i7 920 @ 2.67GHz | 8192 KB | 123161 \u00b1 35113 | 156068 \u00b1 45355 | 1.27\nXeon X5650 @ 2.67GHz | 12288 KB | 106015 \u00b1 5364 | 140335 \u00b1 6739 | 1.32\nCore i7 870 @ 2.93GHz | 8192 KB | 77986 \u00b1 429 | 106040 \u00b1 1043 | 1.36\nCore i7-6700 @ 3.40GHz | 8192 KB | 47854 \u00b1 573 | 66893 \u00b1 1367 | 1.40\nCore i3-4150 @ 3.50GHz | 3072 KB | 76162 \u00b1 983 | 113265 \u00b1 239 | 1.49\nXeon X5650 @ 2.67GHz | 12288 KB | 101384 \u00b1 796 | 152720 \u00b1 2440 | 1.51\nCore i7-3770T @ 2.50GHz | 8192 KB | 69551 \u00b1 1961 | 128929 \u00b1 2631 | 1.85\n"}, {"idx": "webquery-test-5", "doc": "Polymorphism in C++", "code": " Type1 x;\n Type2 y;\n\n f(x);\n f(y);\nf()f()f()f()f()f()f()#define f(X) ((X) += 2)\n// (note: in real code, use a longer uppercase name for a macro!)\n#define f(X) ((X) += 2)\n// (note: in real code, use a longer uppercase name for a macro!)\n#define f(X) ((X) += 2)\n// (note: in real code, use a longer uppercase name for a macro!)\n#define f(X) ((X) += 2)\n// (note: in real code, use a longer uppercase name for a macro!)\nffffstd::enable_ifstd::enable_ifstd::enable_ifstd::enable_ifBase*__FILE____FILE__intintintstd::string x;\nint y = 0;\n\nx += 'c';\ny += 'c';\ndouble a(double x) { return x + 2; }\n\na(3.14);\na(42);\na()a()a()a()a()a()a()a()int a, b;\n\nif (std::cin >> a >> b)\n f(a, b);\nstd::cinf(const std::string& x);\nf(\"hello\"); // invokes `std::string::string(const char*)`\nvoid f()\n{\n typedef int Amount;\n Amount x = 13;\n x /= 2;\n std::cout << x * 1.1;\n}\nxxvoid f() void f()\n{ {\n typedef int Amount; typedef double Amount;\n Amount x = 13; Amount x = 13.0;\n x /= 2; x /= 2.0;\n std::cout << double(x) * 1.1; std::cout << x * 1.1;\n} }\ntemplatetemplate <typename Amount>\nvoid f()\n{\n Amount x = 13;\n x /= 2;\n std::cout << x * 1.1;\n}\nintinttemplate <typename Amount, typename Policy>\nvoid f()\n{\n Amount x = Policy::thirteen;\n x /= static_cast<Amount>(2);\n std::cout << traits<Amount>::to_double(x) * 1.1;\n}\n"}, {"idx": "webquery-test-6", "doc": "Why does integer overflow on x86 with GCC cause an infinite loop?", "code": "-fwrapv-fwrapv-fwrapv"}, {"idx": "webquery-test-7", "doc": "C++ Exceptions questions on rethrow of original exception", "code": "0x98e7058throw;throw;throw;throw;throw;throw;throw;throw;throw;#include <stdio.h>\n\nstruct MyErr {\n MyErr() {\n printf(\" Base default constructor, this=%p\\n\", this);\n }\n MyErr(const MyErr& other) {\n printf(\" Base copy-constructor, this=%p from that=%p\\n\", this, &other);\n }\n virtual ~MyErr() {\n printf(\" Base destructor, this=%p\\n\", this);\n }\n};\n\nstruct MyErrDerived : public MyErr {\n MyErrDerived() {\n printf(\" Derived default constructor, this=%p\\n\", this);\n }\n MyErrDerived(const MyErrDerived& other) {\n printf(\" Derived copy-constructor, this=%p from that=%p\\n\", this, &other);\n }\n virtual ~MyErrDerived() {\n printf(\" Derived destructor, this=%p\\n\", this);\n }\n};\n\nint main() {\n try {\n try {\n MyErrDerived e;\n throw e;\n } catch (MyErr& err) {\n printf(\"A Inner catch, &err=%p\\n\", &err);\n throw;\n }\n } catch (MyErr& err) {\n printf(\"A Outer catch, &err=%p\\n\", &err);\n }\n printf(\"---\\n\");\n try {\n try {\n MyErrDerived e;\n throw e;\n } catch (MyErr& err) {\n printf(\"B Inner catch, &err=%p\\n\", &err);\n throw err;\n }\n } catch (MyErr& err) {\n printf(\"B Outer catch, &err=%p\\n\", &err);\n }\n return 0;\n}\n Base default constructor, this=0xbfbce430\n Derived default constructor, this=0xbfbce430\n Base default constructor, this=0x98e7058\n Derived copy-constructor, this=0x98e7058 from that=0xbfbce430\n Derived destructor, this=0xbfbce430\n Base destructor, this=0xbfbce430\nA Inner catch, &err=0x98e7058\nA Outer catch, &err=0x98e7058\n Derived destructor, this=0x98e7058\n Base destructor, this=0x98e7058\n---\n Base default constructor, this=0xbfbce430\n Derived default constructor, this=0xbfbce430\n Base default constructor, this=0x98e7058\n Derived copy-constructor, this=0x98e7058 from that=0xbfbce430\n Derived destructor, this=0xbfbce430\n Base destructor, this=0xbfbce430\nB Inner catch, &err=0x98e7058\n Base copy-constructor, this=0x98e70b0 from that=0x98e7058\n Derived destructor, this=0x98e7058\n Base destructor, this=0x98e7058\nB Outer catch, &err=0x98e70b0\n Base destructor, this=0x98e70b0\n"}, {"idx": "webquery-test-8", "doc": "Can I assume (bool)true == (int)1 for any C++ compiler?", "code": "true == 1\nintboolbool"}, {"idx": "webquery-test-9", "doc": "How to easily map c++ enums to strings", "code": "std::map<MyEnum, char const*>std::map<MyEnum, const char*> MyMap;\nmap_init(MyMap)\n (eValue1, \"A\")\n (eValue2, \"B\")\n (eValue3, \"C\")\n;\ntemplate <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template <typename T> map_init(T&)template<typename T> struct map_init_helper\n{\n T& data;\n map_init_helper(T& d) : data(d) {}\n map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)\n {\n data[key] = value;\n return *this;\n }\n};\n\ntemplate<typename T> map_init_helper<T> map_init(T& item)\n{\n return map_init_helper<T>(item);\n}\nstd::unordered_map"}, {"idx": "webquery-test-10", "doc": "Why does the use of 'new' cause memory leaks?", "code": "T t;T t;new T()new T()deletenewA a; // a new object of type A\nB b; // a new object of type B\ntemplate <typename T>\nclass automatic_pointer {\npublic:\n automatic_pointer(T* pointer) : pointer(pointer) {}\n\n // destructor: gets called upon cleanup\n // in this case, we want to use delete\n ~automatic_pointer() { delete pointer; }\n\n // emulate pointers!\n // with this we can write *p\n T& operator*() const { return *pointer; }\n // and with this we can write p->f()\n T* operator->() const { return pointer; }\n\nprivate:\n T* pointer;\n\n // for this example, I'll just forbid copies\n // a smarter class could deal with this some other way\n automatic_pointer(automatic_pointer const&);\n automatic_pointer& operator=(automatic_pointer const&);\n};\n\nautomatic_pointer<A> a(new A()); // acts like a pointer, but deletes automatically\nautomatic_pointer<B> b(new B()); // acts like a pointer, but deletes automatically\nautomatic_pointerautomatic_pointerauto_ptrstd::shared_ptr"}, {"idx": "webquery-test-11", "doc": "Incomplete type is not allowed: stringstream", "code": "#include <sstream>#include <sstream>"}, {"idx": "webquery-test-1", "doc": "Visual Studio Code formatting for \"{ }\"", "code": "\"{ BasedOnStyle: Google, IndentWidth: 4 }\"\"C_Cpp.clang_format_fallbackStyle\": \"{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}\"\n\"C_Cpp.clang_format_fallbackStyle\": \"{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}\"\n"}, {"idx": "webquery-test-2", "doc": "std::shared_ptr of this", "code": "std::enable_shared_from_thisstd::enable_shared_from_thisstd::enable_shared_from_thisclass A;\nclass B;\n\nclass A\n : public std::enable_shared_from_this<A>\n{\npublic:\n void addChild(std::shared_ptr<B> child)\n {\n children.push_back(child);\n\n // like this\n child->setParent(shared_from_this()); // ok\n // ^^^^^^^^^^^^^^^^^^\n }\n\nprivate: \n // note weak_ptr \n std::list<std::weak_ptr<B>> children;\n // ^^^^^^^^\n};\n\nclass B\n{\npublic:\n void setParent(std::shared_ptr<A> parent)\n {\n this->parent = parent;\n }\n\nprivate:\n std::shared_ptr<A> parent;\n};\n.shared_from_this().shared_from_this().shared_from_this().shared_from_this()"}, {"idx": "webquery-test-3", "doc": "Does C++11 unique_ptr and shared_ptr able to convert to each other's type?", "code": "std::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptrstd::unique_ptr<std::string> unique = std::make_unique<std::string>(\"test\");\nstd::shared_ptr<std::string> shared = std::move(unique);\nstd::shared_ptr<std::string> shared = std::make_unique<std::string>(\"test\");\n"}, {"idx": "webquery-test-4", "doc": "Arrays vs Vectors: Introductory Similarities and Differences", "code": "mallocmallocmallocstd::vector&vec[0]&vec[0]&vec[0]&vec[0]std::arraystd::arraystd::array"}, {"idx": "webquery-test-5", "doc": "Should I pass a shared_ptr by reference?", "code": "SF = std::shared_ptr<Foo>SF = std::shared_ptr<Foo>SF = std::shared_ptr<Foo>SF = std::shared_ptr<Foo>std::vector<Foo*>std::vector<Foo*>std::vector<Foo*>SF pSF pSF pSF p"}, {"idx": "webquery-test-6", "doc": "How does generic lambda work in C++14?", "code": "C++14C++11C++11auto glambda = [] (auto a) { return a; };\nglambdaclass /* unnamed */\n{\npublic:\n template<typename T>\n T operator () (T a) const { return a; }\n};\n"}, {"idx": "webquery-test-7", "doc": "Should I use an exception specifier in C++?", "code": "template<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\ntemplate<class T>\nvoid f( T k )\n{\n T x( k );\n x.x();\n}\n"}, {"idx": "webquery-test-8", "doc": "std::shared_ptr thread safety explained", "code": "dddddd#include <memory>\n#include <iostream>\nusing namespace std;\n\nstruct A\n{\n int a;\n A(int a) : a(a) {}\n};\n\nint main(int argc, char **argv)\n{\n shared_ptr<A> a(new A(1));\n shared_ptr<A> b(a), c(a), d(a);\n\n cout << \"a: \" << a->a << \"\\tb: \" << b->a\n << \"\\tc: \" << c->a << \"\\td: \" << d->a << endl;\n\n d.reset(new A(10));\n\n cout << \"a: \" << a->a << \"\\tb: \" << b->a\n << \"\\tc: \" << c->a << \"\\td: \" << d->a << endl;\n \n return 0; \n}\nshared_ptr::reset()"}, {"idx": "webquery-test-9", "doc": "vector::at vs. vector::operator[]", "code": "vector::at()vector::at()vector::at()vector::at()"}, {"idx": "webquery-test-10", "doc": "In release mode, code behavior is not as expected", "code": "cl /Ox vc15-bug.cpp /FAsc255255255; 6 : for( int i = 0; i < 17; i++ ) \n\n 00001 33 f6 xor esi, esi\n$LL4@main:\n 00003 8b c6 mov eax, esi\n 00005 c1 e0 04 shl eax, 4\n\n; 7 : { \n; 8 : int result = i * 16;\n; 9 : \n; 10 : if( result > 255 )\n\n // the value `esi` is compared with in the following line should be 15!\n 00008 83 fe 0e cmp esi, 14 ; 0000000eH\n 0000b 7e 05 jle SHORT $LN1@main\n\n; 11 : {\n; 12 : result = 255;\n\n 0000d b8 ff 00 00 00 mov eax, 255 ; 000000ffH\n$LN1@main:\n\n; 13 : }\nvc15-bug.cpp(10) : fatal error C1001: INTERNAL COMPILER ERROR\n"}, {"idx": "webquery-test-11", "doc": "How can I create Min stl priority_queue?", "code": "std::greaterstd::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;\n"}, {"idx": "webquery-test-1", "doc": "How to convert string to char array in C++?", "code": "string temp = \"cat\";\nchar tab2[1024];\nstrcpy(tab2, temp.c_str());\nstring temp = \"cat\";\nchar tab2[1024];\nstrncpy(tab2, temp.c_str(), sizeof(tab2));\ntab2[sizeof(tab2) - 1] = 0;\nstring temp = \"cat\";\nchar * tab2 = new char [temp.length()+1];\nstrcpy (tab2, temp.c_str());\n"}, {"idx": "webquery-test-2", "doc": "Yes/No message box using QMessageBox", "code": "QMessageBox::question#include <QApplication>\n#include <QMessageBox>\n#include <QDebug>\n\n// ...\n\nvoid MyWidget::someSlot() {\n QMessageBox::StandardButton reply;\n reply = QMessageBox::question(this, \"Test\", \"Quit?\",\n QMessageBox::Yes|QMessageBox::No);\n if (reply == QMessageBox::Yes) {\n qDebug() << \"Yes was clicked\";\n QApplication::quit();\n } else {\n qDebug() << \"Yes was *not* clicked\";\n }\n}\nQT += widgetsQT += widgetsQT += widgetsStandardButtonStandardButton"}, {"idx": "webquery-test-3", "doc": "What's the difference between deque and list STL containers?", "code": " Insert/erase at the beginning in middle at the end\n\nDeque: Amortized constant Linear Amortized constant\nList: Constant Constant Constant\n"}, {"idx": "webquery-test-4", "doc": "What is the difference between an int and a long in C++?", "code": " OS arch size\nWindows IA-32 4 bytes\nWindows Intel 64 4 bytes\nWindows IA-64 4 bytes\nLinux IA-32 4 bytes\nLinux Intel 64 8 bytes\nLinux IA-64 8 bytes\nMac OS X IA-32 4 bytes\nMac OS X Intel 64 8 bytes \n"}, {"idx": "webquery-test-5", "doc": "When to make a type non-movable in C++11?", "code": "std::mutexpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tpthread_mutex_tstd::mutexstd::mutexstd::mutexstd::mutexintintintint"}, {"idx": "webquery-test-6", "doc": "Creating an object: with or without `new`", "code": "{ ... }{ ... }deletedeletedeletedeletedeletedeletedeletedelete"}, {"idx": "webquery-test-7", "doc": "throw new std::exception vs throw std::exception", "code": "constcatch (...)deletedelete"}, {"idx": "webquery-test-8", "doc": "Inheriting from a template class in c++", "code": "AreaAreaAreaAreaAreaAreaAreaclass Rectangle:\n public Area<int>\n{\n // ...\n};\nArea<int>Area<int>class Rectangle:\n public Area<int>,\n public Area<char>\n{\n // ...\n};\nRectangleRectangletemplate<typename T> class Rectangle:\n public Area<T>\n{\n // ...\n};\nRectangleRectangleRectangleRectangleRectangleRectangleRectangleRectangleRectangleclass Rectangle // not inheriting from any Area type\n{\n // Area independent interface\n};\n\ntemplate<typename T> class SpecificRectangle:\n public Rectangle,\n public Area<T>\n{\n // Area dependent stuff\n};\n\nvoid foo(Rectangle&); // A function which works with generic rectangles\n\nint main()\n{\n SpecificRectangle<int> intrect;\n foo(intrect);\n\n SpecificRectangle<char> charrect;\n foo(charrect);\n}\nRectangleRectangleRectangleclass Area\n{\n // generic Area interface\n};\n\nclass Rectangle:\n public virtual Area // virtual because of \"diamond inheritance\"\n{\n // generic rectangle interface\n};\n\ntemplate<typename T> class SpecificArea:\n public virtual Area\n{\n // specific implementation of Area for type T\n};\n\ntemplate<typename T> class SpecificRectangle:\n public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later\n public SpecificArea<T> // no virtual inheritance needed here\n{\n // specific implementation of Rectangle for type T\n};\n"}, {"idx": "webquery-test-9", "doc": "What can I use instead of the arrow operator, `->`?", "code": "a->b\n\n(*a).b\n"}, {"idx": "webquery-test-1", "doc": "Finding duplicates in O(n) time and O(1) space", "code": "for i := 0 to n - 1\n while A[A[i]] != A[i] \n swap(A[i], A[A[i]])\n end while\nend for\n\nfor i := 0 to n - 1\n if A[i] != i then \n print A[i]\n end if\nend for\nxxO(N)O(N)O(N)O(N)O(N)O(N)xxxxxx"}, {"idx": "webquery-test-2", "doc": "Is there a __CLASS__ macro in C++?", "code": "typeid(*this).name()typeid(*this).name()typeid(*this).name()inline std::string methodName(const std::string& prettyFunction)\n{\n size_t colons = prettyFunction.find(\"::\");\n size_t begin = prettyFunction.substr(0,colons).rfind(\" \") + 1;\n size_t end = prettyFunction.rfind(\"(\") - begin;\n\n return prettyFunction.substr(begin,end) + \"()\";\n}\n\n#define __METHOD_NAME__ methodName(__PRETTY_FUNCTION__)\n__METHOD_NAME____METHOD_NAME____METHOD_NAME__inline std::string className(const std::string& prettyFunction)\n{\n size_t colons = prettyFunction.find(\"::\");\n if (colons == std::string::npos)\n return \"::\";\n size_t begin = prettyFunction.substr(0,colons).rfind(\" \") + 1;\n size_t end = colons - begin;\n\n return prettyFunction.substr(begin,end);\n}\n\n#define __CLASS_NAME__ className(__PRETTY_FUNCTION__)\n"}, {"idx": "webquery-test-3", "doc": "Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?", "code": "SRC_DIR := .../src\nOBJ_DIR := .../obj\nSRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)\nOBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))\nLDFLAGS := ...\nCPPFLAGS := ...\nCXXFLAGS := ...\n\nmain.exe: $(OBJ_FILES)\n g++ $(LDFLAGS) -o $@ $^\n\n$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp\n g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<\n-MMD-MMD-MMDCXXFLAGS += -MMD\n-include $(OBJ_FILES:.o=.d)\n"}, {"idx": "webquery-test-4", "doc": "Const map element access", "code": "at()at()operator[]operator[]operator[]operator[]operator[]constconstconst"}, {"idx": "webquery-test-5", "doc": "Creating an instance of class", "code": " /* 1 */ Foo* foo1 = new Foo ();\nFooFooFoo /* 2 */ Foo* foo2 = new Foo;\nFoo /* 3 */ Foo foo3;\nFooFoo /* 4 */ Foo foo4 = Foo::Foo();\nFooFoo /* 5 */ Bar* bar1 = new Bar ( *new Foo() );\nBarBarBar /* 6 */ Bar* bar2 = new Bar ( *new Foo );\n /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );\n /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );\nbar3new Bar ( Foo::Foo() );new Bar ( Foo::Foo() );"}, {"idx": "webquery-test-6", "doc": "How do exceptions work (behind the scenes) in c++", "code": "class MyException\n{\npublic:\n MyException() { }\n ~MyException() { }\n};\n\nvoid my_throwing_function(bool throwit)\n{\n if (throwit)\n throw MyException();\n}\n\nvoid another_function();\nvoid log(unsigned count);\n\nvoid my_catching_function()\n{\n log(0);\n try\n {\n log(1);\n another_function();\n log(2);\n }\n catch (const MyException& e)\n {\n log(3);\n }\n log(4);\n}\ng++ -m32 -W -Wall -O3 -save-temps -c .file \"foo.cpp\"\n .section .text._ZN11MyExceptionD1Ev,\"axG\",@progbits,_ZN11MyExceptionD1Ev,comdat\n .align 2\n .p2align 4,,15\n .weak _ZN11MyExceptionD1Ev\n .type _ZN11MyExceptionD1Ev, @function\n_ZN11MyExceptionD1Ev:\n.LFB7:\n pushl %ebp\n.LCFI0:\n movl %esp, %ebp\n.LCFI1:\n popl %ebp\n ret\n.LFE7:\n .size _ZN11MyExceptionD1Ev, .-_ZN11MyExceptionD1Ev\n_ZN11MyExceptionD1Ev_ZN11MyExceptionD1Ev.globl __gxx_personality_v0\n.globl _Unwind_Resume\n .text\n .align 2\n .p2align 4,,15\n.globl _Z20my_catching_functionv\n .type _Z20my_catching_functionv, @function\n_Z20my_catching_functionv:\n.LFB9:\n pushl %ebp\n.LCFI2:\n movl %esp, %ebp\n.LCFI3:\n pushl %ebx\n.LCFI4:\n subl $20, %esp\n.LCFI5:\n movl $0, (%esp)\n.LEHB0:\n call _Z3logj\n.LEHE0:\n movl $1, (%esp)\n.LEHB1:\n call _Z3logj\n call _Z16another_functionv\n movl $2, (%esp)\n call _Z3logj\n.LEHE1:\n.L5:\n movl $4, (%esp)\n.LEHB2:\n call _Z3logj\n addl $20, %esp\n popl %ebx\n popl %ebp\n ret\n.L12:\n subl $1, %edx\n movl %eax, %ebx\n je .L16\n.L14:\n movl %ebx, (%esp)\n call _Unwind_Resume\n.LEHE2:\n.L16:\n.L6:\n movl %eax, (%esp)\n call __cxa_begin_catch\n movl $3, (%esp)\n.LEHB3:\n call _Z3logj\n.LEHE3:\n call __cxa_end_catch\n .p2align 4,,3\n jmp .L5\n.L11:\n.L8:\n movl %eax, %ebx\n .p2align 4,,6\n call __cxa_end_catch\n .p2align 4,,6\n jmp .L14\n.LFE9:\n .size _Z20my_catching_functionv, .-_Z20my_catching_functionv\n .section .gcc_except_table,\"a\",@progbits\n .align 4\n.LLSDA9:\n .byte 0xff\n .byte 0x0\n .uleb128 .LLSDATT9-.LLSDATTD9\n.LLSDATTD9:\n .byte 0x1\n .uleb128 .LLSDACSE9-.LLSDACSB9\n.LLSDACSB9:\n .uleb128 .LEHB0-.LFB9\n .uleb128 .LEHE0-.LEHB0\n .uleb128 0x0\n .uleb128 0x0\n .uleb128 .LEHB1-.LFB9\n .uleb128 .LEHE1-.LEHB1\n .uleb128 .L12-.LFB9\n .uleb128 0x1\n .uleb128 .LEHB2-.LFB9\n .uleb128 .LEHE2-.LEHB2\n .uleb128 0x0\n .uleb128 0x0\n .uleb128 .LEHB3-.LFB9\n .uleb128 .LEHE3-.LEHB3\n .uleb128 .L11-.LFB9\n .uleb128 0x0\n.LLSDACSE9:\n .byte 0x1\n .byte 0x0\n .align 4\n .long _ZTI11MyException\n.LLSDATT9:\n_ZTI11MyException_ZTI11MyException .text\n .align 2\n .p2align 4,,15\n.globl _Z20my_throwing_functionb\n .type _Z20my_throwing_functionb, @function\n_Z20my_throwing_functionb:\n.LFB8:\n pushl %ebp\n.LCFI6:\n movl %esp, %ebp\n.LCFI7:\n subl $24, %esp\n.LCFI8:\n cmpb $0, 8(%ebp)\n jne .L21\n leave\n ret\n.L21:\n movl $1, (%esp)\n call __cxa_allocate_exception\n movl $_ZN11MyExceptionD1Ev, 8(%esp)\n movl $_ZTI11MyException, 4(%esp)\n movl %eax, (%esp)\n call __cxa_throw\n.LFE8:\n .size _Z20my_throwing_functionb, .-_Z20my_throwing_functionb\n__cxa_throw .weak _ZTI11MyException\n .section .rodata._ZTI11MyException,\"aG\",@progbits,_ZTI11MyException,comdat\n .align 4\n .type _ZTI11MyException, @object\n .size _ZTI11MyException, 8\n_ZTI11MyException:\n .long _ZTVN10__cxxabiv117__class_type_infoE+8\n .long _ZTS11MyException\n .weak _ZTS11MyException\n .section .rodata._ZTS11MyException,\"aG\",@progbits,_ZTS11MyException,comdat\n .type _ZTS11MyException, @object\n .size _ZTS11MyException, 14\n_ZTS11MyException:\n .string \"11MyException\"\n .section .eh_frame,\"a\",@progbits\n.Lframe1:\n .long .LECIE1-.LSCIE1\n.LSCIE1:\n .long 0x0\n .byte 0x1\n .string \"zPL\"\n .uleb128 0x1\n .sleb128 -4\n .byte 0x8\n .uleb128 0x6\n .byte 0x0\n .long __gxx_personality_v0\n .byte 0x0\n .byte 0xc\n .uleb128 0x4\n .uleb128 0x4\n .byte 0x88\n .uleb128 0x1\n .align 4\n.LECIE1:\n.LSFDE3:\n .long .LEFDE3-.LASFDE3\n.LASFDE3:\n .long .LASFDE3-.Lframe1\n .long .LFB9\n .long .LFE9-.LFB9\n .uleb128 0x4\n .long .LLSDA9\n .byte 0x4\n .long .LCFI2-.LFB9\n .byte 0xe\n .uleb128 0x8\n .byte 0x85\n .uleb128 0x2\n .byte 0x4\n .long .LCFI3-.LCFI2\n .byte 0xd\n .uleb128 0x5\n .byte 0x4\n .long .LCFI5-.LCFI3\n .byte 0x83\n .uleb128 0x3\n .align 4\n.LEFDE3:\n.LSFDE5:\n .long .LEFDE5-.LASFDE5\n.LASFDE5:\n .long .LASFDE5-.Lframe1\n .long .LFB8\n .long .LFE8-.LFB8\n .uleb128 0x4\n .long 0x0\n .byte 0x4\n .long .LCFI6-.LFB8\n .byte 0xe\n .uleb128 0x8\n .byte 0x85\n .uleb128 0x2\n .byte 0x4\n .long .LCFI7-.LCFI6\n .byte 0xd\n .uleb128 0x5\n .align 4\n.LEFDE5:\n .ident \"GCC: (GNU) 4.1.2 (Ubuntu 4.1.2-0ubuntu4)\"\n .section .note.GNU-stack,\"\",@progbits\n__cxa_"}, {"idx": "webquery-test-7", "doc": "How to succinctly, portably, and thoroughly seed the mt19937 PRNG?", "code": "std::random_devicestd::random_devicesysrandomCryptGenRandombool acquire_context(HCRYPTPROV *ctx)\n{\n if (!CryptAcquireContext(ctx, nullptr, nullptr, PROV_RSA_FULL, 0)) {\n return CryptAcquireContext(ctx, nullptr, nullptr, PROV_RSA_FULL, CRYPT_NEWKEYSET);\n }\n return true;\n}\n\n\nsize_t sysrandom(void* dst, size_t dstlen)\n{\n HCRYPTPROV ctx;\n if (!acquire_context(&ctx)) {\n throw std::runtime_error(\"Unable to initialize Win32 crypt library.\");\n }\n\n BYTE* buffer = reinterpret_cast<BYTE*>(dst);\n if(!CryptGenRandom(ctx, dstlen, buffer)) {\n throw std::runtime_error(\"Unable to generate random bytes.\");\n }\n\n if (!CryptReleaseContext(ctx, 0)) {\n throw std::runtime_error(\"Unable to release Win32 crypt library.\");\n }\n\n return dstlen;\n}\nsize_t sysrandom(void* dst, size_t dstlen)\n{\n char* buffer = reinterpret_cast<char*>(dst);\n std::ifstream stream(\"/dev/urandom\", std::ios_base::binary | std::ios_base::in);\n stream.read(buffer, dstlen);\n\n return dstlen;\n}\nstd::random_devicestd::uint_least32_t seed; \nsysrandom(&seed, sizeof(seed));\nstd::mt19937 gen(seed);\nMS_DEF_PROVMS_DEF_PROVMS_DEF_PROVMS_DEF_PROVgetrandomgetrandomgetrandomgetrandomgetrandom#if defined(__linux__) || defined(linux) || defined(__linux)\n# // Check the kernel version. `getrandom` is only Linux 3.17 and above.\n# include <linux/version.h>\n# if LINUX_VERSION_CODE >= KERNEL_VERSION(3,17,0)\n# define HAVE_GETRANDOM\n# endif\n#endif\n\n// also requires glibc 2.25 for the libc wrapper\n#if defined(HAVE_GETRANDOM)\n# include <sys/syscall.h>\n# include <linux/random.h>\n\nsize_t sysrandom(void* dst, size_t dstlen)\n{\n int bytes = syscall(SYS_getrandom, dst, dstlen, 0);\n if (bytes != dstlen) {\n throw std::runtime_error(\"Unable to read N bytes from CSPRNG.\");\n }\n\n return dstlen;\n}\n\n#elif defined(_WIN32)\n\n// Windows sysrandom here.\n\n#else\n\n// POSIX sysrandom here.\n\n#endif\n/dev/urandom#if defined(__OpenBSD__)\n# define HAVE_GETENTROPY\n#endif\n\n#if defined(HAVE_GETENTROPY)\n# include <unistd.h>\n\nsize_t sysrandom(void* dst, size_t dstlen)\n{\n int bytes = getentropy(dst, dstlen);\n if (bytes != dstlen) {\n throw std::runtime_error(\"Unable to read N bytes from CSPRNG.\");\n }\n\n return dstlen;\n}\n\n#endif\nbasic_filebufbasic_filebufsysrandomsize_t sysrandom(void* dst, size_t dstlen)\n{\n int fd = open(\"/dev/urandom\", O_RDONLY);\n if (fd == -1) {\n throw std::runtime_error(\"Unable to open /dev/urandom.\");\n }\n if (read(fd, dst, dstlen) != dstlen) {\n close(fd);\n throw std::runtime_error(\"Unable to read N bytes from CSPRNG.\");\n }\n\n close(fd);\n return dstlen;\n}\nFILEgetrandomgetrandom"}, {"idx": "webquery-test-8", "doc": "How do you add a timed delay to a C++ program?", "code": "sleep_forsleep_for#include <chrono>\n#include <thread>\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono; // nanoseconds, system_clock, seconds\n\n sleep_for(nanoseconds(10));\n sleep_until(system_clock::now() + seconds(1));\n}\nsleepsleepsleepsleepsleepsleepnanosecondsnanoseconds#include <chrono>\n#include <thread>\n\nint main() {\n using namespace std::this_thread; // sleep_for, sleep_until\n using namespace std::chrono_literals; // ns, us, ms, s, h, etc.\n using std::chrono::system_clock;\n\n sleep_for(10ns);\n sleep_until(system_clock::now() + 1s);\n}\n"}, {"idx": "webquery-test-9", "doc": "A good example for boost::algorithm::join", "code": "#include <boost/algorithm/string/join.hpp>\n#include <vector>\n#include <iostream>\n\nint main()\n{\n std::vector<std::string> list;\n list.push_back(\"Hello\");\n list.push_back(\"World!\");\n\n std::string joined = boost::algorithm::join(list, \", \");\n std::cout << joined << std::endl;\n}\nHello, World!\n"}, {"idx": "webquery-test-10", "doc": "How do I use CMake?", "code": "mkdir build-dir\ncd build-dir\ncmakecmake ..\nmakemake\nmakemakemakemakemakemakecmake"}, {"idx": "webquery-test-1", "doc": "How to overload std::swap()", "code": "std::swapclass X\n{\n // ...\n friend void swap(X& a, X& b)\n {\n using std::swap; // bring in swap for built-in types\n\n swap(a.base1, b.base1);\n swap(a.base2, b.base2);\n // ...\n swap(a.member1, b.member1);\n swap(a.member2, b.member2);\n // ...\n }\n};\n"}, {"idx": "webquery-test-2", "doc": "std::next_permutation Implementation Explanation", "code": "1 2 3 4\n1 2 4 3\n1 3 2 4\n1 3 4 2\n1 4 2 3\n1 4 3 2\n2 1 3 4\n...\n11while (true)\n{\n It j = i;\n --i;\n\n if (*i < *j)\n { // ...\n }\n\n if (i == begin)\n { // ...\n }\n}\njjjjif (i == begin)if (i == begin)if...\n1 4 3 2\n2 1 3 4\n...\n2 4 3 1\n3 1 2 4\n...\nIt k = end;\n\nwhile (!(*i < *--k))\n /* pass */;\n\niter_swap(i, k);\nreverse(j, end);\nreturn true;\niter_swap()iter_swap()"}, {"idx": "webquery-test-3", "doc": "Why does the delete[] syntax exist in C++?", "code": "delete[]delete[]deletedeletedeletedeletedeletedeletedeletedeletedelete"}, {"idx": "webquery-test-4", "doc": "How to tell where a header file is included from?", "code": "g++ -H ...\n"}, {"idx": "webquery-test-5", "doc": "Fixing Segmentation faults in C++", "code": "-g-g-g-g-g-g"}, {"idx": "webquery-test-6", "doc": "'size_t' vs 'container::size_type'", "code": "size_typesize_typesize_typesize_typecontainer::size_type"}, {"idx": "webquery-test-7", "doc": "What is the meaning of the term \"free function\" in C++?", "code": "struct X {\n void f() {} // not a free function\n};\nvoid g() {} // free function\nint h(int, int) { return 1; } // also a free function\n"}, {"idx": "webquery-test-8", "doc": "Does const mean thread-safe in C++11?", "code": "constthisconstconstconstconstconstconstclass rect {\n int width = 0, height = 0;\n\npublic:\n /*...*/\n void set_size( int new_width, int new_height ) {\n width = new_width;\n height = new_height;\n }\n int area() const {\n return width * height;\n }\n};\nareaareaarearectrectrectrectrectrectrectrectrectrectclass rect {\n int width = 0, height = 0;\n\n mutable int cached_area = 0;\n mutable bool cached_area_valid = true;\n\npublic:\n /*...*/\n void set_size( int new_width, int new_height ) {\n cached_area_valid = ( width == new_width && height == new_height );\n width = new_width;\n height = new_height;\n }\n int area() const {\n if( !cached_area_valid ) {\n cached_area = width;\n cached_area *= height;\n cached_area_valid = true;\n }\n return cached_area;\n }\n};\nintareaarearectrectclass rect {\n int width = 0, height = 0;\n\n mutable std::mutex cache_mutex;\n mutable int cached_area = 0;\n mutable bool cached_area_valid = true;\n\npublic:\n /*...*/\n void set_size( int new_width, int new_height ) {\n if( new_width != width || new_height != height )\n {\n std::lock_guard< std::mutex > guard( cache_mutex );\n \n cached_area_valid = false;\n }\n width = new_width;\n height = new_height;\n }\n int area() const {\n std::lock_guard< std::mutex > guard( cache_mutex );\n \n if( !cached_area_valid ) {\n cached_area = width;\n cached_area *= height;\n cached_area_valid = true;\n }\n return cached_area;\n }\n};\nareaareaareaareaareaarearectrectconstconst"}, {"idx": "webquery-test-1", "doc": "Format Curly Braces on Same Line in C++ VSCode", "code": "\"{ BasedOnStyle: Google, IndentWidth: 4 }\"\"C_Cpp.clang_format_fallbackStyle\": \"{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}\"\n\"C_Cpp.clang_format_fallbackStyle\": \"{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}\"\n"}, {"idx": "webquery-test-2", "doc": "How to initialize a private static const map in C++?", "code": "//myClass.hpp\nclass myClass {\n private:\n static map<int,int> myMap;\n};\n//myClass.cpp\nmap<int,int> myClass::myMap = {\n {1, 2},\n {3, 4},\n {5, 6}\n};\n"}, {"idx": "webquery-test-3", "doc": "What does string::npos mean in this code?", "code": "static const size_t npos = -1;\n"}, {"idx": "webquery-test-4", "doc": "When to use \"new\" and when not to, in C++?", "code": "newnewnewvoid foo()\n{\n Point p = Point(0,0);\n} // p is now destroyed.\n\nfor (...)\n{\n Point p = Point(0,0);\n} // p is destroyed after each loop\nnewclass Foo\n{\n\n Point p;\n}; // p will be automatically destroyed when foo is.\nnewnewvoid foo(int size)\n{\n Point* pointArray = new Point[size];\n ...\n delete [] pointArray;\n}\n"}, {"idx": "webquery-test-5", "doc": "Compiling simple Hello World program on OS X via command line", "code": "g++ hw.cpp\n./a.out\ng++g++#include <iostream>\n\nint main()\n{\n std::cout << \"Hello world!\" << std::endl;\n}\n"}, {"idx": "webquery-test-6", "doc": "What is the difference between cout, cerr, clog of iostream header in c++? When to use which one?", "code": "std::coutstd::coutstd::coutstd::cerrstdoutstdoutstdoutstdoutstdoutstdoutstdoutstdout"}, {"idx": "webquery-test-1", "doc": "Is there a better way to express nested namespaces in C++ within the header", "code": "namespace A::B::C {\n}\nnamespace A { namespace B { namespace C {\n} } }\n"}, {"idx": "webquery-test-2", "doc": "When should I make explicit use of the `this` pointer?", "code": "this->this->template<class T>\nstruct A {\n T i;\n};\n\ntemplate<class T>\nstruct B : A<T> {\n T foo() {\n return this->i; //standard accepted by all compilers \n //return i; //clang and gcc will fail\n //clang 13.1.6: use of undeclared identifier 'i'\n //gcc 11.3.0: 'i' was not declared in this scope\n //Microsoft C++ Compiler 2019 will accept it\n }\n\n};\n\nint main() {\n B<int> b;\n b.foo();\n}\nthis->this->this->this->this->this->this->template<class T>\nstruct B : A<T> {\n int foo() {\n return A<T>::i; // explicitly refer to a variable in the base class \n //where 'i' is now known to exist\n }\n\n};\n"}, {"idx": "webquery-test-3", "doc": "undefined reference to template function", "code": "namespace Util\n{\n template<class T>\n QString convert2QString(T type , int digits=0);\n}\n#include \"util_impl.h\"\nnamespace Util\n{\n template<class T>\n QString convert2QString(T type, int digits=0)\n {\n using std::string;\n\n string temp = (boost::format(\"%1\") % type).str();\n\n return QString::fromStdString(temp);\n }\n}\n"}, {"idx": "webquery-test-4", "doc": "How to create a static library with g++?", "code": "g++ -c header.cpp\nar rvs header.a header.o\ng++ main.cpp header.a\n"}, {"idx": "webquery-test-5", "doc": "Downcasting shared_ptr<Base> to shared_ptr<Derived>?", "code": "dynamic_pointer_castdynamic_pointer_caststd::shared_ptr<Base> base (new Derived());\nstd::shared_ptr<Derived> derived =\n std::dynamic_pointer_cast<Derived> (base);\nstd::static_pointer_cast"}, {"idx": "webquery-test-6", "doc": "Why do we need argc while there is always a null at the end of argv?", "code": "argv[argc]==NULLargc"}, {"idx": "webquery-test-7", "doc": "Can I call memcpy() and memmove() with \"number of bytes\" set to zero?", "code": "size_t nsize_t n"}, {"idx": "webquery-test-8", "doc": "How to reuse an ostringstream?", "code": "// clear, because eof or other bits may be still set. \ns.clear();\ns.str(\"\");\ns.clear();\ns.seekp(0); // for outputs: seek put ptr to start\ns.seekg(0); // for inputs: seek get ptr to start\nstrstd::ostringstream s;\ns << \"hello\";\ns.seekp(0);\ns << \"b\";\nassert(s.str() == \"bello\");\nstd::endsstd::ostringstream s;\ns << \"hello\";\ns.seekp(0);\ns << \"b\" << std::ends;\nassert(s.str().size() == 5 && std::strlen(s.str().data()) == 1);\nstd::endsstd::endsstd::ends"}, {"idx": "webquery-test-1", "doc": "Why does the ternary operator with commas evaluate only one expression in the true case?", "code": "??someValuesomeValuesomeValuesomeValue--x--xsomeValue?++x,++y:--x\n++x,++y++x,++y++x,++y++x,++ysomeValue?someValue?someValue?someValue?--y(someValue?(++x,++y):--x), --y;\nsomeValuesomeValue(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)(someValue?(++x,++y):--x)--x, --ysomeValue?++x,++y:(--x, --y);\n"}, {"idx": "webquery-test-2", "doc": "Using std Namespace", "code": "std::stringstd::stringstd::stringstd::stringstd::stringusing namespace std;stdstdstdstdstdstd::countstd::count#include <algorithm>\nusing namespace std;\n\nint count = 0;\n\nint increment()\n{\n return ++count; // error, identifier count is ambiguous\n}\nstd::countstd::count#include <algorithm>\nusing namespace std;\n\nint increment()\n{\n static int count = 0;\n return ++count;\n}\nstd::countstd::countstd::count#include <algorithm>\n\nint increment()\n{\n using namespace std;\n static int count = 0;\n return ++count;\n}\ncountcountcountcountcountcountcountcount#include <algorithm>\n\nint count = 0;\n\nint increment()\n{\n using namespace std;\n return ++count; // error ambiguous\n}\n"}, {"idx": "webquery-test-3", "doc": "visual c++: #include files from other projects in the same solution", "code": "#include \"filename.h\"\n// In project settings\nAdditional Include Directories ..\\..\\libroot\n\n// In code\n#include \"lib1/lib1.h\" // path is relative to libroot\n#include \"lib2/lib2.h\" // path is relative to libroot\n"}, {"idx": "webquery-test-4", "doc": "What is an SDL renderer?", "code": "SDL_WindowSDL_RendererSDL_RendererSDL_RendererSDL_RendererSDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_SetRenderDrawColor(renderer, r, g, b, a);SDL_RendererSDL_RendererSDL_RendererSDL_RendererSDL_RendererSDL_RendererSDL_Texture* SDL_CreateTextureFromSurface(SDL_Renderer* renderer,\n SDL_Surface* surface)\nSDL_FreeSurface( SDL_Surface* surface )\nSDL_SurfaceSDL_Surfacex, yx, y0, 00, 00, 0"}, {"idx": "webquery-test-5", "doc": "Floating point vs integer calculations on modern hardware", "code": "-O3short add/sub: 1.005460 [0]\nshort mul/div: 3.926543 [0]\nlong add/sub: 0.000000 [0]\nlong mul/div: 7.378581 [0]\nlong long add/sub: 0.000000 [0]\nlong long mul/div: 7.378593 [0]\nfloat add/sub: 0.993583 [0]\nfloat mul/div: 1.821565 [0]\ndouble add/sub: 0.993884 [0]\ndouble mul/div: 1.988664 [0]\n-O3short add/sub: 0.553863 [0]\nshort mul/div: 12.509163 [0]\nlong add/sub: 0.556912 [0]\nlong mul/div: 12.748019 [0]\nlong long add/sub: 5.298999 [0]\nlong long mul/div: 20.461186 [0]\nfloat add/sub: 2.688253 [0]\nfloat mul/div: 4.683886 [0]\ndouble add/sub: 2.700834 [0]\ndouble mul/div: 4.646755 [0]\n#include <stdio.h>\n#ifdef _WIN32\n#include <sys/timeb.h>\n#else\n#include <sys/time.h>\n#endif\n#include <time.h>\n#include <cstdlib>\n\ndouble\nmygettime(void) {\n# ifdef _WIN32\n struct _timeb tb;\n _ftime(&tb);\n return (double)tb.time + (0.001 * (double)tb.millitm);\n# else\n struct timeval tv;\n if(gettimeofday(&tv, 0) < 0) {\n perror(\"oops\");\n }\n return (double)tv.tv_sec + (0.000001 * (double)tv.tv_usec);\n# endif\n}\n\ntemplate< typename Type >\nvoid my_test(const char* name) {\n Type v = 0;\n // Do not use constants or repeating values\n // to avoid loop unroll optimizations.\n // All values >0 to avoid division by 0\n // Perform ten ops/iteration to reduce\n // impact of ++i below on measurements\n Type v0 = (Type)(rand() % 256)/16 + 1;\n Type v1 = (Type)(rand() % 256)/16 + 1;\n Type v2 = (Type)(rand() % 256)/16 + 1;\n Type v3 = (Type)(rand() % 256)/16 + 1;\n Type v4 = (Type)(rand() % 256)/16 + 1;\n Type v5 = (Type)(rand() % 256)/16 + 1;\n Type v6 = (Type)(rand() % 256)/16 + 1;\n Type v7 = (Type)(rand() % 256)/16 + 1;\n Type v8 = (Type)(rand() % 256)/16 + 1;\n Type v9 = (Type)(rand() % 256)/16 + 1;\n\n double t1 = mygettime();\n for (size_t i = 0; i < 100000000; ++i) {\n v += v0;\n v -= v1;\n v += v2;\n v -= v3;\n v += v4;\n v -= v5;\n v += v6;\n v -= v7;\n v += v8;\n v -= v9;\n }\n // Pretend we make use of v so compiler doesn't optimize out\n // the loop completely\n printf(\"%s add/sub: %f [%d]\\n\", name, mygettime() - t1, (int)v&1);\n t1 = mygettime();\n for (size_t i = 0; i < 100000000; ++i) {\n v /= v0;\n v *= v1;\n v /= v2;\n v *= v3;\n v /= v4;\n v *= v5;\n v /= v6;\n v *= v7;\n v /= v8;\n v *= v9;\n }\n // Pretend we make use of v so compiler doesn't optimize out\n // the loop completely\n printf(\"%s mul/div: %f [%d]\\n\", name, mygettime() - t1, (int)v&1);\n}\n\nint main() {\n my_test< short >(\"short\");\n my_test< long >(\"long\");\n my_test< long long >(\"long long\");\n my_test< float >(\"float\");\n my_test< double >(\"double\");\n\n return 0;\n}\n"}, {"idx": "webquery-test-6", "doc": "Defining static const integer members in class definition", "code": "staticstaticstatic"}, {"idx": "webquery-test-7", "doc": "Best introduction to C++ template metaprogramming?", "code": "NullTypeNullType"}, {"idx": "webquery-test-8", "doc": "Is cout synchronized/thread-safe?", "code": "coutcout// in one thread\ncout << \"The operation took \" << result << \" seconds.\";\n\n// in another thread\ncout << \"Hello world! Hello \" << name << \"!\";\n"}, {"idx": "webquery-test-9", "doc": "C++ performance vs. Java/C#", "code": "usingusingusingusingusingusingusing"}, {"idx": "webquery-test-10", "doc": "Unit testing of private methods", "code": "#define"}, {"idx": "webquery-test-1", "doc": "C++ Tuple vs Struct", "code": "struct StructData {\n int X;\n int Y;\n double Cost;\n std::string Label;\n\n bool operator==(const StructData &rhs) {\n return std::tie(X,Y,Cost, Label) == std::tie(rhs.X, rhs.Y, rhs.Cost, rhs.Label);\n }\n\n bool operator<(const StructData &rhs) {\n return X < rhs.X || (X == rhs.X && (Y < rhs.Y || (Y == rhs.Y && (Cost < rhs.Cost || (Cost == rhs.Cost && Label < rhs.Label)))));\n }\n};\n\nusing TupleData = std::tuple<int, int, double, std::string>;\nstd::vector<StructData> test_struct_data(const size_t N) {\n std::vector<StructData> data(N);\n std::transform(data.begin(), data.end(), data.begin(), [N](auto item) {\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution<> dis(0, N);\n item.X = dis(gen);\n item.Y = dis(gen);\n item.Cost = item.X * item.Y;\n item.Label = std::to_string(item.Cost);\n return item;\n });\n return data;\n}\n\nstd::vector<TupleData> test_tuple_data(const std::vector<StructData> &input) {\n std::vector<TupleData> data(input.size());\n std::transform(input.cbegin(), input.cend(), data.begin(),\n [](auto item) { return std::tie(item.X, item.Y, item.Cost, item.Label); });\n return data;\n}\n\nconstexpr int NumberOfSamples = 10;\nconstexpr int NumberOfIterations = 5;\nconstexpr size_t N = 1000000;\nauto const sdata = test_struct_data(N);\nauto const tdata = test_tuple_data(sdata);\n\nCELERO_MAIN\n\nBASELINE(Sort, struct, NumberOfSamples, NumberOfIterations) {\n std::vector<StructData> data(sdata.begin(), sdata.end());\n std::sort(data.begin(), data.end());\n // print(data);\n\n}\n\nBENCHMARK(Sort, tuple, NumberOfSamples, NumberOfIterations) {\n std::vector<TupleData> data(tdata.begin(), tdata.end());\n std::sort(data.begin(), data.end());\n // print(data);\n}\nCelero\nTimer resolution: 0.001000 us\n-----------------------------------------------------------------------------------------------------------------------------------------------\n Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec | \n-----------------------------------------------------------------------------------------------------------------------------------------------\nSort | struct | Null | 10 | 5 | 1.00000 | 196663.40000 | 5.08 | \nSort | tuple | Null | 10 | 5 | 0.92471 | 181857.20000 | 5.50 | \nComplete.\nCelero\nTimer resolution: 0.001000 us\n-----------------------------------------------------------------------------------------------------------------------------------------------\n Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec | \n-----------------------------------------------------------------------------------------------------------------------------------------------\nSort | struct | Null | 10 | 5 | 1.00000 | 219096.00000 | 4.56 | \nSort | tuple | Null | 10 | 5 | 0.91463 | 200391.80000 | 4.99 | \nComplete.\nbool operator<(const StructData &rhs) {\n return std::tie(X,Y,Cost, Label) < std::tie(rhs.X, rhs.Y, rhs.Cost, rhs.Label);\n}\n\nCelero\nTimer resolution: 0.001000 us\n-----------------------------------------------------------------------------------------------------------------------------------------------\n Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec | \n-----------------------------------------------------------------------------------------------------------------------------------------------\nSort | struct | Null | 10 | 5 | 1.00000 | 200508.20000 | 4.99 | \nSort | tuple | Null | 10 | 5 | 0.90033 | 180523.80000 | 5.54 | \nComplete.\nstruct StructData {\n int X;\n int Y;\n double Cost;\n std::string Label;\n\n bool operator==(const StructData &rhs) {\n return std::tie(X,Y,Cost, Label) == std::tie(rhs.X, rhs.Y, rhs.Cost, rhs.Label);\n }\n\n void swap(StructData & other)\n {\n std::swap(X, other.X);\n std::swap(Y, other.Y);\n std::swap(Cost, other.Cost);\n std::swap(Label, other.Label);\n } \n\n bool operator<(const StructData &rhs) {\n return std::tie(X,Y,Cost, Label) < std::tie(rhs.X, rhs.Y, rhs.Cost, rhs.Label);\n }\n};\nCelero\nTimer resolution: 0.001000 us\n-----------------------------------------------------------------------------------------------------------------------------------------------\n Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec | \n-----------------------------------------------------------------------------------------------------------------------------------------------\nSort | struct | Null | 10 | 5 | 1.00000 | 176308.80000 | 5.67 | \nSort | tuple | Null | 10 | 5 | 1.02699 | 181067.60000 | 5.52 | \nComplete.\nCelero\nTimer resolution: 0.001000 us\n-----------------------------------------------------------------------------------------------------------------------------------------------\n Group | Experiment | Prob. Space | Samples | Iterations | Baseline | us/Iteration | Iterations/sec | \n-----------------------------------------------------------------------------------------------------------------------------------------------\nSort | struct | Null | 10 | 5 | 1.00000 | 198844.80000 | 5.03 | \nSort | tuple | Null | 10 | 5 | 1.00601 | 200039.80000 | 5.00 | \nComplete.\n"}, {"idx": "webquery-test-2", "doc": "Why is there no std::stou?", "code": "strtoustrtoustrtoustrtoustrtoustoistoistoistoistoistoi"}, {"idx": "webquery-test-3", "doc": "Example for boost shared_mutex (multiple reads/one write)?", "code": "boost::shared_mutex _access;\nvoid reader()\n{\n boost::shared_lock< boost::shared_mutex > lock(_access);\n // do work here, without anyone having exclusive access\n}\n\nvoid conditional_writer()\n{\n boost::upgrade_lock< boost::shared_mutex > lock(_access);\n // do work here, without anyone having exclusive access\n\n if (something) {\n boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);\n // do work here, but now you have exclusive access\n }\n\n // do more work here, without anyone having exclusive access\n}\n\nvoid unconditional_writer()\n{\n boost::unique_lock< boost::shared_mutex > lock(_access);\n // do work here, with exclusive access\n}\n"}, {"idx": "webquery-test-4", "doc": "How to overcome \"'aclocal-1.15' is missing on your system\" warning?", "code": "./configure./configure.zip.zip.zip.zip"}, {"idx": "webquery-test-5", "doc": "When do I really need to use atomic<bool> instead of bool?", "code": "std::atomic*std::atomic<bool>std::atomic<bool>"}, {"idx": "webquery-test-6", "doc": "Calling Objective-C method from C++ member function?", "code": "#ifndef __MYOBJECT_C_INTERFACE_H__\n#define __MYOBJECT_C_INTERFACE_H__\n\n// This is the C \"trampoline\" function that will be used\n// to invoke a specific Objective-C method FROM C++\nint MyObjectDoSomethingWith (void *myObjectInstance, void *parameter);\n#endif\n#import \"MyObject-C-Interface.h\"\n\n// An Objective-C class that needs to be accessed from C++\n@interface MyObject : NSObject\n{\n int someVar;\n}\n\n// The Objective-C member function you want to call from C++\n- (int) doSomethingWith:(void *) aParameter;\n@end\n#import \"MyObject.h\"\n\n@implementation MyObject\n\n// C \"trampoline\" function to invoke Objective-C method\nint MyObjectDoSomethingWith (void *self, void *aParameter)\n{\n // Call the Objective-C method using Objective-C syntax\n return [(id) self doSomethingWith:aParameter];\n}\n\n- (int) doSomethingWith:(void *) aParameter\n{\n // The Objective-C function you wanted to call from C++.\n // do work here..\n return 21 ; // half of 42\n}\n@end\n#include \"MyCPPClass.h\"\n#include \"MyObject-C-Interface.h\"\n\nint MyCPPClass::someMethod (void *objectiveCObject, void *aParameter)\n{\n // To invoke an Objective-C method from C++, use\n // the C trampoline function\n return MyObjectDoSomethingWith (objectiveCObject, aParameter);\n}\n.m#ifndef __MYOBJECT_C_INTERFACE_H__\n#define __MYOBJECT_C_INTERFACE_H__\n\nclass MyClassImpl\n{\npublic:\n MyClassImpl ( void );\n ~MyClassImpl( void );\n\n void init( void );\n int doSomethingWith( void * aParameter );\n void logMyMessage( char * aCStr );\n\nprivate:\n void * self;\n};\n\n#endif\n#import \"MyObject-C-Interface.h\"\n\n@interface MyObject : NSObject\n{\n int someVar;\n}\n\n- (int) doSomethingWith:(void *) aParameter;\n- (void) logMyMessage:(char *) aCStr;\n\n@end\n#import \"MyObject.h\"\n\n@implementation MyObject\n\nMyClassImpl::MyClassImpl( void )\n : self( NULL )\n{ }\n\nMyClassImpl::~MyClassImpl( void )\n{\n [(id)self dealloc];\n}\n\nvoid MyClassImpl::init( void )\n{ \n self = [[MyObject alloc] init];\n}\n\nint MyClassImpl::doSomethingWith( void *aParameter )\n{\n return [(id)self doSomethingWith:aParameter];\n}\n\nvoid MyClassImpl::logMyMessage( char *aCStr )\n{\n [(id)self doLogMessage:aCStr];\n}\n\n- (int) doSomethingWith:(void *) aParameter\n{\n int result;\n\n // ... some code to calculate the result\n\n return result;\n}\n\n- (void) logMyMessage:(char *) aCStr\n{\n NSLog( aCStr );\n}\n\n@end\n#ifndef __MYCPP_CLASS_H__\n#define __MYCPP_CLASS_H__\n\nclass MyClassImpl;\n\nclass MyCPPClass\n{\n enum { cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING = 42 };\npublic:\n MyCPPClass ( void );\n ~MyCPPClass( void );\n\n void init( void );\n void doSomethingWithMyClass( void );\n\nprivate:\n MyClassImpl * _impl;\n int _myValue;\n};\n\n#endif\n#include \"MyCPPClass.h\"\n#include \"MyObject-C-Interface.h\"\n\nMyCPPClass::MyCPPClass( void )\n : _impl ( NULL )\n{ }\n\nvoid MyCPPClass::init( void )\n{\n _impl = new MyClassImpl();\n}\n\nMyCPPClass::~MyCPPClass( void )\n{\n if ( _impl ) { delete _impl; _impl = NULL; }\n}\n\nvoid MyCPPClass::doSomethingWithMyClass( void )\n{\n int result = _impl->doSomethingWith( _myValue );\n if ( result == cANSWER_TO_LIFE_THE_UNIVERSE_AND_EVERYTHING )\n {\n _impl->logMyMessage( \"Hello, Arthur!\" );\n }\n else\n {\n _impl->logMyMessage( \"Don't worry.\" );\n }\n}\n"}, {"idx": "webquery-test-7", "doc": "Difference between std::pair and std::tuple with only two members?", "code": "std::tuplestd::tuplestd::tuplestd::tuplestd::tuplestd::tuplestd::tuplestd::tuple"}, {"idx": "webquery-test-8", "doc": "What exception classes are in the standard C++ library", "code": "std::exception <exception> interface (debatable if you should catch this)\n std::bad_alloc <new> failure to allocate storage\n std::bad_array_new_length <new> invalid array length\n std::bad_cast <typeinfo> execution of an invalid dynamic-cast\n std::bad_exception <exception> signifies an incorrect exception was thrown\n std::bad_function_call <functional> thrown by \"null\" std::function\n std::bad_typeid <typeinfo> using typeinfo on a null pointer\n std::bad_weak_ptr <memory> constructing a shared_ptr from a bad weak_ptr\n std::logic_error <stdexcept> errors detectable before the program executes\n std::domain_error <stdexcept> parameter outside the valid range\n std::future_error <future> violated a std::promise/std::future condition\n std::invalid_argument <stdexcept> invalid argument\n std::length_error <stdexcept> length exceeds its maximum allowable size\n std::out_of_range <stdexcept> argument value not in its expected range\n std::runtime_error <stdexcept> errors detectable when the program executes\n std::overflow_error <stdexcept> arithmetic overflow error.\n std::underflow_error <stdexcept> arithmetic underflow error.\n std::range_error <stdexcept> range errors in internal computations\n std::regex_error <regex> errors from the regular expression library.\n std::system_error <system_error> from operating system or other C API\n std::ios_base::failure <ios> Input or output error\nlogic_errorlogic_error"}, {"idx": "webquery-test-1", "doc": "C++ convert vector<int> to vector<double>", "code": "std::vectorstd::vector<int> intVec;\nstd::vector<double> doubleVec(intVec.begin(), intVec.end());\n"}, {"idx": "webquery-test-2", "doc": "How to use doxygen to create UML class diagrams from C++ source", "code": "COLLABORATION_GRAPH = YESEXTRACT_ALL = YES\nCLASS_DIAGRAMS = YES\nHIDE_UNDOC_RELATIONS = NO\nHAVE_DOT = YES\nCLASS_GRAPH = YES\nCOLLABORATION_GRAPH = YES\nUML_LOOK = YES\nUML_LIMIT_NUM_FIELDS = 50\nTEMPLATE_RELATIONS = YES\nDOT_GRAPH_MAX_NODES = 100\nMAX_DOT_GRAPH_DEPTH = 0\nDOT_TRANSPARENT = YES\nCLASS_GRAPH=YESCLASS_GRAPH=YESDOT_IMAGE_FORMAT = svgDOT_IMAGE_FORMAT = svgDOT_GRAPH_MAX_NODES"}, {"idx": "webquery-test-3", "doc": "What happens if I read a map's value where the key does not exist?", "code": "map::operator[]map::atmap::operator[]T& operator[](const key_type& x);T& operator[](key_type&& x);"}, {"idx": "webquery-test-4", "doc": "Why don't C++ compilers optimize this conditional boolean assignment as an unconditional assignment?", "code": "flagflagconst bool foo = true;\n\nint main()\n{\n func(const_cast<bool&>(foo));\n}\nfunc()"}, {"idx": "webquery-test-5", "doc": "Why explicitly delete the constructor instead of making it private?", "code": "//deleted constructor\nclass Foo\n{ \n public: \n Foo() = delete; \n public:\n static void foo();\n};\n\nvoid Foo::foo()\n{\n Foo f; //illegal\n}\n//private constructor\nclass Foo\n{ \n private: \n Foo() {} \n public:\n static void foo();\n};\n\nvoid Foo::foo()\n{\n Foo f; //legal\n}\nprivateprivateprivate"}, {"idx": "webquery-test-6", "doc": "Program being compiled differently in 3 major C++ compilers. Which one is right?", "code": "B::A ba; // object of type A\nA::A a; // error, A::A is not a type name\nstruct A::A a2; // object of type A\nCCCC"}, {"idx": "webquery-test-7", "doc": "How to Use CCache with CMake?", "code": "-DCMAKE_CXX_COMPILER_LAUNCHER=ccache\n"}, {"idx": "webquery-test-8", "doc": "How to create a dynamic array of integers", "code": "int main()\n{\n int size;\n\n std::cin >> size;\n\n int *array = new int[size];\n\n delete [] array;\n\n return 0;\n}\ndeletedelete"}, {"idx": "webquery-test-1", "doc": "Member initialization while using delegated constructor", "code": "linesTokenizer::Tokenizer(std::stringstream *lines)\n : lines(lines)\n{\n}\nTokenizer::Tokenizer()\n : Tokenizer(nullptr)\n{\n}\n"}, {"idx": "webquery-test-2", "doc": "Using C++ library in C code", "code": "extern \"C\"extern \"C\" int foo(char *bar)\n{\n return realFoo(std::string(bar));\n}\nfoo()foo()"}, {"idx": "webquery-test-3", "doc": "Is it intended by the C++ standards committee that in C++11 unordered_map destroys what it inserts?", "code": "bits/stl_map.h template<typename _Pair, typename = typename\n std::enable_if<std::is_constructible<value_type,\n _Pair&&>::value>::type>\n std::pair<iterator, bool>\n insert(_Pair&& __x)\n { return _M_t._M_insert_unique(std::forward<_Pair>(__x)); }\nbits/unordered_map.h template<typename _Pair, typename = typename\n std::enable_if<std::is_constructible<value_type,\n _Pair&&>::value>::type>\n std::pair<iterator, bool>\n insert(_Pair&& __x)\n { return _M_h.insert(std::move(__x)); }\nstd::movestd::move"}, {"idx": "webquery-test-4", "doc": "C++ catch blocks - catch exception by value or reference?", "code": "MyExceptionMyExceptionMyExceptionMyException"}, {"idx": "webquery-test-5", "doc": "In C++, should I bother to cache variables, or let the compiler do the optimization? (Aliasing)", "code": "unoptimized.cppstruct bitmap_t\n{\n long long width;\n} bitmap;\n\nint main(int argc, char** argv)\n{\n for (unsigned x = 0 ; x < static_cast<unsigned>(bitmap.width) ; ++x)\n {\n argv[x][0] = '\\0';\n }\n return 0;\n}\noptimized.cppstruct bitmap_t\n{\n long long width;\n} bitmap;\n\nint main(int argc, char** argv)\n{\n const unsigned width = static_cast<unsigned>(bitmap.width);\n for (unsigned x = 0 ; x < width ; ++x)\n {\n argv[x][0] = '\\0';\n }\n return 0;\n}\n$ g++ -s -O3 unoptimized.cpp$ g++ -s -O3 unoptimized.cpp .file \"unoptimized.cpp\"\n .text\n .p2align 4,,15\n.globl main\n .type main, @function\nmain:\n.LFB0:\n .cfi_startproc\n .cfi_personality 0x3,__gxx_personality_v0\n movl bitmap(%rip), %eax\n testl %eax, %eax\n je .L2\n xorl %eax, %eax\n .p2align 4,,10\n .p2align 3\n.L3:\n mov %eax, %edx\n addl $1, %eax\n movq (%rsi,%rdx,8), %rdx\n movb $0, (%rdx)\n cmpl bitmap(%rip), %eax\n jb .L3\n.L2:\n xorl %eax, %eax\n ret\n .cfi_endproc\n.LFE0:\n .size main, .-main\n.globl bitmap\n .bss\n .align 8\n .type bitmap, @object\n .size bitmap, 8\nbitmap:\n .zero 8\n .ident \"GCC: (GNU) 4.4.7 20120313 (Red Hat 4.4.7-16)\"\n .section .note.GNU-stack,\"\",@progbits\n .file \"optimized.cpp\"\n .text\n .p2align 4,,15\n.globl main\n .type main, @function\nmain:\n.LFB0:\n .cfi_startproc\n .cfi_personality 0x3,__gxx_personality_v0\n movl bitmap(%rip), %eax\n testl %eax, %eax\n je .L2\n subl $1, %eax\n leaq 8(,%rax,8), %rcx\n xorl %eax, %eax\n .p2align 4,,10\n .p2align 3\n.L3:\n movq (%rsi,%rax), %rdx\n addq $8, %rax\n cmpq %rcx, %rax\n movb $0, (%rdx)\n jne .L3\n.L2:\n xorl %eax, %eax\n ret\n .cfi_endproc\n.LFE0:\n .size main, .-main\n.globl bitmap\n .bss\n .align 8\n .type bitmap, @object\n .size bitmap, 8\nbitmap:\n .zero 8\n .ident \"GCC: (GNU) 4.4.7 20120313 (Red Hat 4.4.7-16)\"\n .section .note.GNU-stack,\"\",@progbits\n$ diff -uN unoptimized.s optimized.s\n--- unoptimized.s 2015-11-24 16:11:55.837922223 +0000\n+++ optimized.s 2015-11-24 16:12:02.628922941 +0000\n@@ -1,4 +1,4 @@\n- .file \"unoptimized.cpp\"\n+ .file \"optimized.cpp\"\n .text\n .p2align 4,,15\n .globl main\n@@ -10,16 +10,17 @@\n movl bitmap(%rip), %eax\n testl %eax, %eax\n je .L2\n+ subl $1, %eax\n+ leaq 8(,%rax,8), %rcx\n xorl %eax, %eax\n .p2align 4,,10\n .p2align 3\n .L3:\n- mov %eax, %edx\n- addl $1, %eax\n- movq (%rsi,%rdx,8), %rdx\n+ movq (%rsi,%rax), %rdx\n+ addq $8, %rax\n+ cmpq %rcx, %rax\n movb $0, (%rdx)\n- cmpl bitmap(%rip), %eax\n- jb .L3\n+ jne .L3\n .L2:\n xorl %eax, %eax\n ret\nlealealealea"}, {"idx": "webquery-test-1", "doc": "Why use std::make_unique in C++17?", "code": "newnewmake_sharedmake_sharedmake_sharedmake_shared"}, {"idx": "webquery-test-2", "doc": "How to pass parameters correctly?", "code": "void foo(my_class& obj)\n{\n // Modify obj here...\n}\nconstvoid foo(my_class const& obj)\n{\n // Observe obj here\n}\nstd::move()intintintvoid foo(my_class obj) // One copy or one move here, but not working on\n // the original object...\n{\n // Working on obj...\n\n // Possibly move from obj if the result has to be stored somewhere...\n}\nfoo()my_classmy_classmy_class// Overload for lvalues\nvoid foo(my_class const& obj) // No copy, no move (just reference binding)\n{\n my_class copyOfObj = obj; // Copy!\n // Working on copyOfObj...\n}\n\n// Overload for rvalues\nvoid foo(my_class&& obj) // No copy, no move (just reference binding)\n{\n my_class copyOfObj = std::move(obj); // Move! \n // Notice, that invoking std::move() is \n // necessary here, because obj is an\n // *lvalue*, even though its type is \n // \"rvalue reference to my_class\".\n // Working on copyOfObj...\n}\nfoo()template<typename C>\nvoid foo(C&& obj) // No copy, no move (just reference binding)\n// ^^^\n// Beware, this is not always an rvalue reference! This will \"magically\"\n// resolve into my_class& if an lvalue is passed, and my_class&& if an\n// rvalue is passed\n{\n my_class copyOfObj = std::forward<C>(obj); // Copy if lvalue, move if rvalue\n // Working on copyOfObj...\n}\nstd::forwardtemplate<typename C>\nvoid foo(C&& obj)\n{\n bar(std::forward<C>(obj), std::forward<C>(obj)); // Dangerous!\n}\nCreditCard// Here you are passing a temporary (OK! temporaries are rvalues)\nAccount acc(\"asdasd\",345, CreditCard(\"12345\",2,2015,1001));\n\nCreditCard cc(\"12345\",2,2015,1001);\n// Here you are passing the result of std::move (OK! that's also an rvalue)\nAccount acc(\"asdasd\",345, std::move(cc));\nCreditCard cc(\"12345\",2,2015,1001);\nAccount acc(\"asdasd\",345, cc); // ERROR! cc is an lvalue\nccCreditCardCreditCardCreditCardCreditCardAccount(std::string number, float amount, CreditCard const& creditCard) \n: number(number), amount(amount), creditCard(creditCard) // copy here\n{ }\n\nAccount(std::string number, float amount, CreditCard&& creditCard) \n: number(number), amount(amount), creditCard(std::move(creditCard)) // move here\n{ }\nstd::forward<>template<typename C>\nAccount(std::string number, float amount, C&& creditCard) \n: number(number), amount(amount), creditCard(std::forward<C>(creditCard)) { }\nCCAccount(std::string number, float amount, CreditCard& creditCard) : \nnumber(num), amount(amount), creditCard(std::forward<CreditCard&>(creditCard)) \n{ }\ncreditCardcreditCardcreditCardAccount(std::string number, float amount, CreditCard&& creditCard) : \nnumber(num), amount(amount), creditCard(std::forward<CreditCard>(creditCard)) \n{ }\ncreditCard"}, {"idx": "webquery-test-3", "doc": "Is passing a C++ object into its own constructor legal?", "code": "foo #include <stdio.h>\n\n struct A {\n A() { printf(\"A::A() %p\\n\", this); }\n A(const A& a) { printf(\"A::A(const A&) %p %p\\n\", this, &a); }\n ~A() { printf(\"A::~A() %p\\n\", this); }\n };\n\n int main()\n {\n A a=a;\n }\n #include <stdio.h>\n\n struct A {\n A() { printf(\"A::A() %p\\n\", this); }\n A(const A& a) { printf(\"A::A(const A&) %p %p\\n\", this, &a); }\n ~A() { printf(\"A::~A() %p\\n\", this); }\n };\n\n int main()\n {\n A a=a;\n }\n3.8fooint x = x ;\n"}, {"idx": "webquery-test-4", "doc": "Which one will execute faster, if (flag==0) or if (0==flag)?", "code": "flagflagflagflagx86x86x86x86int regular(int c) {\n if (c == 0) { return 0; }\n return 1;\n}\n\nint yoda(int c) {\n if (0 == c) { return 0; }\n return 1;\n}\n\ndefine i32 @regular(i32 %c) nounwind readnone {\nentry:\n %not. = icmp ne i32 %c, 0 ; <i1> [#uses=1]\n %.0 = zext i1 %not. to i32 ; <i32> [#uses=1]\n ret i32 %.0\n}\n\ndefine i32 @yoda(i32 %c) nounwind readnone {\nentry:\n %not. = icmp ne i32 %c, 0 ; <i1> [#uses=1]\n %.0 = zext i1 %not. to i32 ; <i32> [#uses=1]\n ret i32 %.0\n}\n"}, {"idx": "webquery-test-5", "doc": "What's the scope of the \"using\" declaration in C++?", "code": "usingusingvoid myFunction()\n{\n using namespace std; // only applies to the function's scope\n vector<int> myVector;\n}\n"}, {"idx": "webquery-test-6", "doc": "Undefined reference to static variable c++", "code": "staticstaticfoo()foo()foo()class Helloworld {\n public:\n static int x;\n void foo();\n};\n\nint Helloworld::x = 0; // Or whatever is the most appropriate value\n // for initializing x. Notice, that the\n // initializer is not required: if absent,\n // x will be zero-initialized.\n\nvoid Helloworld::foo() {\n Helloworld::x = 10;\n};\n"}, {"idx": "webquery-test-7", "doc": "How to clear ostringstream", "code": "s.str(\"\");\ns.clear();\nclear()std::ostringstream"}, {"idx": "webquery-test-1", "doc": "How to calculate a time difference in C++", "code": "std::clock()const clock_t begin_time = clock();\n// do something\nstd::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;\n<ctime><ctime>"}, {"idx": "webquery-test-2", "doc": "How can a C++ header file include implementation?", "code": "#include#ifndef FooH\n#define FooH\n\nclass Foo\n{\npublic:\n UInt32 GetNumberChannels() const;\n\nprivate:\n UInt32 _numberChannels;\n};\n\n#endif\n#include \"Foo.h\"\n\nUInt32 Foo::GetNumberChannels() const\n{\n return _numberChannels;\n}\n#include \"Foo.h\"\n\nFoo f;\nUInt32 chans = f.GetNumberChannels();\nclass Foo\n{\npublic:\n UInt32 GetNumberChannels() const;\n\nprivate:\n UInt32 _numberChannels;\n};\n\nUInt32 Foo::GetNumberChannels() const\n{\n return _numberChannels;\n}\nclass Foo\n{\npublic:\n UInt32 GetNumberChannels() const;\n\nprivate:\n UInt32 _numberChannels;\n};\n\nFoo f;\nUInt32 chans = f.GetNumberChannels();\nFoo::GetNumberChannels()Foo::GetNumberChannels()inlineinlineconst"}, {"idx": "webquery-test-3", "doc": "The new keyword \"auto\"; When should it be used to declare a variable type?", "code": "auto//good : auto increases readability here\nfor(auto it = v.begin(); it != v.end(); ++it) //v is some [std] container\n{\n //..\n}\n//good : auto increases readability here\nfor(auto it = std::begin(v); it != std::end(v); ++it)//v could be array as well\n{\n //..\n}\nauto//bad : auto decreases readability here\nauto obj = ProcessData(someVariables);\nautoautoautoauto//without auto. Not that good, looks cumbersome\nSomeType<OtherType>::SomeOtherType * obj1 = new SomeType<OtherType>::SomeOtherType();\nstd::shared_ptr<XyzType> obj2 = std::make_shared<XyzType>(args...);\nstd::unique_ptr<XyzType> obj2 = std::make_unique<XyzType>(args...);\n\n//With auto. good : auto increases readability here\nauto obj1 = new SomeType<OtherType>::SomeOtherType();\nauto obj2 = std::make_shared<XyzType>(args...);\nauto obj3 = std::make_unique<XyzType>(args...);\nnewautofoam::composition::expression<int> x;\n\nauto s = x * x; //square\nauto c = x * x * x; //cube\nfor(int i = 0; i < 5 ; i++ )\n std::cout << s(i) << \", \" << c(i) << std::endl; \n0, 0\n1, 1\n4, 8\n9, 27\n16, 64\nautofoam::composition::expression<int> x;\n\n//scroll horizontally to see the complete type!!\nfoam::composition::expression<foam::composition::details::binary_expression<foam::composition::expression<int>, foam::composition::expression<int>, foam::operators::multiply>> s = x * x; //square\nfoam::composition::expression<foam::composition::details::binary_expression<foam::composition::expression<foam::composition::details::binary_expression<foam::composition::expression<int>, foam::composition::expression<int>, foam::operators::multiply> >, foam::composition::expression<int>, foam::operators::multiply>> c = x * x * x; //cube\n\nfor(int i = 0; i < 5 ; i++ )\n std::cout << s(i) << \", \" << c(i) << std::endl; \nautoauto a = x * x - 4 * x + 4; \nauto b = x * (x + 10) / ( x * x+ 12 );\nauto c = (x ^ 4 + x ^ 3 + x ^ 2 + x + 100 ) / ( x ^ 2 + 10 );\nautoautoauto"}, {"idx": "webquery-test-4", "doc": "Abstract Class vs Interface in C++", "code": "class MyInterface\n{\npublic:\n // Empty virtual destructor for proper cleanup\n virtual ~MyInterface() {}\n\n virtual void Method1() = 0;\n virtual void Method2() = 0;\n};\n\n\nclass MyAbstractClass\n{\npublic:\n virtual ~MyAbstractClass();\n\n virtual void Method1();\n virtual void Method2();\n void Method3();\n\n virtual void Method4() = 0; // make MyAbstractClass not instantiable\n};\n// Abstract class for an OpenGL app.\n// Creates rendering window, initializes OpenGL; \n// client code must derive from it \n// and implement rendering and user input.\nclass OpenGLApp\n{\npublic:\n OpenGLApp();\n virtual ~OpenGLApp();\n ...\n\n // Run the app \n void Run();\n\n\n // <---- This behavior must be implemented by the client ---->\n\n // Rendering\n virtual void Render() = 0;\n\n // Handle user input\n // (returns false to quit, true to continue looping)\n virtual bool HandleInput() = 0;\n\n // <--------------------------------------------------------->\n\n\nprivate:\n //\n // Some infrastructure code\n //\n ... \n void CreateRenderingWindow();\n void CreateOpenGLContext();\n void SwapBuffers();\n};\n\n\nclass MyOpenGLDemo : public OpenGLApp\n{\npublic:\n MyOpenGLDemo();\n virtual ~MyOpenGLDemo();\n\n // Rendering\n virtual void Render(); // implements rendering code\n\n // Handle user input\n virtual bool HandleInput(); // implements user input handling\n\n\n // ... some other stuff\n};\n"}, {"idx": "webquery-test-5", "doc": "How to enable C++17 in CMake", "code": "target_compile_featurestarget_compile_features(${TARGET_NAME} PRIVATE cxx_std_17)"}, {"idx": "webquery-test-6", "doc": "How do I add a library path in cmake?", "code": "include_directories(${CMAKE_SOURCE_DIR}/inc)\nlink_directories(${CMAKE_SOURCE_DIR}/lib)\n\nadd_executable(foo ${FOO_SRCS})\ntarget_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib\n-I and -Ladd_library(bar SHARED IMPORTED) # or STATIC instead of SHARED\nset_target_properties(bar PROPERTIES\n IMPORTED_LOCATION \"${CMAKE_SOURCE_DIR}/lib/libbar.so\"\n INTERFACE_INCLUDE_DIRECTORIES \"${CMAKE_SOURCE_DIR}/include/libbar\"\n)\n\nset(FOO_SRCS \"foo.cpp\")\nadd_executable(foo ${FOO_SRCS})\ntarget_link_libraries(foo bar) # also adds the required include path\nINTERFACE_INCLUDE_DIRECTORIESINTERFACE_INCLUDE_DIRECTORIES"}, {"idx": "webquery-test-7", "doc": "Why is rand()%6 biased?", "code": "rand() % 6rand() % 6rand()rand()rand()rand()rand()rand()rand()rand()rand()rand()rand()rand() % 6RAND_MAXRAND_MAXint max = 6 * ((RAND_MAX + 1u) / 6)\nint value = rand();\nwhile (value >= max)\n value = rand();\n"}, {"idx": "webquery-test-8", "doc": "How to specify preference of library path?", "code": "LD_LIBRARY_PATH-L/my/dir -lfoo-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)\nLD_LIBRARY_PATH=/some/custom/dir ./fooo\n/sbin/ldconfig -p | grep libpthread\n libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0\nldd foo\n linux-gate.so.1 => (0xffffe000)\n libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)\n libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)\n librt.so.1 => /lib/librt.so.1 (0xb7e65000)\n libm.so.6 => /lib/libm.so.6 (0xb7d5b000)\n libc.so.6 => /lib/libc.so.6 (0xb7c2e000)\n /lib/ld-linux.so.2 (0xb7fc7000)\n libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)\n libz.so.1 => /lib/libz.so.1 (0xb7c18000)\n"}, {"idx": "webquery-test-9", "doc": "How does guaranteed copy elision work?", "code": "T Func() {return T();}\nTT t = Func();\nttttreturn T();return T();T()T t = Func();T t = Func();T t = Func();T t = Func();T t = Func();T t = Func();T t = Func();const T &rt = Func();const T &rt = Func();const T &rt = Func();lock_guardnew T(FactoryFunction());\nFactoryFunctionFactoryFunctionTnew auto(FactoryFunction());\nT Func()\n{\n T t = ...;\n ...\n return t;\n}\nt"}, {"idx": "webquery-test-10", "doc": "Initial capacity of vector in C++", "code": "capacitycapacity"}, {"idx": "webquery-test-11", "doc": "What is the lifetime of the result of std::string::c_str()?", "code": "c_str()c_str()c_str()c_str()c_str()c_str()"}, {"idx": "webquery-test-1", "doc": "What is __gxx_personality_v0 for?", "code": "-fno-exceptions-fno-exceptions-fno-exceptions-fno-exceptions-fno-exceptions"}, {"idx": "webquery-test-2", "doc": "Why an unnamed namespace is a \"superior\" alternative to static?", "code": "static"}, {"idx": "webquery-test-3", "doc": "Do rvalue references to const have any use?", "code": "template <class T> void ref(const T&&) = delete;\ntemplate <class T> void cref(const T&&) = delete;\nref(T&)ref(T&)template <class T> void ref(const T&&) = delete;\ntemplate <class T> void cref(const T&&) = delete;\ntemplate <class T> void ref(const T&&) = delete;\ntemplate <class T> void cref(const T&&) = delete;\n"}, {"idx": "webquery-test-4", "doc": "Resolving ambiguous overload on function pointer and std::function for a lambda using + (unary plus)", "code": "++++publicpublicpublicpublic++++void foo(void (*f)())[](){}[](){}[](){}[](){}[](){}void (*)()+"}, {"idx": "webquery-test-5", "doc": "std::ignore with structured bindings?", "code": "std::tiestd::tiestd::tiestd::tiestd::tiestd::tiestd::tie"}, {"idx": "webquery-test-6", "doc": "Malloc vs new -- different padding", "code": "mallocmallocmallocmallocmallocmalloc(sizeof(Foo) * n)malloc(sizeof(Foo) * n)malloc((sizeof(int) + sizeof(char)) * n);\nstruct Foo { int a; char b; }\nnew Foo[n];\nmalloc"}, {"idx": "webquery-test-7", "doc": "Does unique_ptr::release() call the destructor?", "code": "releaseauto v = make_unique<int>(12); // manages the object\nint * raw = v.release(); // pointer to no-longer-managed object\ndelete raw; // needs manual deletion\nresetauto v = make_unique<int>(12); // manages the object\nv.reset(); // delete the object, leaving v empty\n"}, {"idx": "webquery-test-8", "doc": "How to get position of a certain element in strings vector, to use it as an index in ints vector?", "code": "v.begin()ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();\nposposif(pos >= Names.size()) {\n //old_name_ not found\n}\nstd::distanceptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));\n"}, {"idx": "webquery-test-9", "doc": "Why does std::set not have a \"contains\" member function?", "code": "std::setstd::setstd::setstd::setcountcountif (myset.count(element)) \n ...\n"}, {"idx": "webquery-test-10", "doc": "Why would we call cin.clear() and cin.ignore() after reading input?", "code": "cin.clear()cin.clear()cin.clear()"}, {"idx": "webquery-test-11", "doc": "The tilde operator in C", "code": "~NOT 011100\n = 100011\n"}, {"idx": "webquery-test-12", "doc": "how to append a list<T> object to another", "code": "a.insert(a.end(), b.begin(), b.end());\na.splice(a.end(), b);\n"}, {"idx": "webquery-test-13", "doc": "should use size_t or ssize_t", "code": "ssize_tssize_tssize_tsize_tsize_t"}, {"idx": "webquery-test-1", "doc": "How to set std::tuple element by index?", "code": "std::getstd::get<0>(myTuple) = newValue;\nmyTuplemyTupleauto movedTo = std::get<0>(std::move(myTuple));\n"}, {"idx": "webquery-test-2", "doc": "Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined", "code": "#include <sstream>\n\n//...\nQString Stats_Manager::convertInt(int num)\n{\n std::stringstream ss; // <-- also note namespace qualification\n ss << num;\n return ss.str();\n}\n"}, {"idx": "webquery-test-3", "doc": "How can I initialize C++ object member variables in the constructor?", "code": "BigMommaClass {\n BigMommaClass(int, int);\n\nprivate:\n ThingOne thingOne;\n ThingTwo thingTwo;\n};\n\nBigMommaClass::BigMommaClass(int numba1, int numba2)\n : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}\n"}, {"idx": "webquery-test-4", "doc": "Order of evaluation in C++ function parameters", "code": "int x = f(2) + g(3); // unspecified whether f() or g() is called first\n"}, {"idx": "webquery-test-5", "doc": "Why is 'pure polymorphism' preferable over using RTTI?", "code": "am_I_orangeclass node_base {\n public:\n bool has_tag(tag_name);\n"}, {"idx": "webquery-test-6", "doc": "Difference between std::system_clock and std::steady_clock?", "code": "system_clocksteady_clocksteady_clocksteady_clockhigh_resolution_clockhigh_resolution_clockhigh_resolution_clockhigh_resolution_clocksteady_clockC1C1C1C1C1C1C1C1C1C1C1C1C1C1C1C1std::high_resolution_clockstd::high_resolution_clock"}, {"idx": "webquery-test-7", "doc": "How to construct a c++ fstream from a POSIX file descriptor?", "code": "__gnu_cxx::stdio_filebuf__gnu_cxx::stdio_filebufstdio_filebuf (int __fd, std::ios_base::openmode __mode, size_t __size=static_cast< size_t >(BUFSIZ)) \n#include <ext/stdio_filebuf.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n ofstream ofs(\"test.txt\");\n ofs << \"Writing to a basic_ofstream object...\" << endl;\n ofs.close();\n\n int posix_handle = fileno(::fopen(\"test.txt\", \"r\"));\n\n __gnu_cxx::stdio_filebuf<char> filebuf(posix_handle, std::ios::in); // 1\n istream is(&filebuf); // 2\n\n string line;\n getline(is, line);\n cout << \"line: \" << line << std::endl;\n return 0;\n}\nexplicit basic_ifstream(_Filet *_File)\n : _Mybase(&_Filebuffer),\n _Filebuffer(_File)\n { // construct with specified C stream\n }\n#include <cstdio>\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n ofstream ofs(\"test.txt\");\n ofs << \"Writing to a basic_ofstream object...\" << endl;\n ofs.close();\n\n int posix_handle = ::_fileno(::fopen(\"test.txt\", \"r\"));\n\n ifstream ifs(::_fdopen(posix_handle, \"r\")); // 1\n\n string line;\n getline(ifs, line);\n ifs.close();\n cout << \"line: \" << line << endl;\n return 0;\n}\n"}, {"idx": "webquery-test-8", "doc": "When to use std::begin and std::end instead of container specific versions", "code": "c.begin()"}, {"idx": "webquery-test-9", "doc": "Difference between std::result_of and decltype", "code": "result_ofresult_ofdecltyperesult_ofresult_of template<typename _Signature>\n class result_of;\n\n template<typename _Functor, typename... _ArgTypes>\n struct result_of<_Functor(_ArgTypes...)>\n {\n typedef\n decltype( std::declval<_Functor>()(std::declval<_ArgTypes>()...) )\n type;\n };\n"}, {"idx": "webquery-test-1", "doc": "C++ function template partial specialization?", "code": "max<T1,T2>// Partial specialization is not allowed by the spec, though!\ntemplate <typename T> \ninline T const& max<T,T> (T const& a, T const& b)\n{ ^^^^^ <--- [supposed] specializing here\n return 10;\n}\n"}, {"idx": "webquery-test-2", "doc": "Where is shared_ptr?", "code": "shared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptr"}, {"idx": "webquery-test-3", "doc": "How to write std::string to file?", "code": "stringofstreamofstreamoutput.txt#include <fstream>\n#include <string>\n#include <iostream>\n\nint main()\n{\n std::string input;\n std::cin >> input;\n std::ofstream out(\"output.txt\");\n out << input;\n out.close();\n return 0;\n}\nout.close()out.close()out.close()string::c_str()write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );\n"}, {"idx": "webquery-test-4", "doc": "(How) can I count the items in an enum?", "code": "enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};\nint fuz[FOOBAR_NR_ITEMS];\nenum foobar {foo, bar = 5, baz, quz = 20};\n"}, {"idx": "webquery-test-5", "doc": "C++ #include and #import difference", "code": "#import#import#import#pragma#import#include#include"}, {"idx": "webquery-test-6", "doc": "The written versions of the logical operators", "code": "<iso646.h><iso646.h><iso646.h><iso646.h><iso646.h><ciso646><ciso646><ciso646>&&&&"}, {"idx": "webquery-test-7", "doc": "How do I find where an exception was thrown in C++?", "code": "std::terminate()std::terminate()std::terminate()abort()abort()terminate()terminate()terminate()terminate()terminate()terminate()terminate()terminate()terminate()terminate()terminate()throw#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#ifndef __USE_GNU\n#define __USE_GNU\n#endif\n\n#include <execinfo.h>\n#include <signal.h>\n#include <string.h>\n\n#include <iostream>\n#include <cstdlib>\n#include <stdexcept>\n\nvoid my_terminate(void);\n\nnamespace {\n // invoke set_terminate as part of global constant initialization\n static const bool SET_TERMINATE = std::set_terminate(my_terminate);\n}\n\n// This structure mirrors the one found in /usr/include/asm/ucontext.h\ntypedef struct _sig_ucontext {\n unsigned long uc_flags;\n struct ucontext *uc_link;\n stack_t uc_stack;\n struct sigcontext uc_mcontext;\n sigset_t uc_sigmask;\n} sig_ucontext_t;\n\nvoid crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext) {\n sig_ucontext_t * uc = (sig_ucontext_t *)ucontext;\n\n // Get the address at the time the signal was raised from the EIP (x86)\n void * caller_address = (void *) uc->uc_mcontext.eip;\n \n std::cerr << \"signal \" << sig_num \n << \" (\" << strsignal(sig_num) << \"), address is \" \n << info->si_addr << \" from \" \n << caller_address << std::endl;\n\n void * array[50];\n int size = backtrace(array, 50);\n\n std::cerr << __FUNCTION__ << \" backtrace returned \" \n << size << \" frames\\n\\n\";\n\n // overwrite sigaction with caller's address\n array[1] = caller_address;\n\n char ** messages = backtrace_symbols(array, size);\n\n // skip first stack frame (points here)\n for (int i = 1; i < size && messages != NULL; ++i) {\n std::cerr << \"[bt]: (\" << i << \") \" << messages[i] << std::endl;\n }\n std::cerr << std::endl;\n\n free(messages);\n\n exit(EXIT_FAILURE);\n}\n\nvoid my_terminate() {\n static bool tried_throw = false;\n\n try {\n // try once to re-throw currently active exception\n if (!tried_throw++) throw;\n }\n catch (const std::exception &e) {\n std::cerr << __FUNCTION__ << \" caught unhandled exception. what(): \"\n << e.what() << std::endl;\n }\n catch (...) {\n std::cerr << __FUNCTION__ << \" caught unknown/unhandled exception.\" \n << std::endl;\n }\n\n void * array[50];\n int size = backtrace(array, 50); \n\n std::cerr << __FUNCTION__ << \" backtrace returned \" \n << size << \" frames\\n\\n\";\n\n char ** messages = backtrace_symbols(array, size);\n\n for (int i = 0; i < size && messages != NULL; ++i) {\n std::cerr << \"[bt]: (\" << i << \") \" << messages[i] << std::endl;\n }\n std::cerr << std::endl;\n\n free(messages);\n\n abort();\n}\n\nint throw_exception() {\n // throw an unhandled runtime error\n throw std::runtime_error(\"RUNTIME ERROR!\");\n return 0;\n}\n\nint foo2() {\n throw_exception();\n return 0;\n}\n\nint foo1() {\n foo2();\n return 0;\n}\n\nint main(int argc, char ** argv) {\n struct sigaction sigact;\n\n sigact.sa_sigaction = crit_err_hdlr;\n sigact.sa_flags = SA_RESTART | SA_SIGINFO;\n\n if (sigaction(SIGABRT, &sigact, (struct sigaction *)NULL) != 0) {\n std::cerr << \"error setting handler for signal \" << SIGABRT \n << \" (\" << strsignal(SIGABRT) << \")\\n\";\n exit(EXIT_FAILURE);\n }\n\n foo1();\n\n exit(EXIT_SUCCESS);\n}\n"}, {"idx": "webquery-test-8", "doc": "Does C++20 mandate source code being stored in files?", "code": "generate_source | g++ -o- -xc++ - | do_something_with_the_binary\nstd::source_locationstd::source_locationstd::source_locationstd::source_location__FILE__echo -e '#include <iostream>\\n int main(){std::cout << __FILE__ ;}' | g++ -xc++ -\n<stdin>#include <https://raw.githubusercontent.com/Morwenn/poplar-heap/master/poplar.h>\n\n// Type your code here, or load an example.\nvoid poplar_sort(int* data, size_t size) {\n poplar::make_heap(data, data + size);\n poplar::sort_heap(data, data + size);\n}\nstd::source_location"}, {"idx": "webquery-test-9", "doc": "How to check if a std::thread is still running?", "code": "std::asyncstd::asyncstd::asyncstd::async#include <future>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\nint main() {\n using namespace std::chrono_literals;\n\n /* Run some task on new thread. The launch policy std::launch::async\n makes sure that the task is run asynchronously on a new thread. */\n auto future = std::async(std::launch::async, [] {\n std::this_thread::sleep_for(3s);\n return 8;\n });\n\n // Use wait_for() with zero milliseconds to check thread status.\n auto status = future.wait_for(0ms);\n\n // Print status.\n if (status == std::future_status::ready) {\n std::cout << \"Thread finished\" << std::endl;\n } else {\n std::cout << \"Thread still running\" << std::endl;\n }\n\n auto result = future.get(); // Get result.\n}\nstd::threadstd::thread#include <future>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\nint main() {\n using namespace std::chrono_literals;\n\n // Create a promise and get its future.\n std::promise<bool> p;\n auto future = p.get_future();\n\n // Run some task on a new thread.\n std::thread t([&p] {\n std::this_thread::sleep_for(3s);\n p.set_value(true); // Is done atomically.\n });\n\n // Get thread status using wait_for as before.\n auto status = future.wait_for(0ms);\n\n // Print status.\n if (status == std::future_status::ready) {\n std::cout << \"Thread finished\" << std::endl;\n } else {\n std::cout << \"Thread still running\" << std::endl;\n }\n\n t.join(); // Join thread.\n}\nThread still running\n#include <thread>\n#include <atomic>\n#include <chrono>\n#include <iostream>\n\nint main() {\n using namespace std::chrono_literals;\n\n std::atomic<bool> done(false); // Use an atomic flag.\n\n /* Run some task on a new thread.\n Make sure to set the done flag to true when finished. */\n std::thread t([&done] {\n std::this_thread::sleep_for(3s);\n done = true;\n });\n\n // Print status.\n if (done) {\n std::cout << \"Thread finished\" << std::endl;\n } else {\n std::cout << \"Thread still running\" << std::endl;\n }\n\n t.join(); // Join thread.\n}\nstd::packaged_taskstd::packaged_taskstd::packaged_task#include <future>\n#include <thread>\n#include <chrono>\n#include <iostream>\n\nint main() {\n using namespace std::chrono_literals;\n\n // Create a packaged_task using some task and get its future.\n std::packaged_task<void()> task([] {\n std::this_thread::sleep_for(3s);\n });\n auto future = task.get_future();\n\n // Run task on new thread.\n std::thread t(std::move(task));\n\n // Get thread status using wait_for as before.\n auto status = future.wait_for(0ms);\n\n // Print status.\n if (status == std::future_status::ready) {\n // ...\n }\n\n t.join(); // Join thread.\n}\n"}, {"idx": "webquery-test-10", "doc": "What are template deduction guides and when should we use them?", "code": "std::vectortemplate<typename Iterator>\nvoid func(Iterator first, Iterator last)\n{\n vector v(first, last);\n}\nvector<T>vector<T>vector<T>vector<T>vector<T>template<typename Iterator> vector(Iterator b, Iterator e) -> \n vector<typename std::iterator_traits<Iterator>::value_type>;\nvectorvectorvectorvectorvectorvectorvectortemplate<typename T>\nstruct Thingy\n{\n T t;\n};\n\nThingy(const char *) -> Thingy<std::string>;\n\nThingy thing{\"A String\"}; //thing.t is a `std::string`.\n"}, {"idx": "webquery-test-11", "doc": "When to use the brace-enclosed initializer?", "code": "==="}, {"idx": "webquery-test-1", "doc": "What does it mean to \"ODR-use\" something?", "code": "std::list<>::sortstd::list<>::sortstd::list<>::sortstd::list<>::sort"}, {"idx": "webquery-test-2", "doc": "C++11 lambda implementation and memory model", "code": "auto lamb = []() {return 5;};\nlamblambstd::functionauto func_lamb = std::function<int()>(lamb);\nlamblamblamblambfunc_lambfunc_lambauto func_lamb_ptr = new std::function<int()>(lamb);\nstd::functionstd::functionstd::functionstd::functionstd::functionstd::function"}, {"idx": "webquery-test-3", "doc": "Unicode Processing in C++", "code": "is_alphais_alpha"}, {"idx": "webquery-test-4", "doc": "Compiling a C++ program with GCC", "code": "gccgcc info.C -lstdc++\ng++"}, {"idx": "webquery-test-5", "doc": "Call a C function from C++ code", "code": "gcc -c -o somecode.o somecode.c\ng++ -c -o othercode.o othercode.cpp\ng++ -o yourprogram somecode.o othercode.o\nothercode.cppextern \"C\" {\n#include \"somecode.h\"\n}\nsomecode.h #ifndef SOMECODE_H_\n #define SOMECODE_H_\n\n void foo();\n\n #endif\n"}, {"idx": "webquery-test-6", "doc": "What does extern inline do?", "code": "inlineinlineinlineinlineinlineinlineinlineinlineinlinestatic inlinestatic inline"}, {"idx": "webquery-test-7", "doc": "Confusing Template error", "code": "t->f0<U>();t->f0<U>();t->f0<U>();t->f0<U>();t->f0<U>();t->f0<U>()t->f0<U>()"}, {"idx": "webquery-test-8", "doc": "Linking libstdc++ statically: any gotchas?", "code": "libstdc++.solibstdc++.adlopendlopendlopendlopenlibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.solibstdc++.so"}, {"idx": "webquery-test-9", "doc": "What are the evaluation order guarantees introduced by C++17?", "code": "C++17i = 1;\nf(i++, i)\nffff(1, 1)f(1, 1)f(1, 1)std::cout << f() << f() << f();\nff(g(), h(), j());\ngetf()(g(),h(),j())getf()(g(),h(),j())getf()(g(),h(),j()) std::string s = \"but I have heard it works even if you don't believe in it\"\n s.replace(0, 4, \"\").replace(s.find(\"even\"), 4, \"only\")\n .replace(s.find(\" don't\"), 6, \"\");\n.then( . . . )#include <iostream>\n#include <string>\n#include <vector>\n#include <cassert>\n\nstruct Speaker{\n int i =0;\n Speaker(std::vector<std::string> words) :words(words) {}\n std::vector<std::string> words;\n std::string operator()(){\n assert(words.size()>0);\n if(i==words.size()) i=0;\n // Pre-C++17 version:\n auto word = words[i] + (i+1==words.size()?\"\\n\":\",\");\n ++i;\n return word;\n // Still not possible with C++17:\n // return words[i++] + (i==words.size()?\"\\n\":\",\");\n\n }\n};\n\nint main() {\n auto spk = Speaker{{\"All\", \"Work\", \"and\", \"no\", \"play\"}};\n std::cout << spk() << spk() << spk() << spk() << spk() ;\n}\nplay\nno,and,Work,All,\nAll,work,and,no,play\n(((((std::cout << spk()) << spk()) << spk()) << spk()) << spk()) ;\na(b1, b2, b3)a(b1, b2, b3)a(b1, b2, b3)a(b1, b2, b3)b1b1b1f(std::unique_ptr<A> a, std::unique_ptr<B> b);\n\nf(get_raw_a(), get_raw_a());\nget_raw_a()int x=0;\nx++ + ++x;\n"}, {"idx": "webquery-test-1", "doc": "How to build a full path string (safely) from separate strings?", "code": "#include <iostream>\n#include <boost/filesystem.hpp>\n\nnamespace fs = boost::filesystem;\n\nint main ()\n{\n fs::path dir (\"/tmp\");\n fs::path file (\"foo.txt\");\n fs::path full_path = dir / file;\n std::cout << full_path << std::endl;\n return 0;\n}\n$ g++ ./test.cpp -o test -lboost_filesystem -lboost_system\n$ ./test \n/tmp/foo.txt\n"}, {"idx": "webquery-test-2", "doc": "How can I create my own comparator for a map?", "code": "std::mapstruct cmpByStringLength {\n bool operator()(const std::string& a, const std::string& b) const {\n return a.length() < b.length();\n }\n};\n\n// ...\nstd::map<std::string, std::string, cmpByStringLength> myMap;\nmap"}, {"idx": "webquery-test-3", "doc": "How to get integer thread id in c++11", "code": "std::hash<std::thread::id>{}(std::this_thread::get_id())\nsize_tstd::hashstd::hash"}, {"idx": "webquery-test-4", "doc": "Is gcc 4.8 or earlier buggy about regular expressions?", "code": "<regex><regex><regex><regex><regex>"}, {"idx": "webquery-test-5", "doc": "Magic number in boost::hash_combine", "code": "phi = (1 + sqrt(5)) / 2\n2^32 / phi = 0x9e3779b9\nhash_value()"}, {"idx": "webquery-test-6", "doc": "Why can't we declare a std::vector<AbstractClass>?", "code": "std::vector<IFunnyInterface*> ifVec;\n"}, {"idx": "webquery-test-7", "doc": "How can I use cout << myclass", "code": "operator<<struct myclass { \n int i;\n};\n\nstd::ostream &operator<<(std::ostream &os, myclass const &m) { \n return os << m.i;\n}\n\nint main() { \n myclass x(10);\n\n std::cout << x;\n return 0;\n}\n"}, {"idx": "webquery-test-8", "doc": "Can const-correctness improve performance?", "code": "constconstconstconstconstconstconstconst"}, {"idx": "webquery-test-9", "doc": "Why does C++ disallow anonymous structs?", "code": ".v[i].v[i].v[i].v[i].v[i].v[i]struct vector3 {\n float v[3];\n float &operator[] (int i) { return v[i]; }\n float &x() { return v[0]; }\n float &y() { return v[1]; }\n float &z() { return v[2]; }\n};\n"}, {"idx": "webquery-test-1", "doc": "What does [=] mean in C++?", "code": "[=][=][=][=][=][=][=]"}, {"idx": "webquery-test-2", "doc": "How can I sort two vectors in the same way, with criteria that uses only one of the vectors?", "code": "std::vector<T>std::vector<T>template <typename T, typename Compare>\nstd::vector<std::size_t> sort_permutation(\n const std::vector<T>& vec,\n Compare& compare)\n{\n std::vector<std::size_t> p(vec.size());\n std::iota(p.begin(), p.end(), 0);\n std::sort(p.begin(), p.end(),\n [&](std::size_t i, std::size_t j){ return compare(vec[i], vec[j]); });\n return p;\n}\nstd::vector<T>std::vector<T>template <typename T>\nstd::vector<T> apply_permutation(\n const std::vector<T>& vec,\n const std::vector<std::size_t>& p)\n{\n std::vector<T> sorted_vec(vec.size());\n std::transform(p.begin(), p.end(), sorted_vec.begin(),\n [&](std::size_t i){ return vec[i]; });\n return sorted_vec;\n}\napply_permutationapply_permutationtemplate <typename T>\nvoid apply_permutation_in_place(\n std::vector<T>& vec,\n const std::vector<std::size_t>& p)\n{\n std::vector<bool> done(vec.size());\n for (std::size_t i = 0; i < vec.size(); ++i)\n {\n if (done[i])\n {\n continue;\n }\n done[i] = true;\n std::size_t prev_j = i;\n std::size_t j = p[i];\n while (i != j)\n {\n std::swap(vec[prev_j], vec[j]);\n done[j] = true;\n prev_j = j;\n j = p[j];\n }\n }\n}\nvector<MyObject> vectorA;\nvector<int> vectorB;\n\nauto p = sort_permutation(vectorA,\n [](T const& a, T const& b){ /*some comparison*/ });\n\nvectorA = apply_permutation(vectorA, p);\nvectorB = apply_permutation(vectorB, p);\nstd::vectorstd::vectorstd::vectorstd::vectorstd::vector"}, {"idx": "webquery-test-3", "doc": "C++: Namespaces -- How to use in header and source files correctly?", "code": "usingusing"}, {"idx": "webquery-test-4", "doc": "How should I deal with mutexes in movable types in C++?", "code": "class A\n{\n using MutexType = std::mutex;\n using ReadLock = std::unique_lock<MutexType>;\n using WriteLock = std::unique_lock<MutexType>;\n\n mutable MutexType mut_;\n\n std::string field1_;\n std::string field2_;\n\npublic:\n ...\nmutexmutexmutexAAA A(A&& a)\n {\n WriteLock rhs_lk(a.mut_);\n field1_ = std::move(a.field1_);\n field2_ = std::move(a.field2_);\n }\nthisthis// Thread 1\nx = std::move(y);\n\n// Thread 2\ny = std::move(x);\n A& operator=(A&& a)\n {\n if (this != &a)\n {\n WriteLock lhs_lk(mut_, std::defer_lock);\n WriteLock rhs_lk(a.mut_, std::defer_lock);\n std::lock(lhs_lk, rhs_lk);\n field1_ = std::move(a.field1_);\n field2_ = std::move(a.field2_);\n }\n return *this;\n }\nstd::lock(m1, m2)std::lock(m1, m2) A(const A& a)\n {\n ReadLock rhs_lk(a.mut_);\n field1_ = a.field1_;\n field2_ = a.field2_;\n }\nReadLockReadLockReadLock using MutexType = std::shared_timed_mutex;\n using ReadLock = std::shared_lock<MutexType>;\n using WriteLock = std::unique_lock<MutexType>;\n A& operator=(const A& a)\n {\n if (this != &a)\n {\n WriteLock lhs_lk(mut_, std::defer_lock);\n ReadLock rhs_lk(a.mut_, std::defer_lock);\n std::lock(lhs_lk, rhs_lk);\n field1_ = a.field1_;\n field2_ = a.field2_;\n }\n return *this;\n }\nAA friend void swap(A& x, A& y)\n {\n if (&x != &y)\n {\n WriteLock lhs_lk(x.mut_, std::defer_lock);\n WriteLock rhs_lk(y.mut_, std::defer_lock);\n std::lock(lhs_lk, rhs_lk);\n using std::swap;\n swap(x.field1_, y.field1_);\n swap(x.field2_, y.field2_);\n }\n }\nstd::swapstd::swapswapswapstd::recursive_mutexstd::recursive_mutexmutable MutexType mut_;\nReadLock read_lock_;\nWriteLock write_lock_;\n// ... other data members ...\nmutable MutexType mut_;\nReadLock read_lock_;\nWriteLock write_lock_;\n// ... other data members ...\n A(const A& a)\n : A(a, ReadLock(a.mut_))\n {}\nprivate:\n A(const A& a, ReadLock rhs_lk)\n : field1_(a.field1_)\n , field2_(a.field2_)\n {}\n"}, {"idx": "webquery-test-5", "doc": "Why does everybody typedef over standard C types?", "code": "stdint.hstdint.h"}, {"idx": "webquery-test-6", "doc": "What is the difference between chrono::month and chrono::months", "code": "monthmonthmonthschrono::durationnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsnanosecondsmonthsmonthsyearsstatic_assert(12*months{1} == years{1});\ncout << months{7} << '\\n';\n7[2629746]s\nstatic_assert(months{1} == 2'629'746s);\nmonthmonthmonthstatic_assert(month{7} == July);\nauto independence_day = month{7}/4d/2020y;\nmonthmonthauto x = month{7} + month{7};\n ~~~~~~~~ ^ ~~~~~~~~\nerror: invalid operands to binary expression ('std::chrono::month' and 'std::chrono::month')\nauto constexpr x = month{7} + months{7};\nstatic_assert(x == February);\nauto constexpr x = months{7} + months{7};\nstatic_assert(x == months{14});\nauto b = February == months{14};\n ~~~~~~~~ ^ ~~~~~~~~~~\nerror: invalid operands to binary expression ('const std::chrono::month' and 'std::chrono::months')\nmonthmonthdaydaydaydaychrono::duration<chrono>"}, {"idx": "webquery-test-7", "doc": "Get the status of a std::future", "code": "wait_untiltemplate<typename R>\n bool is_ready(std::future<R> const& f)\n { return f.wait_for(std::chrono::seconds(0)) == std::future_status::ready; }\nwait_for"}, {"idx": "webquery-test-8", "doc": "How do you serialize an object in C++?", "code": "#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/binary_iarchive.hpp>\nclass gps_position\n{\nprivate:\n friend class boost::serialization::access;\n template<class Archive>\n void serialize(Archive & ar, const unsigned int version)\n {\n ar & degrees;\n ar & minutes;\n ar & seconds;\n }\n int degrees;\n int minutes;\n float seconds;\n\npublic:\n gps_position(){};\n gps_position(int d, int m, float s) :\n degrees(d), minutes(m), seconds(s)\n {}\n};\n#include <fstream>\nstd::ofstream ofs(\"filename.dat\", std::ios::binary);\n\n // create class instance\n const gps_position g(35, 59, 24.567f);\n\n // save data to archive\n {\n boost::archive::binary_oarchive oa(ofs);\n // write class instance to archive\n oa << g;\n // archive and stream closed when destructors are called\n }\n"}, {"idx": "webquery-test-9", "doc": "What\u2019s the best way to check if a file exists in C++? (cross platform)", "code": "#include <boost/filesystem.hpp>\n\nif ( !boost::filesystem::exists( \"myfile.txt\" ) )\n{\n std::cout << \"Can't find my file!\" << std::endl;\n}\n"}, {"idx": "webquery-test-1", "doc": "How to get a certain element in a list, given the position?", "code": "std::liststd::liststd::liststd::advancestd::list<Object> l;\n// add elements to list 'l'...\n\nunsigned N = /* index of the element you want to retrieve */;\nif (l.size() > N)\n{\n std::list<Object>::iterator it = l.begin();\n std::advance(it, N);\n // 'it' points to the element at index 'N'\n}\nstd::liststd::liststd::liststd::liststd::listif (l.size() > N)\n{\n std::list<Object>::iterator it = std::next(l.begin(), N);\n}\nstd::nextstd::nextstd::nextstd::next"}, {"idx": "webquery-test-2", "doc": "How to set breakpoints on future shared libraries with a command flag", "code": "cmds.gdbset breakpoint pending on\nbreak <source file name>:<line number>\n"}, {"idx": "webquery-test-3", "doc": "How to catch segmentation fault in Linux?", "code": "SIGSEGVtry\n{\n *(int*) 0 = 0;\n}\ncatch (std::exception& e)\n{\n std::cerr << \"Exception caught : \" << e.what() << std::endl;\n}\n"}, {"idx": "webquery-test-4", "doc": "Error: free(): invalid next size (fast):", "code": "freefreefreefreefreefree"}, {"idx": "webquery-test-5", "doc": "How to efficiently get a `string_view` for a substring of `std::string`", "code": "std::string#include <string>\n#include <string_view>\n\nstd::string_view sub_string(\n std::string_view s, \n std::size_t p, \n std::size_t n = std::string_view::npos)\n{\n return s.substr(p, n);\n}\n\nint main()\n{\n using namespace std::literals;\n\n auto source = \"foobar\"s;\n\n // this is fine and elegant...\n auto bar = sub_string(source, 3);\n\n // but uh-oh...\n bar = sub_string(\"foobar\"s, 3);\n}\nstd::string#include <string>\n#include <string_view>\n\nstd::string_view sub_string(std::string_view s, \n std::size_t p, \n std::size_t n = std::string_view::npos)\n{\n return s.substr(p, n);\n}\n\nstd::string sub_string(std::string&& s, \n std::size_t p, \n std::size_t n = std::string::npos)\n{\n return s.substr(p, n);\n}\n\nstd::string sub_string(std::string const& s, \n std::size_t p, \n std::size_t n = std::string::npos)\n{\n return s.substr(p, n);\n}\n\nint main()\n{\n using namespace std::literals;\n\n auto source = \"foobar\"s;\n auto bar = sub_string(std::string_view(source), 3);\n\n // but uh-oh...\n bar = sub_string(\"foobar\"s, 3);\n}\nstd::stringstd::stringstd::string_viewstd::string_viewauto s = get_something().get_suffix();\nget_suffix()get_suffix()std::string_viewautoautoauto"}, {"idx": "webquery-test-6", "doc": "Why is there no transform_if in the C++ standard library?", "code": "v | filtered(arg1 % 2) | transformed(arg1 * arg1 / 7.0)\ntransform_iftransform_if v | transformed(arg1 * arg1 / 7.0) | filtered(arg1 < 2.0)\nstd::filter_and_transformstd::filter_and_transformstd::filter_and_transform#include <boost/range/algorithm.hpp>\n#include <boost/range/adaptors.hpp>\n\nusing namespace boost::adaptors;\n\n// only for succinct predicates without lambdas\n#include <boost/phoenix.hpp>\nusing namespace boost::phoenix::arg_names;\n\n// for demo\n#include <iostream>\n\nint main()\n{\n std::vector<int> const v { 1,2,3,4,5 };\n\n boost::copy(\n v | filtered(arg1 % 2) | transformed(arg1 * arg1 / 7.0),\n std::ostream_iterator<double>(std::cout, \"\\n\"));\n}\n"}, {"idx": "webquery-test-1", "doc": "Memory management in Qt?", "code": "QObjectQObjectQObject* parent = new QObject();\nQObject* child = new QObject(parent);\ndeletedeletedeletedeletedeleteMyClassMyClassQObjectQObjectQWidget(QWidget* parent=0)QWidget(QWidget* parent=0)QWidget(QWidget* parent=0)"}, {"idx": "webquery-test-2", "doc": "What are the rules for the \"...\" token in the context of variadic templates?", "code": "......thing // pack : appears as template arguments\nthing... // unpack : appears when consuming the arguments\n......template<typename ...T> //pack\nvoid f(T ... args) //pack\n{\n // here are unpack patterns\n\n g( args... ); //pattern = args\n h( x(args)... ); //pattern = x(args)\n m( y(args...) ); //pattern = args (as argument to y())\n n( z<T>(args)... ); //pattern = z<T>(args)\n}\nTTg( arg0, arg1, arg2 ); \nh( x(arg0), x(arg1), x(arg2) );\nm( y(arg0, arg1, arg2) );\nn( z<int>(arg0), z<char>(arg1), z<short>(arg2) );\nstd::forwardstd::forwardx(args)...x(args)......struct data_info\n{\n boost::any data;\n std::size_t type_size;\n};\n\nstd::vector<data_info> v{{args, sizeof(T)}...}; //pattern = {args, sizeof(T)}\nstd::vector<data_info> v \n{ \n {arg0, sizeof(int)},\n {arg1, sizeof(char)},\n {arg2, sizeof(short)}\n};\npublictemplate<typename ... Mixins>\nstruct mixture : public Mixins ... //pattern = public Mixins\n{\n //code\n};\nstruct mixture__instantiated : public Mixin0, public Mixin1, .. public MixinN \nmixture"}, {"idx": "webquery-test-3", "doc": "How to view symbols in object files?", "code": "nmnmnmnmnmnm"}, {"idx": "webquery-test-4", "doc": "Are C++11 thread_local variables automatically static?", "code": "void f() {\n thread_local vector<int> V;\n V.clear();\n ... // use V as a temporary variable\n}\nvoid f() {\n static thread_local vector<int> V;\n V.clear();\n ... // use V as a temporary variable\n}\n"}, {"idx": "webquery-test-5", "doc": "Why sizeof int is wrong, while sizeof(int) is right?", "code": "sizeof int * + 1\n(sizeof (int*)) + 1(sizeof (int*)) + 1*sizeof (int *) + 1sizeof (int *) + 1sizeof (int *) + 1int(0)int(0)int(0)int(0)"}, {"idx": "webquery-test-6", "doc": "Understanding std::atomic::compare_exchange_weak() in C++11", "code": "compare_exchange_weakcompare_exchange_weakcompare_exchange_strongweakweakweakweakweakweakweakweakweakweakweakstrongstrong!expectedfalsetruetruefalsestrongstrongstrongstd::atomicstd::atomicweakweak"}, {"idx": "webquery-test-7", "doc": "Do I have to acquire lock before calling condition_variable.notify_one()?", "code": "condition_variable::notify_one()notify_one()notify_one()notify_one()lock()lock()lock()lock()notify_one()notify_one()notify_one()notify_one()notify_one()iiiiiiiiiiiwhile (!pred())\n wait(lock);\n \niiiiiiiiiiiiiidonedonedonedonedoneif (--f->counter == 0) // (1)\n // we have zeroed this fence's counter, wake up everyone that waits\n f->resume.notify_all(); // (2)\nelse\n{\n unique_lock<mutex> lock(f->resume_mutex);\n f->resume.wait(lock); // (3)\n}\nwait()wait()wait()wait()wait()wait()wait()wait()wait()"}, {"idx": "webquery-test-8", "doc": "How to read a value from the Windows registry", "code": "HKEY hKey;\nLONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L\"SOFTWARE\\\\Perl\", 0, KEY_READ, &hKey);\nbool bExistsAndSuccess (lRes == ERROR_SUCCESS);\nbool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);\nstd::wstring strValueOfBinDir;\nstd::wstring strKeyDefaultValue;\nGetStringRegKey(hKey, L\"BinDir\", strValueOfBinDir, L\"bad\");\nGetStringRegKey(hKey, L\"\", strKeyDefaultValue, L\"bad\");\n\nLONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)\n{\n nValue = nDefaultValue;\n DWORD dwBufferSize(sizeof(DWORD));\n DWORD nResult(0);\n LONG nError = ::RegQueryValueExW(hKey,\n strValueName.c_str(),\n 0,\n NULL,\n reinterpret_cast<LPBYTE>(&nResult),\n &dwBufferSize);\n if (ERROR_SUCCESS == nError)\n {\n nValue = nResult;\n }\n return nError;\n}\n\n\nLONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)\n{\n DWORD nDefValue((bDefaultValue) ? 1 : 0);\n DWORD nResult(nDefValue);\n LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);\n if (ERROR_SUCCESS == nError)\n {\n bValue = (nResult != 0) ? true : false;\n }\n return nError;\n}\n\n\nLONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)\n{\n strValue = strDefaultValue;\n WCHAR szBuffer[512];\n DWORD dwBufferSize = sizeof(szBuffer);\n ULONG nError;\n nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);\n if (ERROR_SUCCESS == nError)\n {\n strValue = szBuffer;\n }\n return nError;\n}\n"}, {"idx": "webquery-test-9", "doc": "Is gcc std::unordered_map implementation slow? If so - why?", "code": "inserts: 37728\nget : 2985\ninserts: 2531\nget : 1565\nstd::unordered_mapstd::unordered_map"}, {"idx": "webquery-test-10", "doc": "Why isn't std::initializer_list a language built-in?", "code": "stdstdstdstdstdtype_infostdstdstd"}, {"idx": "webquery-test-11", "doc": "Why does C++ require a user-provided default constructor to default-construct a const object?", "code": "struct POD\n{\n int i;\n};\n\nPOD p1; //uninitialized - but don't worry we can assign some value later on!\np1.i = 10; //assign some value later on!\n\nPOD p2 = POD(); //initialized\n\nconst POD p3 = POD(); //initialized \n\nconst POD p4; //uninitialized - error - as we cannot change it later on!\nstruct nonPOD_A\n{\n nonPOD_A() {} //this makes non-POD\n};\n\nnonPOD_A a1; //initialized \nconst nonPOD_A a2; //initialized \nstruct nonPOD_B\n{\n virtual void f() {} //virtual function make it non-POD\n};\n\nnonPOD_B b1; //initialized \nconst nonPOD_B b2; //initialized \nPOD p1; //uninitialized - can be useful - hence allowed\nconst POD p2; //uninitialized - never useful - hence not allowed - error\n"}, {"idx": "webquery-test-12", "doc": "Techniques for obscuring sensitive strings in C++", "code": "stringskey = key1 XOR key2\nkeykeykey1[n] = crypto_grade_random_number(0..255)\nkey2[n] = key[n] XOR key1[n]\nkey1key1"}, {"idx": "webquery-test-13", "doc": "How did this person code \"Hello World\" with Microsoft Paint?", "code": "BM'A'"}, {"idx": "webquery-test-1", "doc": "stdcall and cdecl", "code": "__stdcall__stdcallvoid __stdcall StdcallFunc() {}\n\nvoid __cdecl CdeclFunc()\n{\n // The compiler knows that StdcallFunc() uses the __stdcall\n // convention at this point, so it generates the proper binary\n // for stack cleanup.\n StdcallFunc();\n}\nLRESULT MyWndProc(HWND hwnd, UINT msg,\n WPARAM wParam, LPARAM lParam);\n// ...\n// Compiler usually complains but there's this cast here...\nwindowClass.lpfnWndProc = reinterpret_cast<WNDPROC>(&MyWndProc);\n// CALLBACK is #define'd as __stdcall\nLRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg\n WPARAM wParam, LPARAM lParam);\n// ...\nwindowClass.lpfnWndProc = &MyWndProc;\n__cdecl__cdecl"}, {"idx": "webquery-test-2", "doc": "C++11: Number of Variadic Template Function Parameters?", "code": "const std::size_t n = sizeof...(T); //you may use `constexpr` instead of `const`\nnstd::array<int, n> a; //array of n elements\nstd::array<int, 2*n> b; //array of (2*n) elements\n\nauto middle = std::get<n/2>(tupleInstance);\ntemplate<std::size_t ...>\nstruct add_all : std::integral_constant< std::size_t,0 > {};\n\ntemplate<std::size_t X, std::size_t ... Xs>\nstruct add_all<X,Xs...> : \n std::integral_constant< std::size_t, X + add_all<Xs...>::value > {};\nconstexpr auto size = add_all< sizeof(T)... >::value;\nconstexpr auto size = (sizeof(T) + ...);\n"}, {"idx": "webquery-test-3", "doc": "Why is splitting a string slower in C++ than Python?", "code": "std::stringstd::string#include <iostream> \n#include <string>\n#include <sstream>\n#include <time.h>\n#include <vector>\n\nusing namespace std;\n\nclass StringRef\n{\nprivate:\n char const* begin_;\n int size_;\n\npublic:\n int size() const { return size_; }\n char const* begin() const { return begin_; }\n char const* end() const { return begin_ + size_; }\n\n StringRef( char const* const begin, int const size )\n : begin_( begin )\n , size_( size )\n {}\n};\n\nvector<StringRef> split3( string const& str, char delimiter = ' ' )\n{\n vector<StringRef> result;\n\n enum State { inSpace, inToken };\n\n State state = inSpace;\n char const* pTokenBegin = 0; // Init to satisfy compiler.\n for( auto it = str.begin(); it != str.end(); ++it )\n {\n State const newState = (*it == delimiter? inSpace : inToken);\n if( newState != state )\n {\n switch( newState )\n {\n case inSpace:\n result.push_back( StringRef( pTokenBegin, &*it - pTokenBegin ) );\n break;\n case inToken:\n pTokenBegin = &*it;\n }\n }\n state = newState;\n }\n if( state == inToken )\n {\n result.push_back( StringRef( pTokenBegin, &*str.end() - pTokenBegin ) );\n }\n return result;\n}\n\nint main() {\n string input_line;\n vector<string> spline;\n long count = 0;\n int sec, lps;\n time_t start = time(NULL);\n\n cin.sync_with_stdio(false); //disable synchronous IO\n\n while(cin) {\n getline(cin, input_line);\n //spline.clear(); //empty the vector for the next line to parse\n\n //I'm trying one of the two implementations, per compilation, obviously:\n// split1(spline, input_line); \n //split2(spline, input_line);\n\n vector<StringRef> const v = split3( input_line );\n count++;\n };\n\n count--; //subtract for final over-read\n sec = (int) time(NULL) - start;\n cerr << \"C++ : Saw \" << count << \" lines in \" << sec << \" seconds.\" ;\n if (sec > 0) {\n lps = count / sec;\n cerr << \" Crunch speed: \" << lps << endl;\n } else\n cerr << endl;\n return 0;\n}\n\n//compiled with: g++ -Wall -O3 -o split1 split_1.cpp -std=c++0x\n"}, {"idx": "webquery-test-4", "doc": "Confused when boost::asio::io_service run method blocks/unblocks", "code": "void handle_async_receive(...) { ... }\nvoid print() { ... }\n\n... \n\nboost::asio::io_service io_service;\nboost::asio::ip::tcp::socket socket(io_service);\n\n...\n\nio_service.post(&print); // 1\nsocket.connect(endpoint); // 2\nsocket.async_receive(buffer, &handle_async_receive); // 3\nio_service.post(&print); // 4\nio_service.run(); // 5\nprintprintprintprint()print()run()run()run()run()run()run()run()run()async_io_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_service.run()io_service.run()io_service.run()printprintprintprintio_serviceio_serviceio_serviceio_serviceio_serviceio_serviceio_servicesocket->async_receivesocket->async_receivesocket->async_receivesocket->async_receivevoid CalculateFib(std::size_t n);\n\nint main()\n{\n boost::asio::io_service io_service;\n boost::optional<boost::asio::io_service::work> work = // '. 1\n boost::in_place(boost::ref(io_service)); // .'\n\n boost::thread_group worker_threads; // -.\n for(int x = 0; x < 2; ++x) // :\n { // '.\n worker_threads.create_thread( // :- 2\n boost::bind(&boost::asio::io_service::run, &io_service) // .'\n ); // :\n } // -'\n\n io_service.post(boost::bind(CalculateFib, 3)); // '.\n io_service.post(boost::bind(CalculateFib, 4)); // :- 3\n io_service.post(boost::bind(CalculateFib, 5)); // .'\n\n work = boost::none; // 4\n worker_threads.join_all(); // 5\n}\nio_serviceio_service::run()io_service::run()io_service::run()io_service::run()io_service::run()io_service::run()io_service::workio_service::workio_service::workio_service::workio_service::workio_service::workio_service::workio_service::workio_serviceio_serviceio_serviceint main()\n{\n boost::asio::io_service io_service;\n\n io_service.post(boost::bind(CalculateFib, 3)); // '.\n io_service.post(boost::bind(CalculateFib, 4)); // :- 3\n io_service.post(boost::bind(CalculateFib, 5)); // .'\n\n boost::thread_group worker_threads; // -.\n for(int x = 0; x < 2; ++x) // :\n { // '.\n worker_threads.create_thread( // :- 2\n boost::bind(&boost::asio::io_service::run, &io_service) // .'\n ); // :\n } // -'\n worker_threads.join_all(); // 5\n}\nsocket.async_receive(buffer, handler)\nio_service.run();\nboost::asio::error_code error;\nstd::size_t bytes_transferred = socket.receive(buffer, 0, error);\nhandler(error, bytes_transferred);\n"}, {"idx": "webquery-test-5", "doc": "What's the difference between span and array_view in the gsl library?", "code": "array_viewarray_viewarray_view"}, {"idx": "webquery-test-1", "doc": "Difference between function arguments declared with & and * in C++", "code": "f2f2const double& refNULLNULL"}, {"idx": "webquery-test-2", "doc": "Why can I define structures and classes within a function in C++?", "code": "operator()()operator()()operator()()"}, {"idx": "webquery-test-3", "doc": "Precompiled headers with GCC", "code": "#include <boost/xpressive/xpressive.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::xpressive;\n\n// A simple regular expression test\nint main()\n{\n std::string hello(\"Hello, World!\");\n\n sregex rex = sregex::compile( \"(\\\\w+) (\\\\w+)!\" );\n smatch what;\n\n if( regex_match( hello, what, rex ) )\n {\n std::cout << what[0] << '\\n'; // Whole match\n std::cout << what[1] << '\\n'; // First capture\n std::cout << what[2] << '\\n'; // Second capture\n }\n return 0;\n}\n-Hg++ -Wall -fexceptions -g -c main.cpp -o obj/Debug/main.o\nsudo g++ -Wall -fexceptions -g /usr/local/include/boost/xpressive/xpressive.hpp\n-Hg++ -Wall -fexceptions -H -g -c main.cpp -o obj/Debug/main.o\n\n! /usr/local/include/boost/xpressive/xpressive.hpp.gch\nmain.cpp\n. /usr/include/c++/4.4/iostream\n.. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h\n.. /usr/include/c++/4.4/ostream\n.. /usr/include/c++/4.4/istream\nmain.cpp\ng++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3\n"}, {"idx": "webquery-test-4", "doc": "Memory alignment : how to use alignof / alignas?", "code": "alignas\n#include <cstdlib>\n#include <iostream>\n\nint main() {\n alignas(16) int a[4];\n alignas(1024) int b[4];\n printf(\"%p\\n\", a);\n printf(\"%p\", b);\n}\n0xbfa493e0\n0xbfa49000 // note how many more \"zeros\" now.\n// binary equivalent\n1011 1111 1010 0100 1001 0011 1110 0000\n1011 1111 1010 0100 1001 0000 0000 0000 // every zero is just a extra power of 2\nalignof\nint a[4];\nassert(a % 16 == 0); // check if alignment is to 16 bytes: WRONG compiler error\nassert(alignof(a) == 16);\nassert(alignof(b) == 1024);\n assert(alignof(b) == 32); // fail.\nalignas(alignof(float)) float SqDistance;\n"}, {"idx": "webquery-test-5", "doc": "Default member values best practice", "code": "class Foo\n{\n bool done = false; // always start like this\n int qty;\n Bar * p;\n\npublic:\n Foo() : qty(0), p(nullptr) { }\n Foo(int q, Bar * bp) : qty(q), p(bp) { }\n explicit Foo(char const * s) : qty(std::strlen(s)), p(new Bar(s)) { }\n\n // ...\n};\ndonedonedonedone"}, {"idx": "webquery-test-6", "doc": "Deprecation of the static keyword... no more?", "code": "1012. Undeprecating staticstaticstatic"}, {"idx": "webquery-test-7", "doc": "Why can't I capture this by-reference ('&this') in lambda?", "code": "[&this][&this][&this]capture:\n identifier\n & identifier\n this\n&this&this&thisthisthisthiscapturecapturecapture-default:\n &\n =\n&&&&thisthisxx&&&&&&[this][this][this][this][this][this][&this][&this][&this][&this]"}, {"idx": "webquery-test-8", "doc": "C++ Get name of type in template", "code": "typeid(T).name()\ntypeid(T)"}, {"idx": "webquery-test-9", "doc": "How to programmatically cause a core dump in C/C++", "code": "SIGABRTSIGABRT#include <signal.h>\n: : :\nraise (SIGABRT);\nabort()abort()abort()"}, {"idx": "webquery-test-10", "doc": "c++ deque vs queue vs stack", "code": " std::stack<int, std::deque<int> > s;\n std::queue<double, std::list<double> > q;\nssback()back()back()back()back()back()back()operator[]operator[]operator[]"}, {"idx": "webquery-test-11", "doc": "std::thread calling method of class", "code": "#include <thread>\n\nvoid Test::runMultiThread()\n{\n std::thread t1(&Test::calculate, this, 0, 10);\n std::thread t2(&Test::calculate, this, 11, 20);\n t1.join();\n t2.join();\n}\n#include <future>\n\nvoid Test::runMultiThread()\n{\n auto f1 = std::async(&Test::calculate, this, 0, 10);\n auto f2 = std::async(&Test::calculate, this, 11, 20);\n\n auto res1 = f1.get();\n auto res2 = f2.get();\n}\n"}, {"idx": "webquery-test-1", "doc": "Should arrays be used in C++?", "code": "std::array"}, {"idx": "webquery-test-2", "doc": "Why is NULL undeclared?", "code": "NULLNULLnullptr#include <<a href=\"http://en.wikipedia.org/wiki/Stddef.h\" rel=\"noreferrer\">stddef.h</a>>NULL"}, {"idx": "webquery-test-3", "doc": "Expression must have class type", "code": "a->f();\n.A a;\na.f();\nA& ref = a;\nref.f();\nA* ptr = new A();\n(*ptr).f();\nptr->f();\na->ba->boperator->operator->auto ptr = make_unique<A>();\nptr->f();\n"}, {"idx": "webquery-test-4", "doc": "How to read a file line by line or a whole text file at once?", "code": "std::getline#include <fstream>\n#include <string>\n\nint main() \n{ \n std::ifstream file(\"Read.txt\");\n std::string str; \n while (std::getline(file, str))\n {\n // Process str\n }\n}\nstd::string::getline()std::ifstream file(\"Read.txt\");\nstd::string str;\nstd::string file_contents;\nwhile (std::getline(file, str))\n{\n file_contents += str;\n file_contents.push_back('\\n');\n} \n"}, {"idx": "webquery-test-5", "doc": "Passing std::string by Value or Reference", "code": "(std::string const&)(std::string)(std::string &)(std::string &&)"}, {"idx": "webquery-test-6", "doc": "Finding the position of the maximum element", "code": "std::max_elementstd::max_elementint main(int argc, char** argv) {\n int A[4] = {0, 2, 3, 1};\n const int N = sizeof(A) / sizeof(int);\n\n cout << \"Index of max element: \"\n << distance(A, max_element(A, A + N))\n << endl;\n\n return 0;\n}\n"}, {"idx": "webquery-test-7", "doc": "How to make C++ cout not use scientific notation", "code": "std::fixedcout<<fixed<<\"Bas ana: \"<<x<<\"\\tSon faiz: \"<<t<<\"\\tSon ana: \"<<x+t<<endl;\n"}, {"idx": "webquery-test-8", "doc": "Why is assigning a value to a bit field not giving the same value back?", "code": "struct mystruct {int enabled:1;};int:nintintsigned intsigned intint"}, {"idx": "webquery-test-9", "doc": "OpenCV Point(x,y) represent (column,row) or (row,column)", "code": "src.at(i,j)src.at(i,j)src.at(i,j)src.at(i,j)cv::Mat0/0---column--->\n |\n |\nrow\n |\n |\n v\n ^\n |\n |\n Y\n |\n |\n0/0---X--->\n0/0---X--->\n |\n |\n Y\n |\n |\n v\nmat.at<type>(row,column)mat.at<type>(row,column)mat.at<type>(row,column)mat.at<type>(row,column)"}, {"idx": "webquery-test-10", "doc": "How to get the file size in bytes with C++17", "code": "<filesystem>#include <cstdint>\n#include <filesystem>\n\n// ...\n\nstd::uintmax_t size = std::filesystem::file_size(\"c:\\\\foo\\\\bar.txt\");\n"}, {"idx": "webquery-test-11", "doc": "Signed/unsigned comparisons", "code": "-1 == (unsigned) -1-1 == (unsigned) -1-1 == -1-1 == -1-1 < 2-1 < 2"}, {"idx": "webquery-test-1", "doc": "How to read until EOF from cin in C++", "code": "stdinstdinstd::string line;\nwhile (std::getline(std::cin, line))\n{\n std::cout << line << std::endl;\n}\ngetline()getline()"}, {"idx": "webquery-test-2", "doc": "Proper way to create unique_ptr that holds an allocated array", "code": "T[]std::unique_ptr<unsigned char[]> testData(new unsigned char[16000]());\nnewnewnewauto testData = std::make_unique<unsigned char[]>(16000);\n"}, {"idx": "webquery-test-3", "doc": "Why can't I create a vector of lambdas (of the same type) in C++11?", "code": "std::functionstd::vector<std::function<int()>> functors;\nfunctors.push_back([&] { return 100; });\nfunctors.push_back([&] { return 10; });\n"}, {"idx": "webquery-test-4", "doc": "What does OpenCV's cvWaitKey( ) function do?", "code": "cvWaitKey(x) / cv::waitKey(x)cv::imshow()cv::imshow()cv::imshow()cv::imshow()cv::imshow()cv::imshow()cv::imshow()cv::imshow()"}, {"idx": "webquery-test-5", "doc": "Efficiency of premature return in a function", "code": "=====> cat test_return.cpp\nextern void something();\nextern void something2();\n\nvoid test(bool b)\n{\n if(b)\n {\n something();\n }\n else\n something2();\n}\n=====> cat test_return2.cpp\nextern void something();\nextern void something2();\n\nvoid test(bool b)\n{\n if(b)\n {\n something();\n return;\n }\n something2();\n}\n=====> rm -f test_return.s test_return2.s\n=====> g++ -S test_return.cpp \n=====> g++ -S test_return2.cpp \n=====> diff test_return.s test_return2.s\n=====> rm -f test_return.s test_return2.s\n=====> clang++ -S test_return.cpp \n=====> clang++ -S test_return2.cpp \n=====> diff test_return.s test_return2.s\n=====> \n"}, {"idx": "webquery-test-6", "doc": "Multi line preprocessor macros", "code": "\\#define swap(a, b) { \\\n (a) ^= (b); \\\n (b) ^= (a); \\\n (a) ^= (b); \\\n }\n\\"}, {"idx": "webquery-test-7", "doc": "How to copy contents of a directory into build directory after make with CMake?", "code": "add_custom_commandMyTargetadd_custom_command(TARGET MyTarget PRE_BUILD\n COMMAND ${CMAKE_COMMAND} -E copy_directory\n ${CMAKE_SOURCE_DIR}/config/ $<TARGET_FILE_DIR:MyTarget>)\nMyTargetPRE_BUILDPRE_BUILDPRE_BUILD${CMAKE_COMMAND}${CMAKE_COMMAND}${CMAKE_COMMAND}${CMAKE_COMMAND}${CMAKE_COMMAND}${CMAKE_COMMAND}"}, {"idx": "webquery-test-8", "doc": "Run C++ in command prompt - Windows", "code": "cdcdcdcd"}, {"idx": "webquery-test-9", "doc": "How to call on a function found on another file?", "code": "player.h#ifndef PLAYER_H // To make sure you don't declare the function more than once by including the header multiple times.\n#define PLAYER_H\n\n#include \"stdafx.h\"\n#include <SFML/Graphics.hpp>\n\nint playerSprite();\n\n#endif\n#include \"player.h\" // player.h must be in the current directory. or use relative or absolute path to it. e.g #include \"include/player.h\"\n\nint playerSprite(){\n sf::Texture Texture;\n if(!Texture.loadFromFile(\"player.png\")){\n return 1;\n }\n sf::Sprite Sprite;\n Sprite.setTexture(Texture);\n return 0;\n}\n#include \"stdafx.h\"\n#include <SFML/Graphics.hpp>\n#include \"player.h\" //Here. Again player.h must be in the current directory. or use relative or absolute path to it.\n\nint main()\n{\n // ...\n int p = playerSprite(); \n //...\n#include \"stdafx.h\"\n#include <SFML/Graphics.hpp>\n// #include \"player.cpp\"\n\n\nint playerSprite(); // Here\n\nint main()\n{\n // ... \n int p = playerSprite(); \n //...\n"}, {"idx": "webquery-test-10", "doc": "Is there go up line character? (Opposite of \\n)", "code": "\"\\033[F\"\"\\033[F\"print(\"\\033[FMy text overwriting the previous line.\")\n"}, {"idx": "webquery-test-11", "doc": "explicit specialization of template class member function", "code": "template <class C> template<>\nvoid X<C>::get_as<double>()\n{\n\n}\nX<int>template <> template<>\nvoid X<int>::get_as<double>()\n{\n\n}\ntemplate <class C> class X\n{\n template<typename T> struct type { };\n\npublic:\n template <class T> void get_as() {\n get_as(type<T>());\n }\n\nprivate:\n template<typename T> void get_as(type<T>) {\n\n }\n\n void get_as(type<double>) {\n\n }\n};\n"}, {"idx": "webquery-test-12", "doc": "What is COM (Component Object Model) in a nutshell?", "code": "interface IUnknown\n{\n virtual HRESULT QueryInterface(REFIID riid, void **ppvObject) = 0;\n virtual ULONG AddRef(void) = 0;\n virtual ULONG Release(void) = 0;\n};\nQueryInterfaceQueryInterfaceQueryInterfaceCoCreateInstance()CoCreateInstance()"}, {"idx": "webquery-test-1", "doc": "Will using goto leak variables?", "code": "xgotogotocasevoid f() {\n int x = 0;\n goto lol;\n}\n\nint main() {\n f();\nlol:\n return 0;\n}\n\n// error: label 'lol' used but not defined\n[n3290: 6.1/1]:int main() {\n goto lol;\n int x = 0;\nlol:\n return 0;\n}\n\n// error: jump to label \u2018lol\u2019\n// error: from here\n// error: crosses initialization of \u2018int x\u2019\nstruct T {\n T() { cout << \"*T\"; }\n ~T() { cout << \"~T\"; }\n};\n\nint main() {\n int x = 0;\n\n lol:\n T t;\n if (x++ < 5)\n goto lol;\n}\n\n// Output: *T~T*T~T*T~T*T~T*T~T*T~T\n[n3290: 6.6/2]:int main() {\n goto lol;\n {\n std::string x;\nlol:\n x = \"\";\n }\n}\n\n// error: jump to label \u2018lol\u2019\n// error: from here\n// error: crosses initialization of \u2018std::string x\u2019\nint main() {\n goto lol;\n {\n int x;\nlol:\n x = 0;\n }\n}\n\n// OK\n[n3290: 6.7/3]:gotostruct T {\n T() { cout << \"*T\"; }\n ~T() { cout << \"~T\"; }\n};\n\nint main() {\n {\n T t;\n goto lol;\n }\n\nlol:\n return 0;\n}\n\n// *T~T\n[n3290: 6.6/2]:gotogoto"}, {"idx": "webquery-test-2", "doc": "How to convert string to IP address and vice versa", "code": "inet_ntop()inet_ntop()inet_ntop()// IPv4 demo of inet_ntop() and inet_pton()\n\nstruct sockaddr_in sa;\nchar str[INET_ADDRSTRLEN];\n\n// store this IP address in sa:\ninet_pton(AF_INET, \"192.0.2.33\", &(sa.sin_addr));\n\n// now get it back and print it\ninet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);\n\nprintf(\"%s\\n\", str); // prints \"192.0.2.33\"\n"}, {"idx": "webquery-test-3", "doc": "How does the main() method work in C?", "code": " ;; pseudo-assembly-language\n ;; main(argc, argv, envp); call\n\n push envp ;; rightmost argument\n push argv ;; \n push argc ;; leftmost argument ends up on top of stack\n\n call main\n\n pop ;; caller cleans up \n pop\n pop\nmainmainmainmain/* I'm adding envp to show that even a popular platform-specific variant\n can be handled. */\nextern int main(int argc, char **argv, char **envp);\n\nvoid __start(void)\n{\n /* This is the real startup function for the executable.\n It performs a bunch of library initialization. */\n\n /* ... */\n\n /* And then: */\n exit(main(argc_from_somewhere, argv_from_somewhere, envp_from_somewhere));\n}\nint, char **mainmainint main(void)\n{\n /* ... */\n}\nint main(int __argc_ignore, char **__argv_ignore, char **__envp_ignore)\n{\n /* ... */\n}\n__argc_ignore__start__start__start__startmainmainmainmainmain"}, {"idx": "webquery-test-4", "doc": "How to declare a function that accepts a lambda?", "code": "operator()template<typename Func>\nvoid LambdaTest(Func f) {\n f(10);\n}\n"}, {"idx": "webquery-test-5", "doc": "C# equivalent of C++ vector, with contiguous memory?", "code": "List<T>List<T>List<T>List<int> integers = new List<int>();\nintegers.Add(1);\nintegers.Add(4);\nintegers.Add(7);\n\nint someElement = integers[1];\n"}, {"idx": "webquery-test-6", "doc": "Pretty-print std::tuple", "code": "namespace aux{\ntemplate<std::size_t...> struct seq{};\n\ntemplate<std::size_t N, std::size_t... Is>\nstruct gen_seq : gen_seq<N-1, N-1, Is...>{};\n\ntemplate<std::size_t... Is>\nstruct gen_seq<0, Is...> : seq<Is...>{};\n\ntemplate<class Ch, class Tr, class Tuple, std::size_t... Is>\nvoid print_tuple(std::basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){\n using swallow = int[];\n (void)swallow{0, (void(os << (Is == 0? \"\" : \", \") << std::get<Is>(t)), 0)...};\n}\n} // aux::\n\ntemplate<class Ch, class Tr, class... Args>\nauto operator<<(std::basic_ostream<Ch, Tr>& os, std::tuple<Args...> const& t)\n -> std::basic_ostream<Ch, Tr>&\n{\n os << \"(\";\n aux::print_tuple(os, t, aux::gen_seq<sizeof...(Args)>());\n return os << \")\";\n}\n// Delimiters for tuple\ntemplate<class... Args>\nstruct delimiters<std::tuple<Args...>, char> {\n static const delimiters_values<char> values;\n};\n\ntemplate<class... Args>\nconst delimiters_values<char> delimiters<std::tuple<Args...>, char>::values = { \"(\", \", \", \")\" };\n\ntemplate<class... Args>\nstruct delimiters<std::tuple<Args...>, wchar_t> {\n static const delimiters_values<wchar_t> values;\n};\n\ntemplate<class... Args>\nconst delimiters_values<wchar_t> delimiters<std::tuple<Args...>, wchar_t>::values = { L\"(\", L\", \", L\")\" };\noperator<<operator<<template<class Ch, class Tr, class... Args>\nauto operator<<(std::basic_ostream<Ch, Tr>& os, std::tuple<Args...> const& t)\n -> std::basic_ostream<Ch, Tr>&\n{\n typedef std::tuple<Args...> tuple_t;\n if(delimiters<tuple_t, Ch>::values.prefix != 0)\n os << delimiters<tuple_t,char>::values.prefix;\n\n print_tuple(os, t, aux::gen_seq<sizeof...(Args)>());\n\n if(delimiters<tuple_t, Ch>::values.postfix != 0)\n os << delimiters<tuple_t,char>::values.postfix;\n\n return os;\n}\ntemplate<class Ch, class Tr, class Tuple, std::size_t... Is>\nvoid print_tuple(std::basic_ostream<Ch, Tr>& os, Tuple const& t, seq<Is...>){\n using swallow = int[];\n char const* delim = delimiters<Tuple, Ch>::values.delimiter;\n if(!delim) delim = \"\";\n (void)swallow{0, (void(os << (Is == 0? \"\" : delim) << std::get<Is>(t)), 0)...};\n}\n"}, {"idx": "webquery-test-7", "doc": "Equivalent of #region for C++", "code": "// pragma_directives_region.cpp\n#pragma region Region_1\nvoid Test() {}\nvoid Test2() {}\nvoid Test3() {}\n#pragma endregion Region_1\n\nint main() {}\n"}, {"idx": "webquery-test-8", "doc": "Getting std :: ifstream to handle LF, CR, and CRLF?", "code": "std::istream& safeGetline(std::istream& is, std::string& t)\n{\n t.clear();\n\n // The characters in the stream are read one-by-one using a std::streambuf.\n // That is faster than reading them one-by-one using the std::istream.\n // Code that uses streambuf this way must be guarded by a sentry object.\n // The sentry object performs various tasks,\n // such as thread synchronization and updating the stream state.\n\n std::istream::sentry se(is, true);\n std::streambuf* sb = is.rdbuf();\n\n for(;;) {\n int c = sb->sbumpc();\n switch (c) {\n case '\\n':\n return is;\n case '\\r':\n if(sb->sgetc() == '\\n')\n sb->sbumpc();\n return is;\n case std::streambuf::traits_type::eof():\n // Also handle the case when the last line has no line ending\n if(t.empty())\n is.setstate(std::ios::eofbit);\n return is;\n default:\n t += (char)c;\n }\n }\n}\nint main()\n{\n std::string path = ... // insert path to test file here\n\n std::ifstream ifs(path.c_str());\n if(!ifs) {\n std::cout << \"Failed to open the file.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n int n = 0;\n std::string t;\n while(!safeGetline(ifs, t).eof())\n ++n;\n std::cout << \"The file contains \" << n << \" lines.\" << std::endl;\n return EXIT_SUCCESS;\n}\n"}, {"idx": "webquery-test-9", "doc": "Set precision of std::to_string when converting floating point values", "code": "to_string()to_string()#include <sstream>\n\ntemplate <typename T>\nstd::string to_string_with_precision(const T a_value, const int n = 6)\n{\n std::ostringstream out;\n out.precision(n);\n out << std::fixed << a_value;\n return out.str();\n}\n"}, {"idx": "webquery-test-10", "doc": "Possible to call C++ code from C#?", "code": "#include \"NativeType.h\"\n\npublic ref class ManagedType\n{\n NativeType* NativePtr; \n\npublic:\n ManagedType() : NativePtr(new NativeType()) {}\n ~ManagedType() { delete NativePtr; }\n\n void ManagedMethod()\n { NativePtr->NativeMethod(); } \n}; \nManagedType mt = new ManagedType();\nmt.ManagedMethod();\n"}, {"idx": "webquery-test-1", "doc": "c++ parse int from string", "code": "std::stoistd::stoistd::stoistd::stoistd::stoistd::stoistd::stoistd::stoistd::stoistd::stois = \"10jh\"int to_int(char const *s)\n{\n if ( s == NULL || *s == '\\0' )\n throw std::invalid_argument(\"null or empty string argument\");\n\n bool negate = (s[0] == '-');\n\u00a0 \u00a0 \u00a0if ( *s == '+' || *s == '-' )\u00a0\n\u00a0 \u00a0 \u00a0 \u00a0 ++s;\n\n if ( *s == '\\0')\n throw std::invalid_argument(\"sign character only.\");\n\n\u00a0 \u00a0 \u00a0int result = 0;\n\u00a0 \u00a0 \u00a0while(*s)\n\u00a0 \u00a0 \u00a0{\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 if ( *s < '0' || *s > '9' )\n throw std::invalid_argument(\"invalid input string\");\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 result = result * 10 \u00a0- (*s - '0'); \u00a0//assume negative number\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 ++s;\n\u00a0 \u00a0 \u00a0}\n\u00a0 \u00a0 \u00a0return negate ? result : -result; //-result is positive!\n}\u00a0\n"}, {"idx": "webquery-test-2", "doc": "Is 'auto const' and 'const auto' the same?", "code": "const"}, {"idx": "webquery-test-3", "doc": "How do you 'realloc' in C++?", "code": "Type* t = (Type*)malloc(sizeof(Type)*n) \nmemset(t, 0, sizeof(Type)*m)\n::std::vector<Type> t(n, 0);\nt = (Type*)realloc(t, sizeof(Type) * n2);\nt.resize(n2);\nFoo(t)\nFoo(&t[0])\n"}, {"idx": "webquery-test-4", "doc": "Detecting signed overflow in C/C++", "code": "int half = INT_MAX/2;\nint half1 = half + 1;\nINT_MAXINT_MAXINT_MAX<<int add(int lhs, int rhs)\n{\n if (lhs >= 0) {\n if (INT_MAX - lhs < rhs) {\n /* would overflow */\n abort();\n }\n }\n else {\n if (rhs < INT_MIN - lhs) {\n /* would overflow */\n abort();\n }\n }\n return lhs + rhs;\n}\nlhs"}, {"idx": "webquery-test-5", "doc": "shared_ptr magic :)", "code": "boost::functionboost::functiontemplate<class T>\nclass shared_ptr\n{\npublic:\n ...\n template<class Y>\n explicit shared_ptr(Y* p);\n ...\n};\nBaseBaseclass Base {};\nclass Derived : public Base {};\n\nint main() {\n shared_ptr<Base> sp (new Derived);\n}\nY=DerivedY=DerivedY=Derivedpppppp*this*this*this*this*this*this*this*this*this*this"}, {"idx": "webquery-test-6", "doc": "Reusing a moved container?", "code": "xxxxxclear"}, {"idx": "webquery-test-7", "doc": "How to store variadic template arguments?", "code": "std::tuple<Ts...> args;\nargsargstemplate <typename F, typename... Args>\nAction(F&& func, Args&&... args)\n : f(std::forward<F>(func)),\n args(std::forward<Args>(args)...)\n{}\nnamespace helper\n{\n template <int... Is>\n struct index {};\n\n template <int N, int... Is>\n struct gen_seq : gen_seq<N - 1, N - 1, Is...> {};\n\n template <int... Is>\n struct gen_seq<0, Is...> : index<Is...> {};\n}\ntemplate <typename... Args, int... Is>\nvoid func(std::tuple<Args...>& tup, helper::index<Is...>)\n{\n f(std::get<Is>(tup)...);\n}\n\ntemplate <typename... Args>\nvoid func(std::tuple<Args...>& tup)\n{\n func(tup, helper::gen_seq<sizeof...(Args)>{});\n}\n\nvoid act()\n{\n func(args);\n}\ntemplate <typename... Ts>\nclass Action\n{\nprivate:\n std::function<void (Ts...)> f;\n std::tuple<Ts...> args;\npublic:\n template <typename F, typename... Args>\n Action(F&& func, Args&&... args)\n : f(std::forward<F>(func)),\n args(std::forward<Args>(args)...)\n {}\n\n template <typename... Args, int... Is>\n void func(std::tuple<Args...>& tup, helper::index<Is...>)\n {\n f(std::get<Is>(tup)...);\n }\n\n template <typename... Args>\n void func(std::tuple<Args...>& tup)\n {\n func(tup, helper::gen_seq<sizeof...(Args)>{});\n }\n\n void act()\n {\n func(args);\n }\n};\ntemplate <typename F, typename... Args>\nAction<Args...> make_action(F&& f, Args&&... args)\n{\n return Action<Args...>(std::forward<F>(f), std::forward<Args>(args)...);\n}\n\nint main()\n{\n auto add = make_action([] (int a, int b) { std::cout << a + b; }, 2, 3);\n\n add.act();\n}\n"}, {"idx": "webquery-test-1", "doc": "C++ pass an array by reference", "code": "void foo(double (&bar)[10])\n{\n}\ndouble arr[20];\nfoo(arr); // won't compile\nfootemplate<typename T, size_t N>\nvoid foo(T (&bar)[N])\n{\n // use N here\n}\nstd::vectorstd::vector"}, {"idx": "webquery-test-2", "doc": "Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio", "code": "QPixmap p; // load pixmap\n// get label dimensions\nint w = label->width();\nint h = label->height();\n\n// set a scaled pixmap to a w x h window keeping its aspect ratio \nlabel->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));\nresizeEvent"}, {"idx": "webquery-test-3", "doc": "In this specific case, is there a difference between using a member initializer list and assigning values in a constructor?", "code": "struct aa\n{\n int i;\n const int ci; // constant member\n\n aa() : i(0) {} // will fail, constant member not initialized\n};\n\nstruct aa\n{\n int i;\n const int ci;\n\n aa() : i(0) { ci = 3;} // will fail, ci is constant\n};\n\nstruct aa\n{\n int i;\n const int ci;\n\n aa() : i(0), ci(3) {} // works\n};\nstruct bb {};\n\nstruct aa\n{\n bb& rb;\n aa(bb& b ) : rb(b) {}\n};\n\n// usage:\n\nbb b;\naa a(b);\nstruct bb {};\n\nstruct dd\n{\n char c;\n dd(char x) : c(x) {}\n};\n\nstruct aa : dd\n{\n bb& rb;\n aa(bb& b ) : dd('a'), rb(b) {}\n};\n"}, {"idx": "webquery-test-4", "doc": "How to find the index of current object in range-based for loop?", "code": "template <typename T>\nstruct iterator_extractor { typedef typename T::iterator type; };\n\ntemplate <typename T>\nstruct iterator_extractor<T const> { typedef typename T::const_iterator type; };\n\n\ntemplate <typename T>\nclass Indexer {\npublic:\n class iterator {\n typedef typename iterator_extractor<T>::type inner_iterator;\n\n typedef typename std::iterator_traits<inner_iterator>::reference inner_reference;\n public:\n typedef std::pair<size_t, inner_reference> reference;\n\n iterator(inner_iterator it): _pos(0), _it(it) {}\n\n reference operator*() const { return reference(_pos, *_it); }\n\n iterator& operator++() { ++_pos; ++_it; return *this; }\n iterator operator++(int) { iterator tmp(*this); ++*this; return tmp; }\n\n bool operator==(iterator const& it) const { return _it == it._it; }\n bool operator!=(iterator const& it) const { return !(*this == it); }\n\n private:\n size_t _pos;\n inner_iterator _it;\n };\n\n Indexer(T& t): _container(t) {}\n\n iterator begin() const { return iterator(_container.begin()); }\n iterator end() const { return iterator(_container.end()); }\n\nprivate:\n T& _container;\n}; // class Indexer\n\ntemplate <typename T>\nIndexer<T> index(T& t) { return Indexer<T>(t); }\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <vector>\n\n// Zipper code here\n\nint main() {\n std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n for (auto p: index(v)) {\n std::cout << p.first << \": \" << p.second << \"\\n\";\n }\n}\nzipzipcounting_rangecounting_rangeint main() {\n std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n for (auto tuple: zip(iota(0), v)) {\n std::cout << tuple.at<0>() << \": \" << tuple.at<1>() << \"\\n\";\n }\n}\nzipzipzip"}, {"idx": "webquery-test-5", "doc": "Why do (only) some compilers use the same address for identical string literals?", "code": "A == BA == BA == B"}, {"idx": "webquery-test-6", "doc": "std::vector::resize() vs. std::vector::reserve()", "code": "std::vector::reservestd::vector::resize&vec[4]&vec[4]&vec[4]"}, {"idx": "webquery-test-7", "doc": "does `const auto` have any meaning?", "code": "const auto x = expr;\nauto x = expr;\nconst X x = expr;\nX x = expr;\nconst autoconst autoconst autoconstconstconstconst"}, {"idx": "webquery-test-8", "doc": "Copy constructor and = operator overload in C++: is a common function possible?", "code": "operator=MyClass(const MyClass& other)\n{\n operator=(other);\n}\noperator=operator=operator=MyClass& operator=(const MyClass& other)\n{\n MyClass tmp(other);\n swap(tmp);\n return *this;\n}\nMyClass& operator=(MyClass other)\n{\n swap(other);\n return *this;\n}\nswapstd::swapswapswap"}, {"idx": "webquery-test-9", "doc": "What exactly is streambuf? How do I use it?", "code": "streambuf"}, {"idx": "webquery-test-10", "doc": "What is const void?", "code": "const voidconst voidconst voidconst voidconst voidconst voidconst voidconst voidconst voidconst int i = 10;\nvoid* vp = &i; // error\nconst void* cvp = &i; // ok\nauto ip = static_cast<int*>(cvp); // error\nauto cip = static_cast<const int*>(cvp); // ok\n"}, {"idx": "webquery-test-1", "doc": "Why would I prefer using vector to deque", "code": "dequedequedequedequedequedeque"}, {"idx": "webquery-test-2", "doc": "How to make a conditional typedef in C++", "code": "std::conditional#include <type_traits> //include this\n\ntypedef std::conditional<sizeof(int) <= 4,\n std::mt19937,\n std::mt19937_64>::type Engine;\nsizeofsizeofsizeoftypedef typename std::conditional<sizeof(T) <= 4, // T is template parameter\n std::mt19937,\n std::mt19937_64>::type Engine;\nEngineEnginetemplate<typename T>\nusing Engine = typename std::conditional<sizeof(T) <= 4, \n std::mt19937,\n std::mt19937_64>::type;\nEngine<int> engine1;\nEngine<long> engine2;\nEngine<T> engine3; // where T could be template parameter!\n"}, {"idx": "webquery-test-3", "doc": "How should I use FormatMessage() properly in C++?", "code": "HRESULTHRESULTLPTSTR errorText = NULL;\n\nFormatMessage(\n // use system message tables to retrieve error text\n FORMAT_MESSAGE_FROM_SYSTEM\n // allocate buffer on local heap for error text\n |FORMAT_MESSAGE_ALLOCATE_BUFFER\n // Important! will fail otherwise, since we're not \n // (and CANNOT) pass insertion parameters\n |FORMAT_MESSAGE_IGNORE_INSERTS, \n NULL, // unused with FORMAT_MESSAGE_FROM_SYSTEM\n hresult,\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n (LPTSTR)&errorText, // output \n 0, // minimum size for output buffer\n NULL); // arguments - see note \n \nif ( NULL != errorText )\n{\n // ... do something with the string `errorText` - log it, display it to the user, etc.\n\n // release memory allocated by FormatMessage()\n LocalFree(errorText);\n errorText = NULL;\n}\nFORMAT_MESSAGE_IGNORE_INSERTS_com_error{\n _com_error error(hresult);\n LPCTSTR errorText = error.ErrorMessage();\n \n // do something with the error...\n\n //automatic cleanup when error goes out of scope\n}\n"}, {"idx": "webquery-test-4", "doc": "memset() or value initialization to zero out a struct?", "code": "memsetstruct POD_OnlyStruct\n{\n int a;\n char b;\n};\n\nPOD_OnlyStruct t = {}; // OK\n\nPOD_OnlyStruct t;\nmemset(&t, 0, sizeof t); // OK as well\nPOD_OnlyStruct t = {}POD_OnlyStruct t = {}POD_OnlyStruct t = {}struct TestStruct\n{\n int a;\n std::string b;\n};\n\nTestStruct t = {}; // OK\n\n{\n TestStruct t1;\n memset(&t1, 0, sizeof t1); // ruins member 'b' of our struct\n} // Application crashes here\nTestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}TestStruct t = {}memsetmemsetmemset"}, {"idx": "webquery-test-5", "doc": "Confusion between C++ and OpenGL matrix order (row-major vs column-major)", "code": "x.x x.y x.z 0\ny.x y.y y.z 0\nz.x z.y z.z 0\np.x p.y p.z 1\n{ x.x x.y x.z 0 y.x y.y y.z 0 z.x z.y z.z 0 p.x p.y p.z 1 }\n{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, transX, transY, transZ, 1 }.\nm x nm x nm x nm x nm x nm x nm x nm x nm x nm x nm x nm x n//matrix\n|a11 a12 a13|\n|a21 a22 a23|\n|a31 a32 a33|\n\n//row-major\n[a11 a12 a13 a21 a22 a23 a31 a32 a33]\n\n //column-major\n[a11 a21 a31 a12 a22 a32 a13 a23 a33]\n//convention #1\n|vx.x vy.x vz.x pos.x| |p.x| |res.x|\n|vx.y vy.y vz.y pos.y| |p.y| |res.y|\n|vx.z vy.z vz.z pos.z| x |p.z| = |res.z|\n| 0 0 0 1| | 1| |res.w| \n//convention #2 (uncommon)\n | vx.x vx.y vx.z 0| \n | vy.x vy.y vy.z 0| \n|p.x p.y p.z 1| x | vz.x vz.y vz.z 0| = |res.x res.y res.z res.w|\n |pos.x pos.y pos.z 1| \n[vx.x vx.y vx.z 0 vy.x vy.y vy.z 0 vz.x vz.y vz.z 0 pos.x pos.y pos.z 1]\n"}, {"idx": "webquery-test-6", "doc": "conversion from derived * to base * exists but is inaccessible", "code": "class d : public c\nclassclassclassclass"}, {"idx": "webquery-test-7", "doc": "Defining global constant in C++", "code": "// header.hpp\nnamespace constants\n{\n const int GLOBAL_CONST_VAR = 0xFF;\n // ... other related constants\n\n} // namespace constants\n\n// source.cpp - use it\n#include <header.hpp>\nint value = constants::GLOBAL_CONST_VAR;\n"}, {"idx": "webquery-test-8", "doc": "When do we have to use copy constructors?", "code": "class Class {\npublic:\n Class( const char* str );\n ~Class();\nprivate:\n char* stored;\n};\n\nClass::Class( const char* str )\n{\n stored = new char[srtlen( str ) + 1 ];\n strcpy( stored, str );\n}\n\nClass::~Class()\n{\n delete[] stored;\n}\nstoredstoredClass::Class( const Class& another )\n{\n stored = new char[strlen(another.stored) + 1];\n strcpy( stored, another.stored );\n}\n\nvoid Class::operator = ( const Class& another )\n{\n char* temp = new char[strlen(another.stored) + 1];\n strcpy( temp, another.stored);\n delete[] stored;\n stored = temp;\n}\n"}, {"idx": "webquery-test-9", "doc": "How can I \"unuse\" a namespace?", "code": "namespace codegear {\n #include \"codegear_header.h\"\n} // namespace codegear\n"}, {"idx": "webquery-test-10", "doc": "Accessing Environment Variables In C++", "code": "getenv()getenv()getenv()getenv()getenv()System::Environment::GetEnvironmentVariable()System::Environment::GetEnvironmentVariable()"}, {"idx": "webquery-test-11", "doc": "What is the difference between C++0x and C++11?", "code": "x"}, {"idx": "webquery-test-12", "doc": "How to pass a vector to a function?", "code": "vectorint binarySearch(int first, int last, int search4, vector<int>& random);\n\nvector<int> random(100);\n// ...\nfound = binarySearch(first, last, search4, random);\nint binarySearch(int first, int last, int search4, vector<int>* random);\n\nvector<int> random(100);\n// ...\nfound = binarySearch(first, last, search4, &random);\nbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearchbinarySearch"}, {"idx": "webquery-test-1", "doc": "volatile vs. mutable in C++", "code": "mutablemutablemutablemutable"}, {"idx": "webquery-test-2", "doc": "How to read entire stream into a std::string?", "code": "std::istreambuf_iterator<char> eos;\nstd::string s(std::istreambuf_iterator<char>(stream), eos);\nstd::string s(std::istreambuf_iterator<char>(stream), {});\n"}, {"idx": "webquery-test-3", "doc": "Creating files in C++", "code": "// using ofstream constructors.\n#include <iostream>\n#include <fstream> \n\nstd::ofstream outfile (\"test.txt\");\n\noutfile << \"my text here!\" << std::endl;\n\noutfile.close();\n"}, {"idx": "webquery-test-4", "doc": "Why does the first element outside of a defined array default to zero?", "code": "int x[] = {120, 200, 16};\nx for (int i = 0; i < 4; i++)\n cout << x[i] << \" \";\nint x[4] = {120, 200, 16};\n"}, {"idx": "webquery-test-5", "doc": "What is monomorphisation with context to C++?", "code": "fn first<A, B>(pair: (A, B)) -> A {\n let (a, b) = pair;\n return a;\n}\nfirst((1, 2));\nfirst((\"a\", \"b\"));\nfirst()"}, {"idx": "webquery-test-6", "doc": "How can I improve performance via a high-level approach when implementing long equations in C++", "code": "pow(x, 0.1e1/0.3e1)pow(x, 0.1e1/0.3e1)pow(x, 0.1e1/0.3e1)pow(x, 0.1e1/0.3e1)pow(x, 0.1e1/0.3e1)pow(x, 0.1e1/0.3e1)l1l1l1l1l1l1l1l1l1l1l1mumu-ffast-math-ffast-mathpowpowpowl123 = l1 * l2 * l3;\nl123_pow_1_3 = std::cbrt(l123);\nl123_pow_4_3 = l123 * l123_pow_1_3;\nX * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)X * pow(l1 * l2 * l3, 0.1e1 / 0.3e1)(pow(l1 * l2 * l3, -0.1e1 / 0.3e1) - l1 * l2 * l3 * pow(l1 * l2 * l3, -0.4e1 / 0.3e1) / 0.3e1)\nl1l1l12.0/(3.0 * pow(l1 * l2 * l3, 1.0/3.0))\n2.0/(3.0 * l123_pow_1_3)\ncbrt_l123cbrt_l123l123 = l1 * l2 * l3; \ncbrt_l123 = cbrt(l123);\nT = \n mu/(3.0*l123)*( pow(l1/cbrt_l123,a)*(2.0*N1-N2-N3)\n + pow(l2/cbrt_l123,a)*(2.0*N2-N3-N1)\n + pow(l3/cbrt_l123,a)*(2.0*N3-N1-N2))\n +K*(l123-1.0)*(N1+N2+N3);\n// Step 0: Trim all whitespace.\nT=(mu*(pow(l1*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a*(pow(l1*l2*l3,-0.1e1/0.3e1)-l1*l2*l3*pow(l1*l2*l3,-0.4e1/0.3e1)/0.3e1)*pow(l1*l2*l3,0.1e1/0.3e1)/l1-pow(l2*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l1/0.3e1-pow(l3*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l1/0.3e1)/a+K*(l1*l2*l3-0.1e1)*l2*l3)*N1/l2/l3+(mu*(-pow(l1*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l2/0.3e1+pow(l2*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a*(pow(l1*l2*l3,-0.1e1/0.3e1)-l1*l2*l3*pow(l1*l2*l3,-0.4e1/0.3e1)/0.3e1)*pow(l1*l2*l3,0.1e1/0.3e1)/l2-pow(l3*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l2/0.3e1)/a+K*(l1*l2*l3-0.1e1)*l1*l3)*N2/l1/l3+(mu*(-pow(l1*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l3/0.3e1-pow(l2*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a/l3/0.3e1+pow(l3*pow(l1*l2*l3,-0.1e1/0.3e1),a)*a*(pow(l1*l2*l3,-0.1e1/0.3e1)-l1*l2*l3*pow(l1*l2*l3,-0.4e1/0.3e1)/0.3e1)*pow(l1*l2*l3,0.1e1/0.3e1)/l3)/a+K*(l1*l2*l3-0.1e1)*l1*l2)*N3/l1/l2;\n\n// Step 1:\n// l1*l2*l3 -> l123\n// 0.1e1 -> 1.0\n// 0.4e1 -> 4.0\n// 0.3e1 -> 3\nl123 = l1 * l2 * l3;\nT=(mu*(pow(l1*pow(l123,-1.0/3),a)*a*(pow(l123,-1.0/3)-l123*pow(l123,-4.0/3)/3)*pow(l123,1.0/3)/l1-pow(l2*pow(l123,-1.0/3),a)*a/l1/3-pow(l3*pow(l123,-1.0/3),a)*a/l1/3)/a+K*(l123-1.0)*l2*l3)*N1/l2/l3+(mu*(-pow(l1*pow(l123,-1.0/3),a)*a/l2/3+pow(l2*pow(l123,-1.0/3),a)*a*(pow(l123,-1.0/3)-l123*pow(l123,-4.0/3)/3)*pow(l123,1.0/3)/l2-pow(l3*pow(l123,-1.0/3),a)*a/l2/3)/a+K*(l123-1.0)*l1*l3)*N2/l1/l3+(mu*(-pow(l1*pow(l123,-1.0/3),a)*a/l3/3-pow(l2*pow(l123,-1.0/3),a)*a/l3/3+pow(l3*pow(l123,-1.0/3),a)*a*(pow(l123,-1.0/3)-l123*pow(l123,-4.0/3)/3)*pow(l123,1.0/3)/l3)/a+K*(l123-1.0)*l1*l2)*N3/l1/l2;\n\n// Step 2:\n// pow(l123,1.0/3) -> cbrt_l123\n// l123*pow(l123,-4.0/3) -> pow(l123,-1.0/3)\n// (pow(l123,-1.0/3)-pow(l123,-1.0/3)/3) -> 2.0/(3.0*cbrt_l123)\n// *pow(l123,-1.0/3) -> /cbrt_l123\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT=(mu*(pow(l1/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l1-pow(l2/cbrt_l123,a)*a/l1/3-pow(l3/cbrt_l123,a)*a/l1/3)/a+K*(l123-1.0)*l2*l3)*N1/l2/l3+(mu*(-pow(l1/cbrt_l123,a)*a/l2/3+pow(l2/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l2-pow(l3/cbrt_l123,a)*a/l2/3)/a+K*(l123-1.0)*l1*l3)*N2/l1/l3+(mu*(-pow(l1/cbrt_l123,a)*a/l3/3-pow(l2/cbrt_l123,a)*a/l3/3+pow(l3/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l3)/a+K*(l123-1.0)*l1*l2)*N3/l1/l2;\n\n// Step 3:\n// Whitespace is nice.\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n (mu*( pow(l1/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l1\n -pow(l2/cbrt_l123,a)*a/l1/3\n -pow(l3/cbrt_l123,a)*a/l1/3)/a\n +K*(l123-1.0)*l2*l3)*N1/l2/l3\n +(mu*(-pow(l1/cbrt_l123,a)*a/l2/3\n +pow(l2/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l2\n -pow(l3/cbrt_l123,a)*a/l2/3)/a\n +K*(l123-1.0)*l1*l3)*N2/l1/l3\n +(mu*(-pow(l1/cbrt_l123,a)*a/l3/3\n -pow(l2/cbrt_l123,a)*a/l3/3\n +pow(l3/cbrt_l123,a)*a*2.0/(3.0*cbrt_l123)*cbrt_l123/l3)/a\n +K*(l123-1.0)*l1*l2)*N3/l1/l2;\n\n// Step 4:\n// Eliminate the 'a' in (term1*a + term2*a + term3*a)/a\n// Expand (mu_term + K_term)*something to mu_term*something + K_term*something\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n (mu*( pow(l1/cbrt_l123,a)*2.0/(3.0*cbrt_l123)*cbrt_l123/l1\n -pow(l2/cbrt_l123,a)/l1/3\n -pow(l3/cbrt_l123,a)/l1/3))*N1/l2/l3\n +K*(l123-1.0)*l2*l3*N1/l2/l3\n +(mu*(-pow(l1/cbrt_l123,a)/l2/3\n +pow(l2/cbrt_l123,a)*2.0/(3.0*cbrt_l123)*cbrt_l123/l2\n -pow(l3/cbrt_l123,a)/l2/3))*N2/l1/l3\n +K*(l123-1.0)*l1*l3*N2/l1/l3\n +(mu*(-pow(l1/cbrt_l123,a)/l3/3\n -pow(l2/cbrt_l123,a)/l3/3\n +pow(l3/cbrt_l123,a)*2.0/(3.0*cbrt_l123)*cbrt_l123/l3))*N3/l1/l2\n +K*(l123-1.0)*l1*l2*N3/l1/l2;\n\n// Step 5:\n// Rearrange\n// Reduce l2*l3*N1/l2/l3 to N1 (and similar)\n// Reduce 2.0/(3.0*cbrt_l123)*cbrt_l123/l1 to 2.0/3.0/l1 (and similar)\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n (mu*( pow(l1/cbrt_l123,a)*2.0/3.0/l1\n -pow(l2/cbrt_l123,a)/l1/3\n -pow(l3/cbrt_l123,a)/l1/3))*N1/l2/l3\n +(mu*(-pow(l1/cbrt_l123,a)/l2/3\n +pow(l2/cbrt_l123,a)*2.0/3.0/l2\n -pow(l3/cbrt_l123,a)/l2/3))*N2/l1/l3\n +(mu*(-pow(l1/cbrt_l123,a)/l3/3\n -pow(l2/cbrt_l123,a)/l3/3\n +pow(l3/cbrt_l123,a)*2.0/3.0/l3))*N3/l1/l2\n +K*(l123-1.0)*N1\n +K*(l123-1.0)*N2\n +K*(l123-1.0)*N3;\n\n// Step 6:\n// Factor out mu and K*(l123-1.0)\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n mu*( ( pow(l1/cbrt_l123,a)*2.0/3.0/l1\n -pow(l2/cbrt_l123,a)/l1/3\n -pow(l3/cbrt_l123,a)/l1/3)*N1/l2/l3\n + (-pow(l1/cbrt_l123,a)/l2/3\n +pow(l2/cbrt_l123,a)*2.0/3.0/l2\n -pow(l3/cbrt_l123,a)/l2/3)*N2/l1/l3\n + (-pow(l1/cbrt_l123,a)/l3/3\n -pow(l2/cbrt_l123,a)/l3/3\n +pow(l3/cbrt_l123,a)*2.0/3.0/l3)*N3/l1/l2)\n +K*(l123-1.0)*(N1+N2+N3);\n\n// Step 7:\n// Expand\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n mu*( pow(l1/cbrt_l123,a)*2.0/3.0/l1*N1/l2/l3\n -pow(l2/cbrt_l123,a)/l1/3*N1/l2/l3\n -pow(l3/cbrt_l123,a)/l1/3*N1/l2/l3\n -pow(l1/cbrt_l123,a)/l2/3*N2/l1/l3\n +pow(l2/cbrt_l123,a)*2.0/3.0/l2*N2/l1/l3\n -pow(l3/cbrt_l123,a)/l2/3*N2/l1/l3\n -pow(l1/cbrt_l123,a)/l3/3*N3/l1/l2\n -pow(l2/cbrt_l123,a)/l3/3*N3/l1/l2\n +pow(l3/cbrt_l123,a)*2.0/3.0/l3*N3/l1/l2)\n +K*(l123-1.0)*(N1+N2+N3);\n\n// Step 8:\n// Simplify.\nl123 = l1 * l2 * l3;\ncbrt_l123 = cbrt(l123);\nT =\n mu/(3.0*l123)*( pow(l1/cbrt_l123,a)*(2.0*N1-N2-N3)\n + pow(l2/cbrt_l123,a)*(2.0*N2-N3-N1)\n + pow(l3/cbrt_l123,a)*(2.0*N3-N1-N2))\n +K*(l123-1.0)*(N1+N2+N3);\nl1l1l1l123 = l1 * l2 * l3; \ncbrt_l123_inv = 1.0 / cbrt(l123);\nnasty_expression =\n K * (l123 - 1.0) * (N1 + N2 + N3) \n - ( pow(l1 * cbrt_l123_inv, a) * (N2 + N3) \n + pow(l2 * cbrt_l123_inv, a) * (N1 + N3) \n + pow(l3 * cbrt_l123_inv, a) * (N1 + N2)) * mu / (3.0*l123);\nl1l1l1"}, {"idx": "webquery-test-7", "doc": "static variables in an inlined function", "code": "void doSomething()\n{\n static int value ;\n}\ninline void doSomething()\n{\n static int value ;\n}\nstatic void doSomething()\n{\n static int value ;\n}\ninline static void doSomething()\n{\n static int value ;\n}\n"}, {"idx": "webquery-test-8", "doc": "Is accessing data in the heap faster than from the stack?", "code": "sbrksbrksbrksbrksbrknewnewnewnewnewnewnewnewmain()main()"}, {"idx": "webquery-test-9", "doc": "When and why do I need to use cin.ignore() in C++?", "code": "std::cinstd::cinstd::cinstd::cinstd::cinstd::cinstd::cin"}, {"idx": "webquery-test-1", "doc": "Variadic template pack expansion", "code": "template<typename... Args>\nstatic void foo2(Args &&... args)\n{\n int dummy[] = { 0, ( (void) bar(std::forward<Args>(args)), 0) ... };\n}\n{ 0, ( (void) bar(std::forward<Args>(args)), 0) ... };\n | | | | |\n | | | | --- pack expand the whole thing \n | | | | \n | | --perfect forwarding --- comma operator\n | |\n | -- cast to void to ensure that regardless of bar()'s return type\n | the built-in comma operator is used rather than an overloaded one\n |\n ---ensure that the array has at least one element so that we don't try to make an\n illegal 0-length array when args is empty\n{}((void) bar(std::forward<Args>(args)), ...);\n"}, {"idx": "webquery-test-2", "doc": "How to declare an array of strings in C++?", "code": "std::vector<std::string> v = {\"Hello\", \"World\"};\n"}, {"idx": "webquery-test-3", "doc": "Difference between uint8_t, uint_fast8_t and uint_least8_t", "code": "uint_least8_tuint_least8_tunsigned intunsigned intunsigned intunsigned intuint8_tuint8_tuint8_tuint8_tuint8_t"}, {"idx": "webquery-test-4", "doc": "How can I get the class name from a C++ object?", "code": "#include <iostream>\n#define quote(x) #x\nclass one {};\nint main(){\n one A;\n std::cout<<typeid(A).name()<<\"\\t\"<< quote(A) <<\"\\n\";\n return 0;\n}\n3one A\n#std::cout<<typeid(A).name()<<\"\\t\"<< \"A\" <<\"\\n\";\nvoid foo(one B){\n std::cout<<typeid(B).name()<<\"\\t\"<< quote(B) <<\"\\n\";\n}\nint main(){\n one A;\n foo(A);\n return 0;\n}\n3one B\n#include <iostream>\n#include <cxxabi.h>\n#define quote(x) #x\ntemplate <typename foo,typename bar> class one{ };\nint main(){\n one<int,one<double, int> > A;\n int status;\n char * demangled = abi::__cxa_demangle(typeid(A).name(),0,0,&status);\n std::cout<<demangled<<\"\\t\"<< quote(A) <<\"\\n\";\n free(demangled);\n return 0;\n}\none<int, one<double, int> > A\n"}, {"idx": "webquery-test-5", "doc": "How to properly link libraries with cmake?", "code": "ADD_LIBRARY(LibsModule \n file1.cpp\n file2.cpp\n)\nLibsModuleLibsModuleLibsModuletarget_link_libraries(LibsModule -lpthread)\ntarget_link_libraries(LibsModule liblapack.a)\ntarget_link_libraries(LibsModule -L/home/user/libs/somelibpath/)\nADD_EXECUTABLE(MyProgramExecBlaBla main.cpp)\nLibsModuleLibsModuletarget_link_libraries(MyProgramExecBlaBla LibsModule)\ntexture_mappingproject (MyProgramExecBlaBla) #not sure whether this should be the same name of the executable, but I always see that \"convention\"\ncmake_minimum_required(VERSION 2.8)\n\nADD_LIBRARY(LibsModule \n file1.cpp\n file2.cpp\n)\n\ntarget_link_libraries(LibsModule -lpthread)\ntarget_link_libraries(LibsModule liblapack.a)\ntarget_link_libraries(LibsModule -L/home/user/libs/somelibpath/)\nADD_EXECUTABLE(MyProgramExecBlaBla main.cpp)\ntarget_link_libraries(MyProgramExecBlaBla LibsModule)\nfind_package"}, {"idx": "webquery-test-6", "doc": "Required and Optional Arguments Using Boost Library Program Options", "code": "po::storepo::storepo::storepo::storepo::notify(vm)po::notify(vm)po::notify(vm)po::notify(vm)po::value< -type- >( &var_name )po::value< -type- >( &var_name )"}, {"idx": "webquery-test-7", "doc": "What's the use of memset() return value?", "code": "char a[200];\nstrcpy(memset(a, 0, 200), \"bla\");\n"}, {"idx": "webquery-test-8", "doc": "C++ Object without new", "code": "CPlayer(position, attacker)\nCPlayerCPlayer newPlayer =...;\nnewPlayerCPlayer newPlayer(position, attacker);\n"}, {"idx": "webquery-test-9", "doc": "Inverting a 4x4 matrix", "code": "bool gluInvertMatrix(const double m[16], double invOut[16])\n{\n double inv[16], det;\n int i;\n\n inv[0] = m[5] * m[10] * m[15] - \n m[5] * m[11] * m[14] - \n m[9] * m[6] * m[15] + \n m[9] * m[7] * m[14] +\n m[13] * m[6] * m[11] - \n m[13] * m[7] * m[10];\n\n inv[4] = -m[4] * m[10] * m[15] + \n m[4] * m[11] * m[14] + \n m[8] * m[6] * m[15] - \n m[8] * m[7] * m[14] - \n m[12] * m[6] * m[11] + \n m[12] * m[7] * m[10];\n\n inv[8] = m[4] * m[9] * m[15] - \n m[4] * m[11] * m[13] - \n m[8] * m[5] * m[15] + \n m[8] * m[7] * m[13] + \n m[12] * m[5] * m[11] - \n m[12] * m[7] * m[9];\n\n inv[12] = -m[4] * m[9] * m[14] + \n m[4] * m[10] * m[13] +\n m[8] * m[5] * m[14] - \n m[8] * m[6] * m[13] - \n m[12] * m[5] * m[10] + \n m[12] * m[6] * m[9];\n\n inv[1] = -m[1] * m[10] * m[15] + \n m[1] * m[11] * m[14] + \n m[9] * m[2] * m[15] - \n m[9] * m[3] * m[14] - \n m[13] * m[2] * m[11] + \n m[13] * m[3] * m[10];\n\n inv[5] = m[0] * m[10] * m[15] - \n m[0] * m[11] * m[14] - \n m[8] * m[2] * m[15] + \n m[8] * m[3] * m[14] + \n m[12] * m[2] * m[11] - \n m[12] * m[3] * m[10];\n\n inv[9] = -m[0] * m[9] * m[15] + \n m[0] * m[11] * m[13] + \n m[8] * m[1] * m[15] - \n m[8] * m[3] * m[13] - \n m[12] * m[1] * m[11] + \n m[12] * m[3] * m[9];\n\n inv[13] = m[0] * m[9] * m[14] - \n m[0] * m[10] * m[13] - \n m[8] * m[1] * m[14] + \n m[8] * m[2] * m[13] + \n m[12] * m[1] * m[10] - \n m[12] * m[2] * m[9];\n\n inv[2] = m[1] * m[6] * m[15] - \n m[1] * m[7] * m[14] - \n m[5] * m[2] * m[15] + \n m[5] * m[3] * m[14] + \n m[13] * m[2] * m[7] - \n m[13] * m[3] * m[6];\n\n inv[6] = -m[0] * m[6] * m[15] + \n m[0] * m[7] * m[14] + \n m[4] * m[2] * m[15] - \n m[4] * m[3] * m[14] - \n m[12] * m[2] * m[7] + \n m[12] * m[3] * m[6];\n\n inv[10] = m[0] * m[5] * m[15] - \n m[0] * m[7] * m[13] - \n m[4] * m[1] * m[15] + \n m[4] * m[3] * m[13] + \n m[12] * m[1] * m[7] - \n m[12] * m[3] * m[5];\n\n inv[14] = -m[0] * m[5] * m[14] + \n m[0] * m[6] * m[13] + \n m[4] * m[1] * m[14] - \n m[4] * m[2] * m[13] - \n m[12] * m[1] * m[6] + \n m[12] * m[2] * m[5];\n\n inv[3] = -m[1] * m[6] * m[11] + \n m[1] * m[7] * m[10] + \n m[5] * m[2] * m[11] - \n m[5] * m[3] * m[10] - \n m[9] * m[2] * m[7] + \n m[9] * m[3] * m[6];\n\n inv[7] = m[0] * m[6] * m[11] - \n m[0] * m[7] * m[10] - \n m[4] * m[2] * m[11] + \n m[4] * m[3] * m[10] + \n m[8] * m[2] * m[7] - \n m[8] * m[3] * m[6];\n\n inv[11] = -m[0] * m[5] * m[11] + \n m[0] * m[7] * m[9] + \n m[4] * m[1] * m[11] - \n m[4] * m[3] * m[9] - \n m[8] * m[1] * m[7] + \n m[8] * m[3] * m[5];\n\n inv[15] = m[0] * m[5] * m[10] - \n m[0] * m[6] * m[9] - \n m[4] * m[1] * m[10] + \n m[4] * m[2] * m[9] + \n m[8] * m[1] * m[6] - \n m[8] * m[2] * m[5];\n\n det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];\n\n if (det == 0)\n return false;\n\n det = 1.0 / det;\n\n for (i = 0; i < 16; i++)\n invOut[i] = inv[i] * det;\n\n return true;\n}\n"}, {"idx": "webquery-test-10", "doc": "CRTP to avoid dynamic polymorphism", "code": "template <class Derived>\nstruct base {\n void foo() {\n static_cast<Derived *>(this)->foo();\n };\n};\n\nstruct my_type : base<my_type> {\n void foo(); // required to compile.\n};\n\nstruct your_type : base<your_type> {\n void foo(); // required to compile.\n};\ntemplate <class T> // T is deduced at compile-time\nvoid bar(base<T> & obj) {\n obj.foo(); // will do static dispatch\n}\n\nstruct not_derived_from_base { }; // notice, not derived from base\n\n// ...\nmy_type my_instance;\nyour_type your_instance;\nnot_derived_from_base invalid_instance;\nbar(my_instance); // will call my_instance.foo()\nbar(your_instance); // will call your_instance.foo()\nbar(invalid_instance); // compile error, cannot deduce correct overload\n"}, {"idx": "webquery-test-1", "doc": "Forward declaration with unique_ptr?", "code": "unique_ptrA::~A()A::~A()"}, {"idx": "webquery-test-2", "doc": "Using Maven for C/C++ projects", "code": "<dependency>\n <groupId>cppunit</groupId>\n <artifactId>cppunit</artifactId>\n <scope>test</scope>\n</dependency>\n"}, {"idx": "webquery-test-3", "doc": "How do I pass multiple ints into a vector at once?", "code": "std::vector<unsigned int> array;\n\n// First argument is an iterator to the element BEFORE which you will insert:\n// In this case, you will insert before the end() iterator, which means appending value\n// at the end of the vector.\narray.insert(array.end(), { 1, 2, 3, 4, 5, 6 });\n"}, {"idx": "webquery-test-4", "doc": "Is it a good idea to typedef pointers?", "code": "*"}, {"idx": "webquery-test-5", "doc": "Meaning of *& and **& in C++", "code": "void pass_by_value(int* p)\n{\n //Allocate memory for int and store the address in p\n p = new int;\n}\n\nvoid pass_by_reference(int*& p)\n{\n p = new int;\n}\n\nint main()\n{\n int* p1 = NULL;\n int* p2 = NULL;\n\n pass_by_value(p1); //p1 will still be NULL after this call\n pass_by_reference(p2); //p2 's value is changed to point to the newly allocate memory\n\n return 0;\n}\n"}, {"idx": "webquery-test-6", "doc": "Outputting Date and Time in C++ using std::chrono", "code": "<chrono><chrono><chrono><chrono><chrono><chrono>#include <chrono> // chrono::system_clock\n#include <ctime> // localtime\n#include <sstream> // stringstream\n#include <iomanip> // put_time\n#include <string> // string\n\nstd::string return_current_time_and_date()\n{\n auto now = std::chrono::system_clock::now();\n auto in_time_t = std::chrono::system_clock::to_time_t(now);\n\n std::stringstream ss;\n ss << std::put_time(std::localtime(&in_time_t), \"%Y-%m-%d %X\");\n return ss.str();\n}\nstd::localtimestd::localtime#include \"date.h\"\n#include <chrono>\n#include <string>\n#include <sstream>\n\nstd::string return_current_time_and_date() {\n auto now = std::chrono::system_clock::now();\n auto today = date::floor<days>(now);\n\n std::stringstream ss;\n ss << today << ' ' << date::make_time(now - today) << \" UTC\";\n return ss.str();\n}\nconst"}, {"idx": "webquery-test-7", "doc": "QtCreator: No valid kits found", "code": "sudo apt-get install qt5-default\nsudo apt-get install qt4-dev-tools libqt4-dev libqt4-core libqt4-gui\n"}, {"idx": "webquery-test-8", "doc": "C++ array initialization", "code": "= { 0 }boolboolboolbool myBoolArray[ARRAY_SIZE] = { 0 };\nfalsechar* myPtrArray[ARRAY_SIZE] = { 0 };\nchar *bool myBoolArray[ARRAY_SIZE] = { false };\nchar* myPtrArray[ARRAY_SIZE] = { nullptr };\n= { 0 }= { 0 }= { 0 }T myArray[ARRAY_SIZE] = {};\n{}"}, {"idx": "webquery-test-9", "doc": "What's the C++ version of Java's ArrayList", "code": "std::vector"}, {"idx": "webquery-test-1", "doc": "What is this (( ))?", "code": "printf()"}, {"idx": "webquery-test-2", "doc": "Unicode encoding for string literals in C++11", "code": "\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\x\\xu\"\"u\"\"\\u\\ustd::basic_stringstd::basic_stringstd::basic_stringstd::basic_stringstd::basic_string"}, {"idx": "webquery-test-3", "doc": "Unused parameter in c++11", "code": "int main(int, char *[])\n{\n\n return 0;\n}\nint main()\n{\n // no return implies return 0;\n}\n"}, {"idx": "webquery-test-4", "doc": "How does this program work?", "code": "%d%d%e%e%edoubledouble00 00 00 00 00 4A 93 40\n%d%d%dfloatfloatfloatfloatfloat"}, {"idx": "webquery-test-1", "doc": "What is the performance overhead of std::function?", "code": "std:functionstd:functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::functionstd::function"}, {"idx": "webquery-test-2", "doc": "C++ virtual function return type", "code": "class Base {\npublic:\n virtual ~Base() {}\n\n virtual Base* clone() const = 0;\n};\n\nclass Derived: public Base {\npublic:\n virtual Derived* clone() const {\n return new Derived(*this);\n }\n};\nBaseBaseBaseBaseBase* ptr = /* ... */\nBase* clone = ptr->clone();\nclone()clone()clone()clone()"}, {"idx": "webquery-test-3", "doc": "What would 'std:;' do in c++?", "code": "std:std:"}, {"idx": "webquery-test-4", "doc": "std::dynarray vs std::vector", "code": "std::dynarraystd::dynarraydynarraydynarraydynarraystd::dynarray<int> d(5); // can use stack memory for elements\nauto p = new std::dynarray<int>(6); // must use heap memory for elements\nstd::dynarraystd::dynarraystd::dynarray"}, {"idx": "webquery-test-5", "doc": "How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers", "code": "(-1) % 8 == -1(-1) % 8 == -1mod(-1,8)mod(-1,8)int mod(int a, int b)\n{\n if(b < 0) //you can check for b == 0 separately and do what you want\n return -mod(-a, -b); \n int ret = a % b;\n if(ret < 0)\n ret+=b;\n return ret;\n}\n"}, {"idx": "webquery-test-6", "doc": "Is signed integer overflow still undefined behavior in C++?", "code": "unsigned"}, {"idx": "webquery-test-7", "doc": "Has the new C++11 member initialization feature at declaration made initialization lists obsolete?", "code": "class A {\n public:\n A(): a(7), b(5), hash_algorithm(\"MD5\"), s(\"Constructor run\") {}\n A(int a_val) : a(a_val), b(5), hash_algorithm(\"MD5\"), s(\"Constructor run\") {}\n A(D d) : a(7), b(g(d)), hash_algorithm(\"MD5\"), s(\"Constructor run\") {}\n int a, b;\n private:\n HashingFunction hash_algorithm; // Cryptographic hash to be applied to all A instances\n std::string s; // String indicating state in object lifecycle\n};\nclass A {\n public:\n A(): a(7), b(5) {}\n A(int a_val) : a(a_val), b(5) {}\n A(D d) : a(7), b(g(d)) {}\n int a, b;\n private:\n HashingFunction hash_algorithm{\"MD5\"}; // Cryptographic hash to be applied to all A instances\n std::string s{\"Constructor run\"}; // String indicating state in object lifecycle\n};\n"}, {"idx": "webquery-test-8", "doc": "Understanding std::hardware_destructive_interference_size and std::hardware_constructive_interference_size", "code": "alignas()alignof(max_align_t)constexpr std::size_t cache_line_size() {\n#ifdef KNOWN_L1_CACHE_LINE_SIZE\n return KNOWN_L1_CACHE_LINE_SIZE;\n#else\n return std::hardware_destructive_interference_size;\n#endif\n}\nKNOWN_L1_CACHE_LINE_SIZE#include <chrono>\n#include <condition_variable>\n#include <cstddef>\n#include <functional>\n#include <future>\n#include <iostream>\n#include <random>\n#include <thread>\n#include <vector>\n\n// !!! YOU MUST UPDATE THIS TO BE ACCURATE !!!\nconstexpr std::size_t hardware_destructive_interference_size = 64;\n\n// !!! YOU MUST UPDATE THIS TO BE ACCURATE !!!\nconstexpr std::size_t hardware_constructive_interference_size = 64;\n\nconstexpr unsigned kTimingTrialsToComputeAverage = 100;\nconstexpr unsigned kInnerLoopTrials = 1000000;\n\ntypedef unsigned useless_result_t;\ntypedef double elapsed_secs_t;\n\n//////// CODE TO BE SAMPLED:\n\n// wraps an int, default alignment allows false-sharing\nstruct naive_int {\n int value;\n};\nstatic_assert(alignof(naive_int) < hardware_destructive_interference_size, \"\");\n\n// wraps an int, cache alignment prevents false-sharing\nstruct cache_int {\n alignas(hardware_destructive_interference_size) int value;\n};\nstatic_assert(alignof(cache_int) == hardware_destructive_interference_size, \"\");\n\n// wraps a pair of int, purposefully pushes them too far apart for true-sharing\nstruct bad_pair {\n int first;\n char padding[hardware_constructive_interference_size];\n int second;\n};\nstatic_assert(sizeof(bad_pair) > hardware_constructive_interference_size, \"\");\n\n// wraps a pair of int, ensures they fit nicely together for true-sharing\nstruct good_pair {\n int first;\n int second;\n};\nstatic_assert(sizeof(good_pair) <= hardware_constructive_interference_size, \"\");\n\n// accesses a specific array element many times\ntemplate <typename T, typename Latch>\nuseless_result_t sample_array_threadfunc(\n Latch& latch,\n unsigned thread_index,\n T& vec) {\n // prepare for computation\n std::random_device rd;\n std::mt19937 mt{ rd() };\n std::uniform_int_distribution<int> dist{ 0, 4096 };\n\n auto& element = vec[vec.size() / 2 + thread_index];\n\n latch.count_down_and_wait();\n\n // compute\n for (unsigned trial = 0; trial != kInnerLoopTrials; ++trial) {\n element.value = dist(mt);\n }\n\n return static_cast<useless_result_t>(element.value);\n}\n\n// accesses a pair's elements many times\ntemplate <typename T, typename Latch>\nuseless_result_t sample_pair_threadfunc(\n Latch& latch,\n unsigned thread_index,\n T& pair) {\n // prepare for computation\n std::random_device rd;\n std::mt19937 mt{ rd() };\n std::uniform_int_distribution<int> dist{ 0, 4096 };\n\n latch.count_down_and_wait();\n\n // compute\n for (unsigned trial = 0; trial != kInnerLoopTrials; ++trial) {\n pair.first = dist(mt);\n pair.second = dist(mt);\n }\n\n return static_cast<useless_result_t>(pair.first) +\n static_cast<useless_result_t>(pair.second);\n}\n\n//////// UTILITIES:\n\n// utility: allow threads to wait until everyone is ready\nclass threadlatch {\npublic:\n explicit threadlatch(const std::size_t count) :\n count_{ count }\n {}\n\n void count_down_and_wait() {\n std::unique_lock<std::mutex> lock{ mutex_ };\n if (--count_ == 0) {\n cv_.notify_all();\n }\n else {\n cv_.wait(lock, [&] { return count_ == 0; });\n }\n }\n\nprivate:\n std::mutex mutex_;\n std::condition_variable cv_;\n std::size_t count_;\n};\n\n// utility: runs a given function in N threads\nstd::tuple<useless_result_t, elapsed_secs_t> run_threads(\n const std::function<useless_result_t(threadlatch&, unsigned)>& func,\n const unsigned num_threads) {\n threadlatch latch{ num_threads + 1 };\n\n std::vector<std::future<useless_result_t>> futures;\n std::vector<std::thread> threads;\n for (unsigned thread_index = 0; thread_index != num_threads; ++thread_index) {\n std::packaged_task<useless_result_t()> task{\n std::bind(func, std::ref(latch), thread_index)\n };\n\n futures.push_back(task.get_future());\n threads.push_back(std::thread(std::move(task)));\n }\n\n const auto starttime = std::chrono::high_resolution_clock::now();\n\n latch.count_down_and_wait();\n for (auto& thread : threads) {\n thread.join();\n }\n\n const auto endtime = std::chrono::high_resolution_clock::now();\n const auto elapsed = std::chrono::duration_cast<\n std::chrono::duration<double>>(\n endtime - starttime\n ).count();\n\n useless_result_t result = 0;\n for (auto& future : futures) {\n result += future.get();\n }\n\n return std::make_tuple(result, elapsed);\n}\n\n// utility: sample the time it takes to run func on N threads\nvoid run_tests(\n const std::function<useless_result_t(threadlatch&, unsigned)>& func,\n const unsigned num_threads) {\n useless_result_t final_result = 0;\n double avgtime = 0.0;\n for (unsigned trial = 0; trial != kTimingTrialsToComputeAverage; ++trial) {\n const auto result_and_elapsed = run_threads(func, num_threads);\n const auto result = std::get<useless_result_t>(result_and_elapsed);\n const auto elapsed = std::get<elapsed_secs_t>(result_and_elapsed);\n\n final_result += result;\n avgtime = (avgtime * trial + elapsed) / (trial + 1);\n }\n\n std::cout\n << \"Average time: \" << avgtime\n << \" seconds, useless result: \" << final_result\n << std::endl;\n}\n\nint main() {\n const auto cores = std::thread::hardware_concurrency();\n std::cout << \"Hardware concurrency: \" << cores << std::endl;\n\n std::cout << \"sizeof(naive_int): \" << sizeof(naive_int) << std::endl;\n std::cout << \"alignof(naive_int): \" << alignof(naive_int) << std::endl;\n std::cout << \"sizeof(cache_int): \" << sizeof(cache_int) << std::endl;\n std::cout << \"alignof(cache_int): \" << alignof(cache_int) << std::endl;\n std::cout << \"sizeof(bad_pair): \" << sizeof(bad_pair) << std::endl;\n std::cout << \"alignof(bad_pair): \" << alignof(bad_pair) << std::endl;\n std::cout << \"sizeof(good_pair): \" << sizeof(good_pair) << std::endl;\n std::cout << \"alignof(good_pair): \" << alignof(good_pair) << std::endl;\n\n {\n std::cout << \"Running naive_int test.\" << std::endl;\n\n std::vector<naive_int> vec;\n vec.resize((1u << 28) / sizeof(naive_int)); // allocate 256 mibibytes\n\n run_tests([&](threadlatch& latch, unsigned thread_index) {\n return sample_array_threadfunc(latch, thread_index, vec);\n }, cores);\n }\n {\n std::cout << \"Running cache_int test.\" << std::endl;\n\n std::vector<cache_int> vec;\n vec.resize((1u << 28) / sizeof(cache_int)); // allocate 256 mibibytes\n\n run_tests([&](threadlatch& latch, unsigned thread_index) {\n return sample_array_threadfunc(latch, thread_index, vec);\n }, cores);\n }\n {\n std::cout << \"Running bad_pair test.\" << std::endl;\n\n bad_pair p;\n\n run_tests([&](threadlatch& latch, unsigned thread_index) {\n return sample_pair_threadfunc(latch, thread_index, p);\n }, cores);\n }\n {\n std::cout << \"Running good_pair test.\" << std::endl;\n\n good_pair p;\n\n run_tests([&](threadlatch& latch, unsigned thread_index) {\n return sample_pair_threadfunc(latch, thread_index, p);\n }, cores);\n }\n}\n"}, {"idx": "webquery-test-9", "doc": "When to use std::async vs std::threads?", "code": "std::asyncstd::asyncstd::asyncstd::asyncstd::threadstd::async"}, {"idx": "webquery-test-10", "doc": "Calling a constructor to re-initialize object", "code": "A a;\n...\na = A(); \n"}, {"idx": "webquery-test-1", "doc": "What do each memory_order mean?", "code": "memory_order_seq_cstmemory_order_seq_cstmemory_order_seq_cstmemory_order_seq_cstmemory_order_seq_cst"}, {"idx": "webquery-test-2", "doc": "C++ chrono system time in milliseconds, time operations", "code": "now.time_since_epoch()now.time_since_epoch()auto duration = now.time_since_epoch();\nauto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n"}, {"idx": "webquery-test-3", "doc": "Difference between uint32 and uint32_t", "code": "uint32_tuint32_tuint32_tuint32_tuint32_tuint32_t"}, {"idx": "webquery-test-4", "doc": "Does the C++ volatile keyword introduce a memory fence?", "code": "volatilevolatilevolatilevolatilevolatilevolatile int *foo = some_memory_mapped_device;\nwhile (*foo)\n ; // wait until *foo turns false\nvolatilevolatilevolatilevolatilevolatilevolatile"}, {"idx": "webquery-test-5", "doc": "Where are the man pages for C++?", "code": "libstdc++-6-<version>-doclibstdc++-6-<version>-doclibstdc++-6-<version>-doc"}, {"idx": "webquery-test-6", "doc": "How is void *a = &a legal?", "code": "void* a = &a;\n ^~~~~~~~~~~~~~~~~\n a declared as `void*` from here on\n&a&a&a"}, {"idx": "webquery-test-7", "doc": "Initializing member variables using the same name for constructor arguments as for the member variables allowed by the C++ standard?", "code": "Blah(std::vector<int> vec): vec(vec){}\n ^ ^ \n | |\n | this is the argument to the constructor\n this is your member data\n[Example:\nclass X {\n int a;\n int b;\n int i;\n int j;\n public:\n const int& r;\n X(int i): r(a), b(i), i(i), j(this->i) {}\n //^^^^ note this (added by Nawaz)\n};\n Blah(const std::vector<int> & vec): vec(vec) {}\n ^^^^const ^reference\n"}, {"idx": "webquery-test-8", "doc": "C++11 When clearing shared_ptr, should I use reset or set to nullptr?", "code": "foo = nullptr unique_ptr& operator=(nullptr_t) noexcept;\n unique_ptr& operator=(nullptr_t) noexcept;\n unique_ptr& operator=(nullptr_t) noexcept;\n unique_ptr& operator=(nullptr_t) noexcept;\nfoo = nullptr;\nnewstd::shared_ptr<std::string> foo(new std::string(\"foo\"));\nstd::make_shared()auto foo = std::make_shared<std::string>(\"foo\");\n"}, {"idx": "webquery-test-9", "doc": "Meaning of int (*) (int *) = 5 (or any integer value)", "code": " int (*) (int *) \n int (*) (int *) = 5;\n int (*) (int *);\n"}, {"idx": "webquery-test-10", "doc": "Why do I need std::get_temporary_buffer?", "code": "get_temporary_buffer()get_temporary_buffer()"}, {"idx": "webquery-test-11", "doc": "Fast rectangle to rectangle intersection", "code": "r2->right leftr2->right leftr2->right leftr2->right leftfunction intersectRect(r1, r2) {\n return !(r2.left > r1.right || \n r2.right < r1.left || \n r2.top > r1.bottom ||\n r2.bottom < r1.top);\n}\nvar rectA = {\n left: 10,\n top: 10,\n right: 30,\n bottom: 30\n};\n\nvar rectB = {\n left: 20,\n top: 20,\n right: 50,\n bottom: 50\n};\n\nvar rectC = {\n left: 70,\n top: 70,\n right: 90,\n bottom: 90\n};\n\nintersectRect(rectA, rectB); // returns true\nintersectRect(rectA, rectC); // returns false\n"}, {"idx": "webquery-test-1", "doc": "Is there a legitimate use for void*?", "code": "void*void*void*void*void*void*void*std::map<void*,int> score;std::map<void*,int> score;std::map<void*,int> score;std::map<void*,int> score;std::map<void*,int> score;std::map<void*,int> score;std::map<void*,int> score;memsetmemsetvoid*"}, {"idx": "webquery-test-2", "doc": "Is it good practice to make getters and setters inline?", "code": "inline"}, {"idx": "webquery-test-3", "doc": "Error: variable \"cannot be implicitly captured because no default capture mode has been specified\"", "code": "flagIdflagIdauto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),\n [&flagId](Flag& device)\n { return device.getId() == flagId; });\nauto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),\n [flagId](Flag& device)\n { return device.getId() == flagId; });\nauto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),\n [flagId](Flag& device) mutable\n { return device.getId() == flagId; });\nconstconstconst auto& tmp = flagId;\nauto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),\n [&tmp](Flag& device)\n { return device.getId() == tmp; }); //tmp is immutable\nas_constauto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),\n [&flagId = std::as_const(flagId)](Flag& device)\n { return device.getId() == flagId; });\n"}, {"idx": "webquery-test-4", "doc": "C++ Abstract Class: constructor yes or no?", "code": "init()"}, {"idx": "webquery-test-5", "doc": "How do I create a simple Qt console application in C++?", "code": "// main.cpp\n#include <QtCore>\n\nclass Task : public QObject\n{\n Q_OBJECT\npublic:\n Task(QObject *parent = 0) : QObject(parent) {}\n\npublic slots:\n void run()\n {\n // Do processing here\n\n emit finished();\n }\n\nsignals:\n void finished();\n};\n\n#include \"main.moc\"\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n\n // Task parented to the application so that it\n // will be deleted by the application.\n Task *task = new Task(&a);\n\n // This will cause the application to exit when\n // the task signals finished. \n QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));\n\n // This will run the task from the application event loop.\n QTimer::singleShot(0, task, SLOT(run()));\n\n return a.exec();\n}\n"}, {"idx": "webquery-test-6", "doc": "What are the signs of crosses initialization?", "code": "int r = x + y;rrswitch(i)\n{\ncase 1:\n {\n int r = 1;\n cout << r;\n }\n break;\ncase 2:\n {\n int r = x - y;\n cout << r;\n }\n break;\n};\n"}, {"idx": "webquery-test-7", "doc": "Max and min values in a C++ enum", "code": "enum MyPretendEnum\n{\n Apples,\n Oranges,\n Pears,\n Bananas,\n First = Apples,\n Last = Bananas\n};\nFirstFirst"}, {"idx": "webquery-test-8", "doc": "What's \"wrong\" with C++ wchar_t and wstrings? What are some alternatives to wide characters?", "code": "__STDC_ISO_10646____STDC_ISO_10646____STDC_ISO_10646__u8"}, {"idx": "webquery-test-9", "doc": "Why are references not \"const\" in C++?", "code": "int main()\n{\n boolalpha(cout);\n\n int const i = 1;\n cout << is_const<decltype(i)>::value << endl;\n\n int const* ri = &i;\n cout << is_const<decltype(ri)>::value << endl;\n}\ntrue\nfalse\nfalseconstint main()\n{\n boolalpha(cout);\n\n int const i = 1;\n cout << is_const<decltype(i)>::value << endl;\n\n int const* const ri = &i;\n cout << is_const<decltype(ri)>::value << endl;\n}\ntrue\ntrue\nconstint main()\n{\n boolalpha(cout);\n\n int const i = 1;\n cout << is_const<decltype(i)>::value << endl;\n\n int const& const ri = i; // COMPILE TIME ERROR!\n cout << is_const<decltype(ri)>::value << endl;\n}\nconstconstconstint const& const ri = i; // not allowed\nriririririridecltype()decltype()"}, {"idx": "webquery-test-10", "doc": "In CLion, header only library: file \"does not belong to any project target, code insight features might not work properly\"", "code": "incincinclude_directories(\"${PROJECT_SOURCE_DIR}/inc/\")\nadd_subdirectory(src)\nadd_executable(${EXECUTABLE_NAME} main.cpp ${SOURCE})\nMark directory asMark directory asMark directory as"}, {"idx": "webquery-test-11", "doc": "c++, std::atomic, what is std::memory_order and how to use them?", "code": "std::memory_orderstd::memory_orderstd::memory_order_seq_cststd::memory_order_seq_cststd::memory_order_seq_cststd::memory_order"}, {"idx": "webquery-test-1", "doc": "How is \"int* ptr = int()\" value initialization not illegal?", "code": "int()int()"}, {"idx": "webquery-test-2", "doc": "How to detect C++11 support of a compiler with CMake", "code": "cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)\nproject(foobar CXX)\nmessage(\"Your C++ compiler supports these C++ features:\")\nforeach(i ${CMAKE_CXX_COMPILE_FEATURES})\n message(\"${i}\")\nendforeach()\n$ cat /tmp/src/CMakeLists.txt\nproject(foobar CXX)\ncmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)\nadd_executable(prog main.cc)\nset_property(TARGET prog PROPERTY CXX_STANDARD 11)\nset_property(TARGET prog PROPERTY CXX_STANDARD_REQUIRED ON)\n$ cat /tmp/src/main.cc\nint main() {\n return 0;\n}\n$ mkdir /tmp/build\n$ cd /tmp/build\n$ cmake /tmp/src\n-- The CXX compiler identification is GNU 4.8.2\n-- Check for working CXX compiler: /usr/bin/c++\n-- Check for working CXX compiler: /usr/bin/c++ -- works\n-- Detecting CXX compiler ABI info\n-- Detecting CXX compiler ABI info - done\n-- Detecting CXX compile features\n-- Detecting CXX compile features - done\n-- Configuring done\n-- Generating done\n-- Build files have been written to: /tmp/build\n$ make VERBOSE=1 | grep main.cc | grep -- \"-c\"\n/usr/bin/c++ -std=gnu++11 -o CMakeFiles/prog.dir/main.cc.o -c /tmp/src/main.cc\n$\ncmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)\nmessage(\"Your CMake version supports these C++ features:\")\nget_property(known_features GLOBAL PROPERTY CMAKE_CXX_KNOWN_FEATURES)\nforeach(i ${known_features})\n message(\"${i}\")\nendforeach()\n#include <cstdlib>\n\nint main(int argc, char *argv[]) {\n enum class Color { Red, Orange, Yellow, Green, Blue, Violet };\n constexpr float a = 3.1415f;\n auto b = a;\n return EXIT_SUCCESS;\n}\ncmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)\nproject(foobar CXX)\nadd_executable(foobar main.cc) \nset(needed_features\n cxx_strong_enums\n cxx_constexpr\n cxx_auto_type)\ntarget_compile_features(foobar PRIVATE ${needed_features})\n \n"}, {"idx": "webquery-test-3", "doc": "What are the pointer-to-member operators ->* and .* in C++?", "code": "//we have a class\nstruct X\n{\n void f() {}\n void g() {}\n};\n\ntypedef void (X::*pointer)();\n//ok, let's take a pointer and assign f to it.\npointer somePointer = &X::f;\n//now I want to call somePointer. But for that, I need an object\nX x;\n//now I call the member function on x like this\n(x.*somePointer)(); //will call x.f()\n//now, suppose x is not an object but a pointer to object\nX* px = new X;\n//I want to call the memfun pointer on px. I use ->*\n(px ->* somePointer)(); //will call px->f();\nx.somePointer()x.somePointer()"}, {"idx": "webquery-test-4", "doc": "Getting first value from map in C++", "code": "*(myMap.begin())myMap.begin()->firstmyMap.begin()->first"}, {"idx": "webquery-test-5", "doc": "Are parentheses around the result significant in a return statement?", "code": "int var1 = 42;\ndecltype(auto) func1() { return var1; } // return type is int, same as decltype(var1)\ndecltype(auto) func1() { return(var1); } // return type is int&, same as decltype((var1))\nfunc1func1func1func1autodecltypedecltype(auto)int var1 = 42;\ndecltype(auto) func1() { return var1; } // return type is int, same as decltype(var1)\ndecltype(auto) func1() { return(var1); } // return type is int&, same as decltype((var1))\ndecltype(auto)decltype(auto)decltype(auto)decltype(auto)decltype(auto)decltype(auto)decltype(auto)int&int&"}, {"idx": "webquery-test-6", "doc": "What is the <iosfwd> header?", "code": "#include// foo.h\n#include <iosfwd>\n\nvoid sucker(std::iostream& is);\n// foo.cc\n#include <iostream>\n\nvoid sucker(std::iostream& is) {\n is >> somevar;\n}\n"}, {"idx": "webquery-test-7", "doc": "Copying std::vector: prefer assignment or std::copy?", "code": "v2 = v1std::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copystd::copy"}, {"idx": "webquery-test-8", "doc": "Is it a good practice to always use smart pointers?", "code": "C++void notowner(const std::string& name)\n{\n Class* pointer(0);\n if (name == \"cat\")\n pointer = getCat();\n else if (name == \"dog\")\n pointer = getDog();\n\n if (pointer) doSomething(*pointer);\n}\ndeletenewstd::auto_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrscoped_ptrshared_ptrnewnewnewstd::bad_allocstd::bad_allocstd::bad_allocstd::bad_alloc// For the sake of short code, avoid in real code ;)\nusing namespace boost;\n\n// Example classes\n// Yes, clone returns a raw pointer...\n// it puts the burden on the caller as for how to wrap it\n// It is to obey the `Cloneable` concept as described in \n// the Boost Pointer Container library linked above\nstruct Cloneable\n{\n virtual ~Cloneable() {}\n virtual Cloneable* clone() const = 0;\n};\n\nstruct Derived: Cloneable\n{\n virtual Derived* clone() const { new Derived(*this); }\n};\n\nvoid scoped()\n{\n scoped_ptr<Cloneable> c(new Derived);\n} // memory freed here\n\n// illustration of the moved semantics\nunique_ptr<Cloneable> unique()\n{\n return unique_ptr<Cloneable>(new Derived);\n}\n\nvoid shared()\n{\n shared_ptr<Cloneable> n1(new Derived);\n weak_ptr<Cloneable> w = n1;\n\n {\n shared_ptr<Cloneable> n2 = n1; // copy\n\n n1.reset();\n\n assert(n1.get() == 0);\n assert(n2.get() != 0);\n assert(!w.expired() && w.get() != 0);\n } // n2 goes out of scope, the memory is released\n\n assert(w.expired()); // no object any longer\n}\n\nvoid container()\n{\n ptr_vector<Cloneable> vec;\n vec.push_back(new Derived);\n vec.push_back(new Derived);\n\n vec.push_back(\n vec.front().clone() // Interesting semantic, it is dereferenced!\n );\n} // when vec goes out of scope, it clears up everything ;)\n"}, {"idx": "webquery-test-9", "doc": "C++11 make_pair with specified template parameters doesn't compile", "code": "std::make_pairstd::make_pairstd::make_pairstd::make_pairstd::make_pairstd::make_pairtemplate <typename T, typename U>\n[return type] make_pair(T&& argT, U&& argU);\nstd::make_pair[return type] make_pair(std::string&& argT, int&& argU);\n77TTTTTAAAmake_pair(s, 7)\nsssssssssss777777"}, {"idx": "webquery-test-10", "doc": "Why don't the official Qt examples and tutorials use smart pointers?", "code": "deleteLaterQObjectQObjectQObject"}, {"idx": "webquery-test-1", "doc": "When to Overload the Comma Operator?", "code": "enum Place {new_york, washington, ...};\n\npair<Place, Place> operator , (Place p1, Place p2)\n{\n return make_pair(p1, p2);\n}\n\n\nmap< pair<Place, Place>, double> distance;\n\ndistance[new_york, washington] = 100;\n"}, {"idx": "webquery-test-2", "doc": "Is x += a quicker than x = x + a?", "code": "intintintintf*f() += a;\nf*f() = *f() + a;\nffoperator+operator+operator+operator+x.operator+=(a);\nx = x + aauto TEMP(x.operator+(a));\nx.operator=(TEMP);\n+="}, {"idx": "webquery-test-3", "doc": "How can I use std::maps with user-defined types as key?", "code": "operator<operator<struct Class1Compare\n{\n bool operator() (const Class1& lhs, const Class1& rhs) const\n {\n return lhs.id < rhs.id;\n }\n};\n\nstd::map<Class1, int, Class1Compare> c2int;\nstd::mapstd::mapstd::mapstd::mapstd::lessnamespace std\n{\n template<> struct less<Class1>\n {\n bool operator() (const Class1& lhs, const Class1& rhs) const\n {\n return lhs.id < rhs.id;\n }\n };\n}\nstd::mapstd::map"}, {"idx": "webquery-test-4", "doc": "C++ printing boolean, what is displayed?", "code": "boolalphaboolalphaboolalphaboolalphaboolalphastd::boolalpha#include <iostream>\n#include <iomanip>\n\nint main() {\n std::cout<<false<<\"\\n\";\n std::cout << std::boolalpha; \n std::cout<<false<<\"\\n\";\n return 0;\n}\n0\nfalse\nboolalphaboolalphaboolalphaboolalphaboolalpha#include <iostream>\n#include <iomanip>\n#include <locale>\n\nint main() {\n std::cout.imbue(std::locale(\"fr\"));\n\n std::cout << false << \"\\n\";\n std::cout << std::boolalpha;\n std::cout << false << \"\\n\";\n return 0;\n}\nfauxfauxfauxnumpunctnumpunct#include <array>\n#include <string>\n#include <locale>\n#include <ios>\n#include <iostream>\n\nclass my_fr : public std::numpunct< char > {\nprotected:\n char do_decimal_point() const { return ','; }\n char do_thousands_sep() const { return '.'; }\n std::string do_grouping() const { return \"\\3\"; }\n std::string do_truename() const { return \"vrai\"; }\n std::string do_falsename() const { return \"faux\"; }\n};\n\nint main() {\n std::cout.imbue(std::locale(std::locale(), new my_fr));\n\n std::cout << false << \"\\n\";\n std::cout << std::boolalpha;\n std::cout << false << \"\\n\";\n return 0;\n}\n0\nfaux\n"}, {"idx": "webquery-test-5", "doc": "What is the role of glBindVertexArrays vs glBindBuffer and what is their relationship?", "code": "GLuint buffer;\n\n// Generate a name for a new buffer.\n// e.g. buffer = 2\nglGenBuffers(1, &buffer);\n\n// Make the new buffer active, creating it if necessary.\n// Kind of like:\n// if (opengl->buffers[buffer] == null)\n// opengl->buffers[buffer] = new Buffer()\n// opengl->current_array_buffer = opengl->buffers[buffer]\nglBindBuffer(GL_ARRAY_BUFFER, buffer);\n\n// Upload a bunch of data into the active array buffer\n// Kind of like:\n// opengl->current_array_buffer->data = new byte[sizeof(points)]\n// memcpy(opengl->current_array_buffer->data, points, sizeof(points))\nglBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);\nGLuint array;\n// Generate a name for a new array.\nglGenVertexArrays(1, &array);\n// Make the new array active, creating it if necessary.\nglBindVertexArray(array);\n\n// Make the buffer the active array buffer.\nglBindBuffer(GL_ARRAY_BUFFER, buffer);\n// Attach the active buffer to the active array,\n// as an array of vectors with 4 floats each.\n// Kind of like:\n// opengl->current_vertex_array->attributes[attr] = {\n// type = GL_FLOAT,\n// size = 4,\n// data = opengl->current_array_buffer\n// }\nglVertexAttribPointer(attr, 4, GL_FLOAT, GL_FALSE, 0, 0);\n// Enable the vertex attribute\nglEnableVertexAttribArray(attr);\nglVertexAttribPointer()glVertexAttribPointer()glVertexPointer()glVertexPointer()GLuint array;\n// Generate a name for a new array array.\nglGenVertexArrays(1, &array);\n// Make the new array active, creating it if necessary.\nglBindVertexArray(array);\n\n// Enable my attributes\nglEnableVertexAttribArray(loc_attrib);\nglEnableVertexAttribArray(normal_attrib);\nglEnableVertexAttribArray(texcoord_attrib);\n// Set up the formats for my attributes\nglVertexAttribFormat(loc_attrib, 3, GL_FLOAT, GL_FALSE, 0);\nglVertexAttribFormat(normal_attrib, 3, GL_FLOAT, GL_FALSE, 12);\nglVertexAttribFormat(texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 24);\n// Make my attributes all use binding 0\nglVertexAttribBinding(loc_attrib, 0);\nglVertexAttribBinding(normal_attrib, 0);\nglVertexAttribBinding(texcoord_attrib, 0);\n\n// Quickly bind all attributes to use \"buffer\"\n// This replaces several calls to glVertexAttribPointer()\n// Note: you don't need to bind the buffer first! Nice!\nglBindVertexBuffer(0, buffer, 0, 32);\n\n// Quickly bind all attributes to use \"buffer2\"\nglBindVertexBuffer(0, buffer2, 0, 32);\nglBindBuffer()glBindBuffer()GLuint array;\n// Generate a name for the array and create it.\n// Note that glGenVertexArrays() won't work here.\nglCreateVertexArrays(1, &array);\n// Instead of binding it, we pass it to the functions below.\n\n// Enable my attributes\nglEnableVertexArrayAttrib(array, loc_attrib);\nglEnableVertexArrayAttrib(array, normal_attrib);\nglEnableVertexArrayAttrib(array, texcoord_attrib);\n// Set up the formats for my attributes\nglVertexArrayAttribFormat(array, loc_attrib, 3, GL_FLOAT, GL_FALSE, 0);\nglVertexArrayAttribFormat(array, normal_attrib, 3, GL_FLOAT, GL_FALSE, 12);\nglVertexArrayAttribFormat(array, texcoord_attrib, 2, GL_FLOAT, GL_FALSE, 24);\n// Make my attributes all use binding 0\nglVertexArrayAttribBinding(array, loc_attrib, 0);\nglVertexArrayAttribBinding(array, normal_attrib, 0);\nglVertexArrayAttribBinding(array, texcoord_attrib, 0);\n\n// Quickly bind all attributes to use \"buffer\"\nglVertexArrayVertexBuffer(array, 0, buffer, 0, 32);\n\n// Quickly bind all attributes to use \"buffer2\"\nglVertexArrayVertexBuffer(array, 0, buffer2, 0, 32);\n\n// You still have to bind the array to draw.\nglBindVertexArray(array);\nglDrawArrays(...);\nglCreateBuffer()glCreateBuffer()// This defines part of a \"vertex array\", sort of\nVkVertexInputAttributeDescription attrib[3];\nattrib[0].location = 0; // Feed data into shader input #0\nattrib[0].binding = 0; // Get data from buffer bound to slot #0\nattrib[0].format = VK_FORMAT_R32G32B32_SFLOAT;\nattrib[0].offset = 0;\n// repeat for attrib[1], attrib[2]\n"}, {"idx": "webquery-test-6", "doc": "How to enable core dump in my Linux C++ program", "code": "ulimit -culimit -culimit -culimit -c"}, {"idx": "webquery-test-7", "doc": "more modern way of looping through C++ arrays", "code": "sizeofsizeofsizeoffor( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )\nfor(const string &text : texts)\n cout << \"value of text: \" << text << endl;\nstd::arraystd::array"}, {"idx": "webquery-test-1", "doc": "ULL suffix on a numeric literal", "code": "gcclong long intlong long intlong long intlong long int"}, {"idx": "webquery-test-2", "doc": "How to Add Linux Executable Files to .gitignore?", "code": "*\n!*.c\n!Makefile\n"}, {"idx": "webquery-test-3", "doc": "A() = A() - why does it compile?", "code": "A().operator=(A());\n"}, {"idx": "webquery-test-4", "doc": "How to configure CLion IDE for Qt Framework?", "code": "cmake_minimum_required(VERSION 3.5)\nproject(myqtproject)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\n\nset(SOURCE_FILES main.cpp)\nfind_package(Qt5Widgets REQUIRED) <-- this line\n\nadd_executable(myqtproject ${SOURCE_FILES})\n\ntarget_link_libraries(myqtproject Qt5::Widgets) <-- this line\ncmake-DCMAKE_PREFIX_PATH=/Users/edouard/Qt/5.7/clang_64/lib/cmake\nmain.cpp#include <QApplication>\n#include <QDebug>\n\nusing namespace std;\n\nint main() {\n qDebug() << QT_VERSION_STR;\n return 1;\n}\n/Users/edouard/Library/Caches/CLion2016.2/cmake/generated/myqtproject-89a4132/89a4132/Debug/untitled\n5.7.0\n\nProcess finished with exit code 1\nfind_package(Qt5Sql REQUIRED)\nfind_packagetarget_link_libraries(myqtproject Qt5::Widgets Qt5::Sql)\n"}, {"idx": "webquery-test-5", "doc": "How to create a vector of user defined size but with no predefined values?", "code": "// create a vector with 20 integer elements\nstd::vector<int> arr(20);\n\nfor(int x = 0; x < 20; ++x)\n arr[x] = x;\n"}, {"idx": "webquery-test-6", "doc": "Inline version of a function returns different value than non-inline version", "code": "-O1-O1printfinline#include <cmath>\n#include <iostream>\n\nbool is_cube(double r)\n{\n return floor(cbrt(r)) == cbrt(r);\n}\n\u00a0\nbool inline is_cube_inline(double r)\n{\n return floor(cbrt(r)) == cbrt(r);\n}\n\nint main()\n{\n double value;\n std::cin >> value;\n std::cout << (floor(cbrt(value)) == cbrt(value)) << std::endl; // false\n std::cout << (is_cube(value)) << std::endl; // false\n std::cout << (is_cube_inline(value)) << std::endl; // false\n}\n"}, {"idx": "webquery-test-7", "doc": "trivial vs. standard layout vs. POD", "code": "new Tnew Tnew Tstruct N { // neither trivial nor standard-layout\n int i;\n int j;\n virtual ~N();\n};\n\nstruct T { // trivial but not standard-layout\n int i;\nprivate:\n int j;\n};\n\nstruct SL { // standard-layout but not trivial\n int i;\n int j;\n ~SL();\n};\n\nstruct POD { // both trivial and standard-layout\n int i;\n int j;\n};\nPOD"}, {"idx": "webquery-test-8", "doc": "Undefined behavior and sequence points reloaded", "code": "i.operator+=(i.operator ++());\ni.operator ++()i.operator ++()"}, {"idx": "webquery-test-9", "doc": "How do stackless coroutines differ from stackful coroutines?", "code": "template<class Visitor>\nvoid f(Visitor& v);\nasymmetric_coroutine<T>::pull_type pull_from([](asymmetric_coroutine<T>::push_type& yield)\n{\n f(yield);\n});\ngenerator<T> pull_from()\n{\n // yield can only be used here, cannot pass to f\n f(???);\n}\nauto f() CO2_RET(co2::task<>, ())\n{\n int a = 1; // not ok\n CO2_AWAIT(co2::suspend_always{});\n {\n int b = 2; // ok\n doSomething(b);\n }\n CO2_AWAIT(co2::suspend_always{});\n int c = 3; // ok\n doSomething(c);\n} CO2_END\nawait"}, {"idx": "webquery-test-1", "doc": "Program behaving strangely on online IDEs", "code": "-faggressive-loop-optimizationsiii"}, {"idx": "webquery-test-2", "doc": "What is the size of void?", "code": "voidvoid n;\nsizeof(void)$ echo 'int main() { printf(\"%d\", sizeof(void)); }' | gcc -xc -w - && ./a.out \n1\n$ echo 'int main() { printf(\"%d\", sizeof(void)); }' | gcc -xc++ -w - && ./a.out \n<stdin>: In function 'int main()':\n<stdin>:1: error: invalid application of 'sizeof' to a void type\n<stdin>:1: error: 'printf' was not declared in this scope\n"}, {"idx": "webquery-test-3", "doc": "Is using #pragma warning push/pop the right way to temporarily alter warning level?", "code": "#if defined(__clang__)\n# pragma clang diagnostic push\n#endif\n\n#if defined(_MSC_VER)\n# pragma warning(push)\n#endif\n\n#if defined(YOUR_FAVORITE_COMPILER)\n# pragma your compiler push warning\n#endif\n#if defined(__clang__)\n# pragma clang diagnostic pop\n#endif\n\n#if defined(_MSC_VER)\n# pragma warning(pop)\n#endif\n#if defined(__clang__)\n# pragma clang diagnostic ignored \"-Wunused-parameter\"\n# pragma clang diagnostic ignored \"-Wunused-variable\"\n# if __has_warning(\"-Wnew-special-warning\")\n# pragma clang diagnostic ignored \"-Wnew-special-warning\"\n# endif\n#endif\n\n#if defined(_MSC_VER)\n# pragma warning(disable: 4100) // unreferenced formal parameter\n# if _MSC_VER > _MSC_SOME_VERSION\n# pragma warning(disable: xxxx) // disable one more for special version\n# endif\n#endif\n// This code reports warnings\n// ...\n#include <ignore_compiler_warning/push>\n#include <ignore_compiler_warning/warning_type_1>\n#include <ignore_compiler_warning/warning_type_2>\n#include <ignore_compiler_warning/warning_type_3>\n// This code ignores warnings type_{1,2,3}\n// ...\n#include <ignore_compiler_warning/pop>\n// Back to reporting warnings\n// ...\n"}, {"idx": "webquery-test-4", "doc": "Error: invalid operands of types \u2018const char [35]\u2019 and \u2018const char [2]\u2019 to binary \u2018operator+\u2019", "code": "std::string str = \"Hello \" + \"world\"; // bad!\noperator +operator +operator +operator +std::string str = \"Hello \" + std::string(\"world\"); // ok\noperator +operator +operator +std::string str = \"Hello \" + \"there \" + std::string(\"world\"); // no good!\n+++std::string str = std::string(\"Hello \") + \"there \" + \"world\"; // ok\nstd::stringstd::stringstd::string((std::string(\"Hello \") + \"there \") + \"world\");\n((string + char*) + char*)\nstring operator+(string, char*)((string) + char*)\n((char* + char*) + string)\nchar*std::string"}, {"idx": "webquery-test-5", "doc": "Is using an unsigned rather than signed int more likely to cause bugs? Why?", "code": "unsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedunsignedfor (size_t i = 0; i < v.size() - 1; i++) { // do something }\nv.size() - 1 == a giant numberfor (size_t i = 0; i + 1 < v.size(); i++) { // do something }\nsize_twhile (index-- > 0)while (index-- > 0)uint32_tuint32_tuint32_tuint32_tuint32_tuint32_tuint32_tuint32_tuint32_tuint32_tuint32_tsize_t"}, {"idx": "webquery-test-6", "doc": "What is the meaning of a const at end of a member function?", "code": "*this*thisthisthisthisthisthisthisthisthisthisthisconstconstconstconstconstconst"}, {"idx": "webquery-test-7", "doc": "C++ vector's insert & push_back difference", "code": "push_backpush_backpush_backpush_backpush_backpush_backpush_back"}, {"idx": "webquery-test-8", "doc": "Why are bitwise shifts (<< and >>) used for cout and cin?", "code": "cout=a=bcout=a=bcout=a=bcout=a=bcout=a=bcout=a=bcout=a=b"}, {"idx": "webquery-test-1", "doc": "`std::variant` vs. inheritance vs. other ways (performance)", "code": "std::visitstd::vector<Base*> runtime_poly_;//risk of fragmentation\nstd::vector<my_var_type> cp_time_poly_;//no fragmentation (but padding 'risk')\nstd::variant"}, {"idx": "webquery-test-2", "doc": "Use of min and max functions in C++", "code": "fminfminstd::minstd::minstd::minstd::minstd::min"}, {"idx": "webquery-test-3", "doc": "Moving elements from std::vector to another one", "code": "std::make_move_iteratorstd::make_move_iteratorv2.insert(v2.end(), std::make_move_iterator(v1.begin() + 7), \n std::make_move_iterator(v1.end()));\nv1v1v1.erase(v1.begin() + 7, v1.end());\n"}, {"idx": "webquery-test-4", "doc": "C++ style cast from unsigned char * to const char *", "code": "char *char *char *const unsigned char*const unsigned char*const unsigned char*const unsigned char*const unsigned char*const unsigned char*"}, {"idx": "webquery-test-5", "doc": "Does the size of an int depend on the compiler and/or processor?", "code": "intint"}, {"idx": "webquery-test-6", "doc": "How to check if a std::string is set or not?", "code": "empty()std::string s;\n\nif (s.empty())\n // nothing in s\n"}, {"idx": "webquery-test-1", "doc": "How to forward declare a class which is in a namespace", "code": "aanamespace ns1\n{\n class a;\n}\nnamespace ns1\n{\n namespace ns2\n {\n //....\n namespace nsN\n {\n class a;\n }\n //.... \n }\n}\naa"}, {"idx": "webquery-test-2", "doc": "What's the C++ suffix for long double literals?", "code": "floating constantfloating constant"}, {"idx": "webquery-test-3", "doc": "C++ union in C#", "code": "[StructLayout(LayoutKind.Explicit)] \npublic struct SampleUnion\n{\n [FieldOffset(0)] public float bar;\n [FieldOffset(4)] public int killroy;\n [FieldOffset(4)] public float fubar;\n}\n"}, {"idx": "webquery-test-4", "doc": "C++11: Correct std::array initialization?", "code": "std::arraytemplate<typename T, std::size_t N>\nstruct array {\n T __array_impl[N];\n};\n{}"}, {"idx": "webquery-test-5", "doc": "How do I deal with \"signed/unsigned mismatch\" warnings (C4018)?", "code": "things.size()things.size()things.size()things.size()for (size_t i = 0; i < things.size(); ++i) { /**/ }\nfor (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }\n"}, {"idx": "webquery-test-6", "doc": "C++ Return value, reference, const reference", "code": "(v1 += v2) = v3;\nv1 += v2v1v1v1 = (v2 += v3);\n"}, {"idx": "webquery-test-7", "doc": "When I `throw` something, where is it stored in memory?", "code": "g++ 4.4.3g++ 4.4.3g++ 4.4.3std::bad_allocstd::bad_alloc__cxa_allocate_exceptionextern \"C\" void *\n__cxxabiv1::__cxa_allocate_exception(std::size_t thrown_size) throw()\n{\n void *ret;\n\n thrown_size += sizeof (__cxa_refcounted_exception);\n ret = malloc (thrown_size);\n\n if (! ret)\n {\n __gnu_cxx::__scoped_lock sentry(emergency_mutex);\n\n bitmask_type used = emergency_used;\n unsigned int which = 0;\n\n if (thrown_size > EMERGENCY_OBJ_SIZE)\n goto failed;\n while (used & 1)\n {\n used >>= 1;\n if (++which >= EMERGENCY_OBJ_COUNT)\n goto failed;\n }\n\n emergency_used |= (bitmask_type)1 << which;\n ret = &emergency_buffer[which][0];\n\n failed:;\n\n if (!ret)\n std::terminate ();\n }\n\n // We have an uncaught exception as soon as we allocate memory. This\n // yields uncaught_exception() true during the copy-constructor that\n // initializes the exception object. See Issue 475.\n __cxa_eh_globals *globals = __cxa_get_globals ();\n globals->uncaughtExceptions += 1;\n\n memset (ret, 0, sizeof (__cxa_refcounted_exception));\n\n return (void *)((char *)ret + sizeof (__cxa_refcounted_exception));\n}\n"}, {"idx": "webquery-test-8", "doc": "C++11 auto: what if it gets a constant reference?", "code": "auto a1 = i;\nauto a2 = ci;\nauto a3 = *pci;\nauto a4 = pcs->i;\ntemplate<typename T>\nvoid f(T& p);\n\nint i;\nconst int ci = 0;\nconst int *pci = &i;\n\nf(i); // as before, calls f<int>, i.e., T is int\nf(ci); // now calls f<const int>, i.e., T is const int\nf(*pci); // also calls f<const int>, i.e., T is const int\nauto& a1 = i; // a1 is of type int&\nauto& a2 = ci; // a2 is of type const int&\nauto& a3 = *pci; // a3 is also of type const int&\nauto& a4 = pcs->i; // a4 is of type const int&, too\nauto& my_foo2 = GetFoo();\nconstconstautoautoconst Foo my_foo = GetFoo();\nmy_foomy_foo"}, {"idx": "webquery-test-1", "doc": "How to typedef a template class?", "code": "template<typename T>\nusing MyVector = std::vector<T, MyCustomAllocator<T>>;\nMyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>>\n"}, {"idx": "webquery-test-2", "doc": "vector or map, which one to use?", "code": "map<A, B>map<A, B>hash_maphash_maphash_maphash_map"}, {"idx": "webquery-test-3", "doc": "Defining a variable in the condition part of an if-statement?", "code": "if (int x = f()) {\n int x; // ill-formed, redeclaration of x\n}\nelse {\n int x; // ill-formed, redeclaration of x\n}\n"}, {"idx": "webquery-test-4", "doc": "How to check whether file exists in Qt in c++", "code": "QFileInfo#include <QFileInfo>\n#includebool fileExists(QString path) {\n QFileInfo check_file(path);\n // check if file exists and if yes: Is it really a file and no directory?\n if (check_file.exists() && check_file.isFile()) {\n return true;\n } else {\n return false;\n }\n}\nexists()exists()exists()#include <QFileInfo>\n\nbool fileExists(QString path) {\n QFileInfo check_file(path);\n // check if path exists and if yes: Is it really a file and no directory?\n return check_file.exists() && check_file.isFile();\n}\nexistsexistsexists#include <QFileInfo>\n\n// check if path exists and if yes: Is it a file and no directory?\nbool fileExists = QFileInfo::exists(path) && QFileInfo(path).isFile();\n"}, {"idx": "webquery-test-5", "doc": "Why can't I define a function inside another function?", "code": "one1993// This is legal, but why would I want this?\nint two(int bar);\n3.4.1namespace NS {\n class T { };\n void f(T);\n void g(T, int);\n}\n\nNS::T parm;\nvoid g(NS::T, float);\n\nint main() {\n f(parm); // OK: calls NS::f\n extern void g(NS::T, float);\n g(parm, 1); // OK: calls g(NS::T, float)\n}\n"}, {"idx": "webquery-test-6", "doc": "Does 'auto' type assignments of a pointer in c++11 require '*'?", "code": "auto newvar1 = myvector;\n\n// vs:\nauto *newvar2 = myvector;\nstd::vector<MyClass>std::vector<MyClass>std::vector<MyClass>std::vector<MyClass>std::vector<MyClass>autoautoautoauto newvar1 = myvector, newvar2 = something;\nnewvar2auto *newvar1 = myvector, newvar2 = something;\nnewvar2newvar2autoautoautoautoautoautoautoauto"}, {"idx": "webquery-test-7", "doc": "Fast textfile reading in c++", "code": "#include <boost/iostreams/device/mapped_file.hpp> // for mmap\n#include <algorithm> // for std::find\n#include <iostream> // for std::cout\n#include <cstring>\n\nint main()\n{\n boost::iostreams::mapped_file mmap(\"input.txt\", boost::iostreams::mapped_file::readonly);\n auto f = mmap.const_data();\n auto l = f + mmap.size();\n\n uintmax_t m_numLines = 0;\n while (f && f!=l)\n if ((f = static_cast<const char*>(memchr(f, '\\n', l-f))))\n m_numLines++, f++;\n\n std::cout << \"m_numLines = \" << m_numLines << \"\\n\";\n}\nmmap#include <algorithm>\n#include <iostream>\n#include <cstring>\n\n// for mmap:\n#include <sys/mman.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n\nconst char* map_file(const char* fname, size_t& length);\n\nint main()\n{\n size_t length;\n auto f = map_file(\"test.cpp\", length);\n auto l = f + length;\n\n uintmax_t m_numLines = 0;\n while (f && f!=l)\n if ((f = static_cast<const char*>(memchr(f, '\\n', l-f))))\n m_numLines++, f++;\n\n std::cout << \"m_numLines = \" << m_numLines << \"\\n\";\n}\n\nvoid handle_error(const char* msg) {\n perror(msg); \n exit(255);\n}\n\nconst char* map_file(const char* fname, size_t& length)\n{\n int fd = open(fname, O_RDONLY);\n if (fd == -1)\n handle_error(\"open\");\n\n // obtain file size\n struct stat sb;\n if (fstat(fd, &sb) == -1)\n handle_error(\"fstat\");\n\n length = sb.st_size;\n\n const char* addr = static_cast<const char*>(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0u));\n if (addr == MAP_FAILED)\n handle_error(\"mmap\");\n\n // TODO close fd at some point in time, call munmap(...)\n return addr;\n}\nwcwcstatic uintmax_t wc(char const *fname)\n{\n static const auto BUFFER_SIZE = 16*1024;\n int fd = open(fname, O_RDONLY);\n if(fd == -1)\n handle_error(\"open\");\n\n /* Advise the kernel of our access pattern. */\n posix_fadvise(fd, 0, 0, 1); // FDADVICE_SEQUENTIAL\n\n char buf[BUFFER_SIZE + 1];\n uintmax_t lines = 0;\n\n while(size_t bytes_read = read(fd, buf, BUFFER_SIZE))\n {\n if(bytes_read == (size_t)-1)\n handle_error(\"read failed\");\n if (!bytes_read)\n break;\n\n for(char *p = buf; (p = (char*) memchr(p, '\\n', (buf + bytes_read) - p)); ++p)\n ++lines;\n }\n\n return lines;\n}\n"}, {"idx": "webquery-test-8", "doc": "What is the difference between std::transform and std::for_each?", "code": "std::transformstd::transformstd::transformstd::transformstd::transformstd::vector<std::string> names = {\"hi\", \"test\", \"foo\"};\nstd::vector<std::size_t> name_sizes;\n\nstd::transform(names.begin(), names.end(), std::back_inserter(name_sizes), [](const std::string& name) { return name.size();});\nstd::for_eachstd::for_eachstd::for_eachstd::for_each(name_sizes.begin(), name_sizes.end(), [](std::size_t name_size) {\n std::cout << name_size << std::endl;\n});\nforfor (std::size_t name_size: name_sizes) {\n std::cout << name_size << std::endl;\n}\n"}, {"idx": "webquery-test-9", "doc": "Accessing certain pixel RGB value in openCV", "code": "cv::Mat image = ...do some stuff...;\nimage.at<cv::Vec3b>(y,x);image.at<cv::Vec3b>(y,x);image.at<cv::Vec3b>(y,x)[0] = newval[0];\nimage.at<cv::Vec3b>(y,x)[1] = newval[1];\nimage.at<cv::Vec3b>(y,x)[2] = newval[2];\n"}, {"idx": "webquery-test-10", "doc": "const& , & and && specifiers for member functions in C++", "code": "const&const A a = A();\n*a;\n&A a;\n*a;\n&&*A();\n"}, {"idx": "webquery-test-11", "doc": "Nodejs: What does `process.binding` mean?", "code": "timer_wraptimer_wraptimer_wrap"}, {"idx": "webquery-test-1", "doc": "GNU autotools: Debug/Release targets?", "code": "$ mkdir debug\n$ mkdir release\n$ cd debug && /path/to/configure --prefix=/dbg \\\n CPPFLAGS=-DDEBUG CFLAGS=\"-g -O0\" && make && make install\n$ cd ../release && /path/to/configure CPPFLAGS=-DNDEBUG && make && make install\necho 'CPPFLAGS=-DDEBUG CFLAGS=\"-g -O0\"' >> /dbg/share/config.site\nmake && make installmake && make installmake && make installmake && make installmake && make installmake && make install-DMAKE_IT_A_DEBUG-DMAKE_IT_A_DEBUG-DMAKE_IT_A_DEBUG-DMAKE_IT_A_DEBUG-DMAKE_IT_A_DEBUG-DMAKE_IT_A_DEBUG"}, {"idx": "webquery-test-2", "doc": "Vector erase iterator", "code": "res.erase(it)res.erase(it)++it++it.end().end().end() while (it != res.end()) {\n it = res.erase(it); \n }\nres.clear()for ( ; it != res.end(); ) {\n if (condition) {\n it = res.erase(it);\n } else {\n ++it;\n }\n}\n"}, {"idx": "webquery-test-3", "doc": "Why would you use 'extern \"C++\"'?", "code": "extern \"C\" {\n #include \"foo.h\"\n}\n void f_plain(const char *);\n extern \"C++\" void f_fancy(const std::string &);\n"}, {"idx": "webquery-test-4", "doc": "How does one downcast a std::shared_ptr?", "code": "if (ptr->IsChildOne())\n{\n SomeClientExpectingAChildOne(std::static_pointer_cast<ChildOne>(ptr));\n}\n"}, {"idx": "webquery-test-5", "doc": "What's the Use of '\\r' escape sequence?", "code": "\\r\\ro worldo worldo world\\r\\r#include <stdio.h>\n#include <unistd.h>\n\nint main()\n{\n char chars[] = {'-', '\\\\', '|', '/'};\n unsigned int i;\n\n for (i = 0; ; ++i) {\n printf(\"%c\\r\", chars[i % sizeof(chars)]);\n fflush(stdout);\n usleep(200000);\n }\n\n return 0;\n}\n-----"}, {"idx": "webquery-test-6", "doc": "c++ STL set difference", "code": "<algorithm><algorithm>#include <algorithm>\n#include <set>\n#include <iterator>\n// ...\nstd::set<int> s1, s2;\n// Fill in s1 and s2 with values\nstd::set<int> result;\nstd::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n std::inserter(result, result.end()));\nresultresult"}, {"idx": "webquery-test-7", "doc": "Why must the copy assignment operator return a reference/const reference?", "code": "voidvoidvoid"}, {"idx": "webquery-test-8", "doc": "Is Bjarne wrong about this example of ADL, or do I have a compiler bug?", "code": "operator<<operator<<operator<<"}, {"idx": "webquery-test-9", "doc": "Correct way to work with vector of arrays", "code": "vectorarraystd::vector<std::array<double, 4> >\nstd::arraystd::arraystd::array"}, {"idx": "webquery-test-1", "doc": "What is the difference between WM_QUIT, WM_CLOSE, and WM_DESTROY in a windows program?", "code": "WM_CLOSEWM_CLOSEWM_CLOSEWM_DESTROYWM_DESTROYWM_DESTROYWM_NCDESTROYWM_QUITWM_QUITWM_QUITWM_QUITWM_QUITWM_QUITWM_QUITWM_QUITWM_QUIT"}, {"idx": "webquery-test-2", "doc": "Export all symbols when creating a DLL", "code": "// ProjectExport.h\n\n#ifndef __PROJECT_EXPORT_H\n#define __PROJECT_EXPORT_H\n\n#ifdef USEPROJECTLIBRARY\n#ifdef PROJECTLIBRARY_EXPORTS \n#define PROJECTAPI __declspec(dllexport)\n#else\n#define PROJECTAPI __declspec(dllimport)\n#endif\n#else\n#define PROJECTAPI\n#endif\n\n#endif\n#include \"ProjectExport.h\"\n\nnamespace hello {\n class PROJECTAPI Hello {} \n}\n#include \"ProjectExport.h\"\n\nPROJECTAPI void HelloWorld();\nextern \"C\" __declspec(dllexport) void HelloWorld();\nextern \"C\" void HelloWorld();\nEXPORTS \n_HelloWorld\ncmake_minimum_required(VERSION 2.6)\nproject(cmake_export_all)\n\nset(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)\n\nset(dir ${CMAKE_CURRENT_SOURCE_DIR})\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY \"${dir}/bin\")\n\nset(SOURCE_EXE main.cpp)\n\ninclude_directories(foo)\n\nadd_executable(main ${SOURCE_EXE})\n\nadd_subdirectory(foo)\n\ntarget_link_libraries(main foo)\n#include \"foo.h\"\n\nint main() {\n HelloWorld();\n\n return 0;\n}\nproject(foo)\n\nset(SOURCE_LIB foo.cpp)\n\nadd_library(foo SHARED ${SOURCE_LIB})\nvoid HelloWorld();\n#include <iostream>\n\nvoid HelloWorld() {\n std::cout << \"Hello World!\" << std::endl;\n}\nDUMPBIN /SYMBOLS example.obj > log.txt\n"}, {"idx": "webquery-test-3", "doc": "How to use boost bind with a member function", "code": "boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );\n"}, {"idx": "webquery-test-4", "doc": "I do not understand why this compiles", "code": "aaa"}, {"idx": "webquery-test-5", "doc": "Why is the != operator not allowed with OpenMP?", "code": "!=for( i = 0; i < n; ++i )\nfor( i = 0; i != n; ++i ) \nfor( i = 0; i < n; i += 2 )\nfor( i = 0; i != n; i += 2 )\nfor( i = 0; i < n; i += k )\nfor( i = 0; i != n; i += k )\n"}, {"idx": "webquery-test-6", "doc": "Obtaining list of keys and values from unordered_map", "code": "std::vector<Key> keys;\nkeys.reserve(map.size());\nstd::vector<Val> vals;\nvals.reserve(map.size());\n\nfor(auto kv : map) {\n keys.push_back(kv.first);\n vals.push_back(kv.second); \n} \nmapmap"}, {"idx": "webquery-test-7", "doc": "Preparation for std::iterator Being Deprecated", "code": "std::iteratorstd::iteratortemplate<long FROM, long TO>\nclass Range {\npublic:\n // member typedefs provided through inheriting from std::iterator\n class iterator: public std::iterator<\n std::forward_iterator_tag, // iterator_category\n long, // value_type\n long, // difference_type\n const long*, // pointer\n const long& // reference\n > {\n long num = FROM;\n public:\n iterator(long _num = 0) : num(_num) {}\n iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}\n iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}\n bool operator==(iterator other) const {return num == other.num;}\n bool operator!=(iterator other) const {return !(*this == other);}\n long operator*() {return num;}\n };\n iterator begin() {return FROM;}\n iterator end() {return TO >= FROM? TO+1 : TO-1;}\n};\nstd::iteratortemplate<long FROM, long TO>\nclass Range {\npublic:\n class iterator {\n long num = FROM;\n public:\n iterator(long _num = 0) : num(_num) {}\n iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}\n iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}\n bool operator==(iterator other) const {return num == other.num;}\n bool operator!=(iterator other) const {return !(*this == other);}\n long operator*() {return num;}\n // iterator traits\n using difference_type = long;\n using value_type = long;\n using pointer = const long*;\n using reference = const long&;\n using iterator_category = std::forward_iterator_tag;\n };\n iterator begin() {return FROM;}\n iterator end() {return TO >= FROM? TO+1 : TO-1;}\n};\n"}, {"idx": "webquery-test-8", "doc": "Is there any case where a return of a RValue Reference (&&) is useful?", "code": "template <class Iter>\nclass move_iterator\n{\nprivate:\n Iter i_;\npublic:\n ...\n value_type&& operator*() const {return std::move(*i_);}\n ...\n};\n"}, {"idx": "webquery-test-9", "doc": "why is `std::initializer_list` often passed by value?", "code": "std::initializer_list"}, {"idx": "webquery-test-10", "doc": "C++11 std::set lambda comparison function", "code": "std::functionstd::functiondecltype#include <set>\n#include <iostream>\n#include <iterator>\n#include <algorithm>\n\nint main()\n{\n auto comp = [](int x, int y){ return x < y; };\n auto set = std::set<int,decltype(comp)>( comp );\n\n set.insert(1);\n set.insert(10);\n set.insert(1); // Dupe!\n set.insert(2);\n\n std::copy( set.begin(), set.end(), std::ostream_iterator<int>(std::cout, \"\\n\") );\n}\n1\n2\n10\n"}, {"idx": "webquery-test-1", "doc": "What does P::************ mean in Boost assert.hpp file?", "code": "static_assert BOOST_STATIC_ASSERT((std::is_same<T,U>));\nT=void*T=void*error: no matching function for call to \u2018assertion_failed(mpl_::failed************ std::is_same<void*, char*>::************)\u2019\n"}, {"idx": "webquery-test-2", "doc": "Is the behavior of subtracting two NULL pointers defined?", "code": "void *ptrdiff_tstd::ptrdiff_tstd::ptrdiff_t"}, {"idx": "webquery-test-3", "doc": "c++ inline function?", "code": "inlineinlineinlineinlineinline"}, {"idx": "webquery-test-4", "doc": "What is a non-trivial constructor in C++?", "code": "memcpymemcpy"}, {"idx": "webquery-test-5", "doc": "How do I build an import library (.lib) AND a DLL in Visual C++?", "code": "Configuration Properties/Linker/Advanced/Import Library\n"}, {"idx": "webquery-test-6", "doc": "Why does this call the default constructor?", "code": "(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));(X(answer));"}, {"idx": "webquery-test-7", "doc": "Why was std::strstream deprecated?", "code": "strstreamstrstreamstrstreamstrstreamstrstreamends"}, {"idx": "webquery-test-8", "doc": "Can we reassign the reference in C++?", "code": "ri = j; // >>> Is this not reassigning the reference? <<<ririririiiiconst int &cri = i;"}, {"idx": "webquery-test-9", "doc": "Derived template-class access to base-class member-data", "code": "this->void Bar<T>::BarFunc () {\n std::cout << this->_foo_arg << std::endl;\n}\nusingvoid Bar<T>::BarFunc () {\n using Bar<T>::_foo_arg; // Might not work in g++, IIRC\n std::cout << _foo_arg << std::endl;\n}\n"}, {"idx": "webquery-test-1", "doc": "Get elapsed time in Qt", "code": "QElapsedTimer#include <QDebug>\n#include <QElapsedTimer>\n...\n...\nQElapsedTimer timer;\ntimer.start();\nslowOperation(); // we want to measure the time of this slowOperation()\nqDebug() << timer.elapsed();\n"}, {"idx": "webquery-test-2", "doc": "Duplicate code using c++11", "code": "template<bool bonus = false>\nvoid MyFunction()\n{\n foo();\n bar();\n if (bonus) { doBonusStuff(); }\n foobar();\n}\nMyFunction<true>();\nMyFunction<false>();\nMyFunction(); // Call myFunction with the false template by default\nvoid MyFunctionAlone() { MyFunction<false>(); }\nvoid MyFunctionBonus() { MyFunction<true>(); }\ntemplate <int bonus>\nauto MyFunction() {\n foo();\n bar();\n if constexpr (bonus == 0) { doBonusStuff1(); }\n else if constexpr (bonus == 1) { doBonusStuff2(); }\n else if constexpr (bonus == 2) { doBonusStuff3(); }\n else if constexpr (bonus == 3) { doBonusStuff4(); }\n // Guarantee that this function will not compile\n // if a bonus different than 0,1,2,3 is passer\n else { static_assert(false);}, \n foorbar();\n}\n"}, {"idx": "webquery-test-3", "doc": "If a 32-bit integer overflows, can we use a 40-bit structure instead of a 64-bit long one?", "code": "#include <stdint.h> // don't want to rely on something like long long\nstruct bad_idea\n{\n uint64_t var : 40;\n};\nvarstruct using_gaps\n{\n uint64_t var : 40;\n uint64_t useful_uint16 : 16;\n uint64_t char_or_bool : 8; \n};\noperator[]Running test for array size = 1048576\nwhat alloc seq(w) seq(r) rand(w) rand(r) free\n-----------------------------------------------------------\nuint32_t 0 2 1 35 35 1\nuint64_t 0 3 3 35 35 1\nbad40_t 0 5 3 35 35 1\npacked40_t 0 7 4 48 49 1\n\n\nRunning test for array size = 16777216\nwhat alloc seq(w) seq(r) rand(w) rand(r) free\n-----------------------------------------------------------\nuint32_t 0 38 14 560 555 8\nuint64_t 0 81 22 565 554 17\nbad40_t 0 85 25 565 561 16\npacked40_t 0 151 75 765 774 16\n\n\nRunning test for array size = 134217728\nwhat alloc seq(w) seq(r) rand(w) rand(r) free\n-----------------------------------------------------------\nuint32_t 0 312 100 4480 4441 65\nuint64_t 0 648 172 4482 4490 130\nbad40_t 0 682 193 4573 4492 130\npacked40_t 0 1164 552 6181 6176 130\n"}, {"idx": "webquery-test-4", "doc": "How do I deal with the max macro in windows.h colliding with max in std?", "code": "NOMINMAX"}, {"idx": "webquery-test-5", "doc": "error LNK2005, already defined?", "code": "namespace \n{\n int k;\n}\nexternextern int k;\n#include \"A.h\"\nint k = 0;\n#include \"A.h\"\n\n//Use `k` anywhere in the file \n"}, {"idx": "webquery-test-6", "doc": "Initialize a vector array of strings", "code": "std::vector<std::string> v = { \"xyzzy\", \"plugh\", \"abracadabra\" };\nstd::vector<std::string> v({ \"xyzzy\", \"plugh\", \"abracadabra\" });\nstd::vector<std::string> v{ \"xyzzy\", \"plugh\", \"abracadabra\" }; \n"}, {"idx": "webquery-test-7", "doc": "Lazy evaluation in C++", "code": "matrix operator +(matrix const& a, matrix const& b);\nstruct matrix_add;\n\nmatrix_add operator +(matrix const& a, matrix const& b) {\n return matrix_add(a, b);\n}\nstruct matrix_add {\n matrix_add(matrix const& a, matrix const& b) : a(a), b(b) { }\n\n operator matrix() const {\n matrix result;\n // Do the addition.\n return result;\n }\nprivate:\n matrix const& a, b;\n};\noperator matrix()operator matrix()operator matrix()operator matrix()matrix_addint value = (A + B)(2, 3);\nAAAstruct matrix_add {\n // \u2026\u00a0yadda, yadda, yadda \u2026\n\n int operator ()(unsigned int x, unsigned int y) {\n // Calculate *just one* element:\n return a(x, y) + b(x, y);\n }\n};\ninfix"}, {"idx": "webquery-test-8", "doc": "How to access the contents of a vector from a pointer to the vector in C++?", "code": "int main(int nArgs, char ** vArgs)\n{\n vector<int> *v = new vector<int>(10);\n v->at(2); //Retrieve using pointer to member\n v->operator[](2); //Retrieve using pointer to operator member\n v->size(); //Retrieve size\n vector<int> &vr = *v; //Create a reference\n vr[2]; //Normal access through reference\n delete &vr; //Delete the reference. You could do the same with\n //a pointer (but not both!)\n}\n"}, {"idx": "webquery-test-9", "doc": "Foreach loop in C++ equivalent of C#", "code": "std::array<std::string, 3> strarr = {\"ram\", \"mohan\", \"sita\"};\nfor(const std::string& str : strarr) {\n listbox.items.add(str);\n}\nstd::string strarr[] = {\"ram\", \"mohan\", \"sita\"};\nfor(int i = 0; i < 3; ++i) {\n listbox.items.add(strarr[i]);\n}\nstd::string strarr[] = {\"ram\", \"mohan\", \"sita\"};\nstd::vector<std::string> strvec(strarr, strarr + 3);\nstd::vector<std::string>::iterator itr = strvec.begin();\nwhile(itr != strvec.end()) {\n listbox.items.add(*itr);\n ++itr;\n}\nboost::array<std::string, 3> strarr = {\"ram\", \"mohan\", \"sita\"};\nBOOST_FOREACH(std::string & str, strarr) {\n listbox.items.add(str);\n}\n"}, {"idx": "webquery-test-10", "doc": "How can I print out C++ map values?", "code": "for(map<string, pair<string,string> >::const_iterator it = myMap.begin();\n it != myMap.end(); ++it)\n{\n std::cout << it->first << \" \" << it->second.first << \" \" << it->second.second << \"\\n\";\n}\nmap<string, pair<string,string> >::const_iteratormap<string, pair<string,string> >::const_iteratorfor(auto it = myMap.cbegin(); it != myMap.cend(); ++it)\n{\n std::cout << it->first << \" \" << it->second.first << \" \" << it->second.second << \"\\n\";\n}\ncbegin()cbegin()for(const auto& elem : myMap)\n{\n std::cout << elem.first << \" \" << elem.second.first << \" \" << elem.second.second << \"\\n\";\n}\n"}, {"idx": "webquery-test-11", "doc": "Generating combinations in c++", "code": "std::next_permutation#include <iostream>\n#include <algorithm>\n#include <vector>\n\nint main() {\n int n, r;\n std::cin >> n;\n std::cin >> r;\n\n std::vector<bool> v(n);\n std::fill(v.end() - r, v.end(), true);\n\n do {\n for (int i = 0; i < n; ++i) {\n if (v[i]) {\n std::cout << (i + 1) << \" \";\n }\n }\n std::cout << \"\\n\";\n } while (std::next_permutation(v.begin(), v.end()));\n return 0;\n}\n#include <iostream>\n#include <algorithm>\n#include <vector>\n\nint main() {\n int n, r;\n std::cin >> n;\n std::cin >> r;\n\n std::vector<bool> v(n);\n std::fill(v.begin(), v.begin() + r, true);\n\n do {\n for (int i = 0; i < n; ++i) {\n if (v[i]) {\n std::cout << (i + 1) << \" \";\n }\n }\n std::cout << \"\\n\";\n } while (std::prev_permutation(v.begin(), v.end()));\n return 0;\n}\nvvv"}, {"idx": "webquery-test-1", "doc": "how-to initialize 'const std::vector<T>' like a c array", "code": "vector<int> luggage_combo = { 1, 2, 3, 4, 5 };\n#include <boost/assign/std/vector.hpp>\nusing namespace boost::assign; // bring 'operator+=()' into scope\n\nvector<int> v;\nv += 1,2,3,4,5;\n"}, {"idx": "webquery-test-2", "doc": "\"relocation R_X86_64_32S against \" linking Error", "code": "liblog4cplus.aliblog4cplus.aar -x liblog4cplus.a \nreadelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'\nliblog4cplus.aliblog4cplus.a"}, {"idx": "webquery-test-3", "doc": "C and C++ : Partial initialization of automatic structure", "code": "int array[10] = {1,2}; //Case 1:Partial Initialization\nint array[10] = {0,1,2,3,4,5,6,7,8,9}; //Case 2:Complete Initialization\nint array[10]; //Case 3:No Initialization\nCase 3Case 10 struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n struct S { int a; char* b; int c; };\n S ss = { 1, \"asdf\" };\n"}, {"idx": "webquery-test-4", "doc": "I'm getting an error \"invalid use of incomplete type 'class map'", "code": "MapMapMapMap.h.h"}, {"idx": "webquery-test-5", "doc": "Is begin() == end() for any empty() vector?", "code": "empty() +----------+---------------+----------------------+\n |Expression| Return Type | Operational Semantics|\n |----------|---------------|----------------------|\n |a.empty() |Convertible |a.begin() == a.end() |\n | |to bool | |\n | | | |\n +-------------------------------------------------+\n"}, {"idx": "webquery-test-6", "doc": "C++ view types: pass by const& or by value?", "code": "const"}, {"idx": "webquery-test-7", "doc": "Nested templates with dependent scope", "code": "typenametypename typedef typename ptrModel<std::vector<Data> >::Type Type;\nptrModel<std::vector<Data> >::TypeptrModel<std::vector<Data> >::TypeptrModel<std::vector<Data> >::TypeptrModel<std::vector<Data> >::TypeptrModel<std::vector<Data> >::TypeptrModel<std::vector<Data> >::Type"}, {"idx": "webquery-test-8", "doc": "C++ inline member function in .cpp file", "code": "getA()"}, {"idx": "webquery-test-9", "doc": "Array size at run time without dynamic allocation is allowed?", "code": "mallocmallocmallocmallocmalloc"}, {"idx": "webquery-test-10", "doc": "How to convert typename T to string in c++", "code": "typeid(T)::name()// default implementation\ntemplate <typename T>\nstruct TypeName\n{\n static const char* Get()\n {\n return typeid(T).name();\n }\n};\n\n// a specialization for each type of those you want to support\n// and don't like the string returned by typeid\ntemplate <>\nstruct TypeName<int>\n{\n static const char* Get()\n {\n return \"int\";\n }\n};\n\n// usage:\nconst char* name = TypeName<MyType>::Get();\n"}, {"idx": "webquery-test-11", "doc": "What does \"class :\" mean in C++?", "code": "sampleclass Foo : private sample\n{\n // ...\n};\n\nFoo x;\n"}, {"idx": "webquery-test-1", "doc": "How to detect whether there is a specific member variable in class?", "code": "#include <type_traits>\n\ntemplate <typename T, typename = int>\nstruct HasX : std::false_type { };\n\ntemplate <typename T>\nstruct HasX <T, decltype((void) T::x, 0)> : std::true_type { };\nstruct A { int x; };\nstruct B { int y; };\nHasX<A>::value == trueHasX<A>::value == truestd::false_typestd::false_typestd::false_typestd::false_typestd::false_typestd::false_typestd::false_typestd::false_typestd::false_typetemplate <typename T, typename U>\nstruct HasX : std::false_type { };\nHasXHasXHasXHasXU// Primary template\ntemplate <typename T, typename U = int>\nstruct HasX : std::false_type { };\nUUUUU// Primary template\ntemplate <typename T, typename U = int>\nstruct HasX : std::false_type { };\n\n// Specialization for U = int\ntemplate <typename T>\nstruct HasX<T, int> : std::true_type { };\nHasX<T, U>HasX<T, U>HasX<T, U>HasX<T, U>HasX<T, U>HasX<T, U>UUdecltypedecltypedecltype(expression)decltype(expression)decltype(expression)decltype(expression)decltype(expression)decltype(expression)decltype(expression)decltype(expression)decltype(expression)char func(foo, int);\nfoofoofoofoofoofoo(1.2, 0)(1.2, 0)(1.2, 0)int x = (1.2, 0);\nint x = 0;\ndecltypedecltypedecltypedecltypedecltypedecltypedecltypedecltypedecltypedecltype(f, 0)decltype(f, 0)decltype(f, 0)decltype(f, 0)decltype(f, 0)decltype(f, 0)decltype(f, 0)decltype(f, 0)voidvoidvoidvoidvoidvoidvoidvoidvoidvoidvoidvoidvoidvoidfoofoofoofoodecltype((void) f, 0)decltype((void) f, 0)// Primary template\ntemplate <typename T, typename U = int>\nstruct HasX : std::false_type { };\n\n// Specialization for U = int\ntemplate <typename T>\nstruct HasX <T, decltype((void) T::x, 0)> : std::true_type { };\ndecltype((void) T::x, 0)decltype((void) T::x, 0)TTTTTTTTTHasX<bool, int>::value == falseboolboolboolboolboolboolboolboolboolUUU"}, {"idx": "webquery-test-2", "doc": "How to get a pointer from a reference?", "code": "#include <iostream>\n\nstruct foo {};\n\nvoid bar( const foo& obj )\n{\n std::cout << &obj << std::endl;\n}\n\nint main()\n{\n foo obj;\n std::cout << &obj << std::endl;\n bar( obj );\n\n return 0;\n}\n0x22ff1f\n0x22ff1f\n"}, {"idx": "webquery-test-3", "doc": "Unusual usage of .h file in C", "code": "#include#include#includefloat h[N] = {\n #include \"f1.h\"\n};\n#include.h.h.hgcc -C -E -Wall yoursource.c > yoursource.igcc -C -E -Wall yoursource.c > yoursource.ih-data.ch-data.ch-data.ch-data.ch-data.ch-data.ch-data.c"}, {"idx": "webquery-test-4", "doc": "Why am I getting string does not name a type Error?", "code": "usingusingusingusingusingusingusingusingusingusing"}, {"idx": "webquery-test-5", "doc": "Why using the const keyword before and after method or function name?", "code": "const T& get_data() const { return data_; }\n^^^^^\nconstconstconstClass c;\nT& t = c.get_data() // Not allowed.\nconst T& tc = c.get_data() // OK.\nconst T& get_data() const { return data_; }\n ^^^^^\nmutablevoid Class::get_data() const {\n this->data_ = ...; // is not allowed here since get_data() is const (unless 'data_' is mutable)\n this->anything = ... // Not allowed unless the thing is 'mutable'\n}\n"}, {"idx": "webquery-test-6", "doc": "Use of \"this\" keyword in C++", "code": "Person::Person() {\n int age;\n this->age = 1;\n}\nPerson::Person(int _age) {\n age = _age;\n}\nPerson::Person(int age) : age(age) {}\n"}, {"idx": "webquery-test-7", "doc": "Will an 'empty' constructor or destructor do the same thing as the generated one?", "code": "struct A { private: ~A(); };\nstruct B : A { }; \nstruct A { private: ~A(); };\nstruct B : A { ~B() { /* ... */ } }; \n~Bstruct C;\nstruct A {\n auto_ptr<C> a;\n A();\n};\nCCCCCCCC.cpp.cpp.cppstruct C;\nstruct A {\n auto_ptr<C> a;\n A();\n ~A(); // defined as ~A() { } in .cpp file, too\n};\nboost::shared_ptrmemsetstruct A {\n int a;\n};\n\nstruct B {\n int b;\n B() { }\n};\nassert(A().a == 0);\nbassert(B().b == 0);\nnewnewnew"}, {"idx": "webquery-test-8", "doc": "rationale for std::lower_bound and std::upper_bound?", "code": "firstfirstfirstfirstfirstl = std::lower_bound(first, last, val)\nu = std::upper_bound(first, last, val)\nvalvalvalvalvalstd::equal_range"}, {"idx": "webquery-test-1", "doc": "Is sizeof in C++ evaluated at compilation time or run time?", "code": "sizeof"}, {"idx": "webquery-test-2", "doc": "What would be a \"Hello, World!\" example for \"std::ref\"?", "code": "std::refstd::bindstd::bindstd::refstd::ref#include <iostream>\n#include <functional>\n#include <thread>\n\nvoid increment( int &x )\n{\n ++x;\n}\n\nint main()\n{\n int i = 0;\n\n // Here, we bind increment to a COPY of i...\n std::bind( increment, i ) ();\n // ^^ (...and invoke the resulting function object)\n\n // i is still 0, because the copy was incremented.\n std::cout << i << std::endl;\n\n // Now, we bind increment to std::ref(i)\n std::bind( increment, std::ref(i) ) ();\n // i has now been incremented.\n std::cout << i << std::endl;\n\n // The same applies for std::thread\n std::thread( increment, std::ref(i) ).join();\n std::cout << i << std::endl;\n}\n0\n1\n2\n"}, {"idx": "webquery-test-3", "doc": "How do you print a C++11 time_point?", "code": "std::chrono::system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()system_clock::now()time_pointtime_point_casttime_point<system_clock, nanoseconds> time_point;\ntime_point = time_point_cast<nanoseconds>(system_clock::now());\ntime_point_casttime_point_casttime_pointtime_pointtime_pointsystem_clock::time_point time_point;\ntime_point = system_clock::now(); // no time_point_cast needed\nautoauto time_point = system_clock::now(); \ntime_tstd::time_t now_c = std::chrono::system_clock::to_time_t(time_point);\ntime_ttime_ttime_ttime_t"}, {"idx": "webquery-test-4", "doc": "Can I use identical names for fields and constructor parameters?", "code": "class A\n{\n\n A(int a)\n : a(5)//<--- try to initialize a non member variable to 5\n {\n }\n};\nclass A\n{\n\n A(int myVarriable)\n : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly\n {\n }\n int myVariable;\n};\nclass A\n{\n\n A(int myVariable_)\n {\n //<-- do something with _myVariable, oops _myVariable wasn't initialized yet\n ...\n _myVariable = myVariable_;\n }\n int _myVariable;\n};\n"}, {"idx": "webquery-test-5", "doc": "Does C++ pass objects by value or reference?", "code": "void foo(type arg)void foo(type arg)void foo(type arg)void foo(type arg)void foo(type arg)void foo(type (&arg)[10])"}, {"idx": "webquery-test-6", "doc": "Does const-correctness give the compiler more room for optimization?", "code": "constint foo(const int *p) {\n int x = *p;\n bar(x);\n x = *p;\n return x;\n}\n*p*p*p*pfoo()foo()foo()foo()constconstfoo()int x = 37;\nfoo(&x);\nprintf(\"%d\\n\", x);\nfoo()foo()foo()foo()foo()constconst int x = 37;\nfoo(&x);\nprintf(\"%d\\n\", x);\nxxxrestrictfoo()foo(const int * restrict p)\n*p*p*prestrictrestrict"}, {"idx": "webquery-test-7", "doc": "What's the difference between static constexpr and static inline variables in C++17?", "code": "mySecondVarmySecondVarmyFirstVarclass MyClass {\n static constexpr int myFirstVar;\n};\n\nint MyClass::myFirstVar = 1;\n#include <cstdlib>\n\nclass MyClass {\n static constexpr int myFirstVar = rand();\n};\nconstexprinlineinline#include <cstdlib>\n\nclass MyClass {\n static const int mySecondVar;\n};\n\ninline const int MyClass::mySecondVar = rand();\nclass MyClass {\n static inline int mySecondVar();\n};\n\ninline int MyClass::mySecondVar() {\n static const int value = rand();\n return value;\n}\n"}, {"idx": "webquery-test-8", "doc": "Conversion constructor vs. conversion operator: precedence", "code": "B(const A&)\noperator B() \nB(const A&)\nB(A&)\nA&A&A&BB8.5/1413.3.1.413.3.3.2/3"}, {"idx": "webquery-test-1", "doc": "What does this typedef statement mean?", "code": "inttypedef int int_t; // simple int\ntypedef int *intp_t; // pointer to int\ntypedef int (&fp)(int, ulong); // reference to function returning int\ntypedef int arr_t[10]; // array of 10 ints\n"}, {"idx": "webquery-test-2", "doc": "Generate SHA hash in C++ using OpenSSL library", "code": "printf \"compute sha1\" | openssl sha1\n#include <stdio.h>\n#include <string.h>\n#include <openssl/sha.h>\n\nint main()\n{\n unsigned char ibuf[] = \"compute sha1\";\n unsigned char obuf[20];\n\n SHA1(ibuf, strlen(ibuf), obuf);\n\n int i;\n for (i = 0; i < 20; i++) {\n printf(\"%02x \", obuf[i]);\n }\n printf(\"\\n\");\n\n return 0;\n}\n"}, {"idx": "webquery-test-3", "doc": "rand() between 0 and 1", "code": "RAND_MAXRAND_MAXRAND_MAX + 1RAND_MAX + 1RAND_MAX + 1RAND_MAX + 1RAND_MAX + 1RAND_MAX + 1RAND_MAX + 1RAND_MAX + 11 <= r < 2r = ((double) rand() / (RAND_MAX)) + 1\n"}, {"idx": "webquery-test-4", "doc": "const to Non-const Conversion in C++", "code": "constconstconstint main() {\n const int a = 3;\n int b = a;\n}\nconstint main() {\n const int a = 3;\n int& b = a; // or int* b = &a;\n}\n\n// error: invalid initialization of reference of type 'int&' from\n// expression of type 'const int'\nconst_castconst_castconst_castint main() {\n const int a = 3;\n int& b = const_cast<int&>(a);\n\n b = 3;\n}\n"}, {"idx": "webquery-test-5", "doc": "Create N-element constexpr array in C++11", "code": "constexpr#include <iostream>\n\ntemplate<int N>\nstruct A {\n constexpr A() : arr() {\n for (auto i = 0; i != N; ++i)\n arr[i] = i; \n }\n int arr[N];\n};\n\nint main() {\n constexpr auto a = A<4>();\n for (auto x : a.arr)\n std::cout << x << '\\n';\n}\n"}, {"idx": "webquery-test-6", "doc": "Getting a boost::shared_ptr for this", "code": "#include <boost/enable_shared_from_this.hpp>\n\nclass Y: public boost::enable_shared_from_this<Y>\n{\npublic:\n\n shared_ptr<Y> f()\n {\n return shared_from_this();\n }\n}\n\nint main()\n{\n shared_ptr<Y> p(new Y);\n shared_ptr<Y> q = p->f();\n assert(p == q);\n assert(!(p < q || q < p)); // p and q must share ownership\n}\n"}, {"idx": "webquery-test-7", "doc": "There are no arguments that depend on a template parameter", "code": "ignorefoobar::ignore (...)foobar::ignore (...)foobar::ignore (...)template <typename T> void foo() {\n T x;\n x.frobnicate();\n}\nclass Foo {};\n\ntemplate <typename T> void foo() {\n Foo foo;\n foo.frobnicate();\n}\n"}, {"idx": "webquery-test-8", "doc": "Why would the behavior of std::memcpy be undefined for objects that are not TriviallyCopyable?", "code": "std::memcpymemcpystd::copystd::copystd::copy"}, {"idx": "webquery-test-1", "doc": "Must I call atomic load/store explicitly?", "code": "atomic<T>::operator Tatomic<T>::operator Tatomic<T>::operator Tatomic<T>::operator T"}, {"idx": "webquery-test-2", "doc": "How to make generic computations over heterogeneous argument packs of a variadic template function?", "code": "for_each_in_arg_pack()// Simple functor with a generic call operator that prints its input. This is used by the\n// following functors and by some demonstrative test cases in the main() routine.\nstruct print\n{\n template<typename T>\n void operator () (T&& t)\n {\n cout << t << endl;\n }\n};\n\n// This shows how a for_each_*** helper can be used inside a variadic template function\ntemplate<typename... Ts>\nvoid print_all(Ts&&... args)\n{\n for_each_in_arg_pack(print(), forward<Ts>(args)...);\n}\nprint// Shows how to select portions of an argument pack and \n// invoke a functor for each of the selected elements\ntemplate<typename... Ts>\nvoid split_and_print(Ts&&... args)\n{\n constexpr size_t packSize = sizeof...(args);\n constexpr size_t halfSize = packSize / 2;\n\n cout << \"Printing first half:\" << endl;\n for_each_in_arg_pack_subset(\n print(), // The functor to invoke for each element\n index_range<0, halfSize>(), // The indices to select\n forward<Ts>(args)... // The argument pack\n );\n\n cout << \"Printing second half:\" << endl;\n for_each_in_arg_pack_subset(\n print(), // The functor to invoke for each element\n index_range<halfSize, packSize>(), // The indices to select\n forward<Ts>(args)... // The argument pack\n );\n}\nforward_subpack()// Functor with variadic call operator that shows the usage of for_each_*** \n// to print all the arguments of a heterogeneous pack\nstruct my_func\n{\n template<typename... Ts>\n void operator ()(Ts&&... args)\n {\n print_all(forward<Ts>(args)...);\n }\n};\n\n// Shows how to forward only a portion of an argument pack \n// to another variadic functor\ntemplate<typename... Ts>\nvoid split_and_print(Ts&&... args)\n{\n constexpr size_t packSize = sizeof...(args);\n constexpr size_t halfSize = packSize / 2;\n\n cout << \"Printing first half:\" << endl;\n forward_subpack(my_func(), index_range<0, halfSize>(), forward<Ts>(args)...);\n\n cout << \"Printing second half:\" << endl;\n forward_subpack(my_func(), index_range<halfSize, packSize>(), forward<Ts>(args)...);\n}\nnth_value_of()nth_value_of()nth_value_of()// Shows that arguments in a pack can be indexed\ntemplate<unsigned I, typename... Ts>\nvoid print_first_last_and_indexed(Ts&&... args)\n{\n cout << \"First argument: \" << first_value_of(forward<Ts>(args)...) << endl;\n cout << \"Last argument: \" << last_value_of(forward<Ts>(args)...) << endl;\n cout << \"Argument #\" << I << \": \" << nth_value_of<I>(forward<Ts>(args)...) << endl;\n}\nis_homogeneous_pack<>is_homogeneous_pack<>// Shows the use of range-based for loops to iterate over a\n// homogeneous argument pack\ntemplate<typename... Ts>\nvoid print_all(Ts&&... args)\n{\n static_assert(\n is_homogeneous_pack<Ts...>::value, \n \"Template parameter pack not homogeneous!\"\n );\n\n for (auto&& x : { args... })\n {\n // Do something with x...\n }\n\n cout << endl;\n}\nhomogeneous-type<> // ...\n static_assert(\n is_homogeneous_pack<Ts...>::value, \n \"Template parameter pack not homogeneous!\"\n );\n using type = homogeneous_type<Ts...>::type;\n for_each_in_arg_pack([] (type const& x) { cout << x << endl; }, forward<Ts>(args)...);\n#include <type_traits>\n#include <utility>\n\n//===============================================================================\n// META-FUNCTIONS FOR EXTRACTING THE n-th TYPE OF A PARAMETER PACK\n\n// Declare primary template\ntemplate<int I, typename... Ts>\nstruct nth_type_of\n{\n};\n\n// Base step\ntemplate<typename T, typename... Ts>\nstruct nth_type_of<0, T, Ts...>\n{\n using type = T;\n};\n\n// Induction step\ntemplate<int I, typename T, typename... Ts>\nstruct nth_type_of<I, T, Ts...>\n{\n using type = typename nth_type_of<I - 1, Ts...>::type;\n};\n\n// Helper meta-function for retrieving the first type in a parameter pack\ntemplate<typename... Ts>\nstruct first_type_of\n{\n using type = typename nth_type_of<0, Ts...>::type;\n};\n\n// Helper meta-function for retrieving the last type in a parameter pack\ntemplate<typename... Ts>\nstruct last_type_of\n{\n using type = typename nth_type_of<sizeof...(Ts) - 1, Ts...>::type;\n};\n\n//===============================================================================\n// FUNCTIONS FOR EXTRACTING THE n-th VALUE OF AN ARGUMENT PACK\n\n// Base step\ntemplate<int I, typename T, typename... Ts>\nauto nth_value_of(T&& t, Ts&&... args) ->\n typename std::enable_if<(I == 0), decltype(std::forward<T>(t))>::type\n{\n return std::forward<T>(t);\n}\n\n// Induction step\ntemplate<int I, typename T, typename... Ts>\nauto nth_value_of(T&& t, Ts&&... args) ->\n typename std::enable_if<(I > 0), decltype(\n std::forward<typename nth_type_of<I, T, Ts...>::type>(\n std::declval<typename nth_type_of<I, T, Ts...>::type>()\n )\n )>::type\n{\n using return_type = typename nth_type_of<I, T, Ts...>::type;\n return std::forward<return_type>(nth_value_of<I - 1>((std::forward<Ts>(args))...));\n}\n\n// Helper function for retrieving the first value of an argument pack\ntemplate<typename... Ts>\nauto first_value_of(Ts&&... args) ->\n decltype(\n std::forward<typename first_type_of<Ts...>::type>(\n std::declval<typename first_type_of<Ts...>::type>()\n )\n )\n{\n using return_type = typename first_type_of<Ts...>::type;\n return std::forward<return_type>(nth_value_of<0>((std::forward<Ts>(args))...));\n}\n\n// Helper function for retrieving the last value of an argument pack\ntemplate<typename... Ts>\nauto last_value_of(Ts&&... args) ->\n decltype(\n std::forward<typename last_type_of<Ts...>::type>(\n std::declval<typename last_type_of<Ts...>::type>()\n )\n )\n{\n using return_type = typename last_type_of<Ts...>::type;\n return std::forward<return_type>(nth_value_of<sizeof...(Ts) - 1>((std::forward<Ts>(args))...));\n}\n\n//===============================================================================\n// METAFUNCTION FOR COMPUTING THE UNDERLYING TYPE OF HOMOGENEOUS PARAMETER PACKS\n\n// Used as the underlying type of non-homogeneous parameter packs\nstruct null_type\n{\n};\n\n// Declare primary template\ntemplate<typename... Ts>\nstruct homogeneous_type;\n\n// Base step\ntemplate<typename T>\nstruct homogeneous_type<T>\n{\n using type = T;\n static const bool isHomogeneous = true;\n};\n\n// Induction step\ntemplate<typename T, typename... Ts>\nstruct homogeneous_type<T, Ts...>\n{\n // The underlying type of the tail of the parameter pack\n using type_of_remaining_parameters = typename homogeneous_type<Ts...>::type;\n\n // True if each parameter in the pack has the same type\n static const bool isHomogeneous = std::is_same<T, type_of_remaining_parameters>::value;\n\n // If isHomogeneous is \"false\", the underlying type is the fictitious null_type\n using type = typename std::conditional<isHomogeneous, T, null_type>::type;\n};\n\n// Meta-function to determine if a parameter pack is homogeneous\ntemplate<typename... Ts>\nstruct is_homogeneous_pack\n{\n static const bool value = homogeneous_type<Ts...>::isHomogeneous;\n};\n\n//===============================================================================\n// META-FUNCTIONS FOR CREATING INDEX LISTS\n\n// The structure that encapsulates index lists\ntemplate <unsigned... Is>\nstruct index_list\n{\n};\n\n// Collects internal details for generating index ranges [MIN, MAX)\nnamespace detail\n{\n // Declare primary template for index range builder\n template <unsigned MIN, unsigned N, unsigned... Is>\n struct range_builder;\n\n // Base step\n template <unsigned MIN, unsigned... Is>\n struct range_builder<MIN, MIN, Is...>\n {\n typedef index_list<Is...> type;\n };\n\n // Induction step\n template <unsigned MIN, unsigned N, unsigned... Is>\n struct range_builder : public range_builder<MIN, N - 1, N - 1, Is...>\n {\n };\n}\n\n// Meta-function that returns a [MIN, MAX) index range\ntemplate<unsigned MIN, unsigned MAX>\nusing index_range = typename detail::range_builder<MIN, MAX>::type;\n\n//===============================================================================\n// CLASSES AND FUNCTIONS FOR REALIZING LOOPS ON ARGUMENT PACKS\n\n// Implementation inspired by @jogojapan's answer to this question:\n// http://stackoverflow.com/questions/14089637/return-several-arguments-for-another-function-by-a-single-function\n\n// Collects internal details for implementing functor invocation\nnamespace detail\n{\n // Functor invocation is realized through variadic inheritance.\n // The constructor of each base class invokes an input functor.\n // An functor invoker for an argument pack has one base class\n // for each argument in the pack\n\n // Realizes the invocation of the functor for one parameter\n template<unsigned I, typename T>\n struct invoker_base\n {\n template<typename F, typename U>\n invoker_base(F&& f, U&& u) { f(u); }\n };\n\n // Necessary because a class cannot inherit the same class twice\n template<unsigned I, typename T>\n struct indexed_type\n {\n static const unsigned int index = I;\n using type = T;\n };\n\n // The functor invoker: inherits from a list of base classes.\n // The constructor of each of these classes invokes the input\n // functor with one of the arguments in the pack.\n template<typename... Ts>\n struct invoker : public invoker_base<Ts::index, typename Ts::type>...\n {\n template<typename F, typename... Us>\n invoker(F&& f, Us&&... args)\n :\n invoker_base<Ts::index, typename Ts::type>(std::forward<F>(f), std::forward<Us>(args))...\n {\n }\n };\n}\n\n// The functor provided in the first argument is invoked for each\n// argument in the pack whose index is contained in the index list\n// specified in the second argument\ntemplate<typename F, unsigned... Is, typename... Ts>\nvoid for_each_in_arg_pack_subset(F&& f, index_list<Is...> const& i, Ts&&... args)\n{\n // Constructors of invoker's sub-objects will invoke the functor.\n // Note that argument types must be paired with numbers because the\n // implementation is based on inheritance, and one class cannot\n // inherit the same base class twice.\n detail::invoker<detail::indexed_type<Is, typename nth_type_of<Is, Ts...>::type>...> invoker(\n f,\n (nth_value_of<Is>(std::forward<Ts>(args)...))...\n );\n}\n\n// The functor provided in the first argument is invoked for each\n// argument in the pack\ntemplate<typename F, typename... Ts>\nvoid for_each_in_arg_pack(F&& f, Ts&&... args)\n{\n for_each_in_arg_pack_subset(f, index_range<0, sizeof...(Ts)>(), std::forward<Ts>(args)...);\n}\n\n// The functor provided in the first argument is given in input the\n// arguments in whose index is contained in the index list specified\n// as the second argument.\ntemplate<typename F, unsigned... Is, typename... Ts>\nvoid forward_subpack(F&& f, index_list<Is...> const& i, Ts&&... args)\n{\n f((nth_value_of<Is>(std::forward<Ts>(args)...))...);\n}\n\n// The functor provided in the first argument is given in input all the\n// arguments in the pack.\ntemplate<typename F, typename... Ts>\nvoid forward_pack(F&& f, Ts&&... args)\n{\n f(std::forward<Ts>(args)...);\n}\n"}, {"idx": "webquery-test-3", "doc": "Why does unique_ptr take two template parameters when shared_ptr only takes one?", "code": "unique_ptrunique_ptrunique_ptrunique_ptrshared_ptr"}, {"idx": "webquery-test-4", "doc": "> vs. >= in bubble sort causes significant performance difference", "code": "Limit == 10Limit == 10"}, {"idx": "webquery-test-5", "doc": "C++ trying to swap values in a vector", "code": "iter_swapiter_swap// assuming your vector is called v\niter_swap(v.begin() + position, v.begin() + next_position);\n// position, next_position are the indices of the elements you want to swap\n"}, {"idx": "webquery-test-6", "doc": "How to use an iterator?", "code": "using namespace stdusing namespace stdusing namespace stdusing namespace stdusing namespace stdusing namespace stdusing namespace std&*ii&*ii&*ii&*iifloat distance(const point& p1, const point& p2)\n{\n return sqrt((p1.x - p2.x)*(p1.x - p2.x) +\n (p1.y - p2.y)*(p1.y - p2.y));\n}\nconstdistance(*ii,*jj)typedef struct point {\n float x;\n float y;\n} point;\nstruct point {\n float x;\n float y;\n};\nstructstructstructstruct"}, {"idx": "webquery-test-7", "doc": "Why override operator()?", "code": "struct Accumulator\n{\n int counter = 0;\n int operator()(int i) { return counter += i; }\n}\n...\nAccumulator acc;\ncout << acc(10) << endl; //prints \"10\"\ncout << acc(20) << endl; //prints \"30\"\ntemplate <typename InputIterator, typename Functor>\nvoid for_each(InputIterator first, InputIterator last, Functor f)\n{\n while (first != last) f(*first++);\n}\nvoid print(int i) { std::cout << i << std::endl; }\n... \nstd::vector<int> vec;\n// Fill vec\n\n// Using a functor\nAccumulator acc;\nstd::for_each(vec.begin(), vec.end(), acc);\n// acc.counter contains the sum of all elements of the vector\n\n// Using a function pointer\nstd::for_each(vec.begin(), vec.end(), print); // prints all elements\n"}, {"idx": "webquery-test-8", "doc": "what is the size of an enum type data in C++?", "code": "sizeof(months_t)januaryjanuary"}, {"idx": "webquery-test-9", "doc": "class & function names highlighting in Vim", "code": "$VIMRUNTIME/syntax/c.vim\n$HOME/.vim/syntax/c.vim (for UNIX)\n$HOME/vimfiles/syntax/c.vim (for PC or OS/2)\n\" Highlight Class and Function names\nsyn match cCustomParen \"(\" contains=cParen,cCppParen\nsyn match cCustomFunc \"\\w\\+\\s*(\" contains=cCustomParen\nsyn match cCustomScope \"::\"\nsyn match cCustomClass \"\\w\\+\\s*::\" contains=cCustomScope\n\nhi def link cCustomFunc Function\nhi def link cCustomClass Function\nhi def cCustomFunc gui=bold guifg=yellowgreen\nhi def cCustomClass gui=reverse guifg=#00FF00\nhi cCustomFunc gui=bold guifg=yellowgreen\nhi cCustomClass gui=reverse guifg=#00FF00\n"}, {"idx": "webquery-test-10", "doc": "Struct with template variables in C++", "code": "template <typename T> \nstruct array { \n size_t x; \n T *ary; \n}; \n"}, {"idx": "webquery-test-11", "doc": "Why use !! when converting int to bool?", "code": "bool isNonZero = (integerValue != 0);"}, {"idx": "webquery-test-12", "doc": "Post-increment and Pre-increment concept?", "code": "++x\nxxx++\nxxx++x++x++"}, {"idx": "webquery-test-13", "doc": "c++ integer->std::string conversion. Simple function?", "code": "#include <string>\nstring s = std::to_string(123);\n"}, {"idx": "webquery-test-14", "doc": "How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?", "code": "std::vector#include <vector>\n\nstruct base\n{\n virtual ~base() {}\n};\n\nstruct derived : base {};\n\ntypedef std::vector<base*> container;\n\nvoid foo()\n{\n container c;\n\n for (unsigned i = 0; i < 100; ++i)\n c.push_back(new derived());\n\n} // leaks here! frees the pointers, doesn't delete them (nor should it)\n\nint main()\n{\n foo();\n}\n#include <algorithm>\n#include <vector>\n\nstruct base\n{\n virtual ~base() {}\n};\n\nstruct derived : base {};\n\ntypedef std::vector<base*> container;\n\ntemplate <typename T>\nvoid delete_pointed_to(T* const ptr)\n{\n delete ptr;\n}\n\nvoid foo()\n{\n container c;\n\n for (unsigned i = 0; i < 100; ++i)\n c.push_back(new derived());\n\n // free memory\n std::for_each(c.begin(), c.end(), delete_pointed_to<base>);\n}\n\nint main()\n{\n foo();\n}\nstd::unique_ptrstd::unique_ptrstd::unique_ptrauto myresource = /*std::*/make_unique<derived>(); // won't leak, frees itself\nstd::make_uniquestd::make_uniquestd::make_uniquestd::unique_ptr<derived> myresource(new derived());\nauto x = myresource; // error, cannot copy\nauto y = std::move(myresource); // okay, now myresource is empty\n#include <memory>\n#include <vector>\n\nstruct base\n{\n virtual ~base() {}\n};\n\nstruct derived : base {};\n\ntypedef std::vector<std::unique_ptr<base>> container;\n\nvoid foo()\n{\n container c;\n\n for (unsigned i = 0; i < 100; ++i)\n c.push_back(make_unique<derived>());\n\n} // all automatically freed here\n\nint main()\n{\n foo();\n}\nshared_ptrshared_ptrshared_ptrshared_ptrshared_ptr#include <memory>\n#include <vector>\n\nstruct base\n{\n virtual ~base() {}\n};\n\nstruct derived : base {};\n\ntypedef std::vector<std::shared_ptr<base>> container;\n\nvoid foo()\n{\n container c;\n\n for (unsigned i = 0; i < 100; ++i)\n c.push_back(std::make_shared<derived>());\n\n} // all automatically freed here\n\nint main()\n{\n foo();\n}\nstd::unique_ptrstd::unique_ptrstd::unique_ptrboost::ptr_container#include <boost/ptr_container/ptr_vector.hpp>\n\nstruct base\n{\n virtual ~base() {}\n};\n\nstruct derived : base {};\n\n// hold pointers, specially\ntypedef boost::ptr_vector<base> container;\n\nvoid foo()\n{\n container c;\n\n for (int i = 0; i < 100; ++i)\n c.push_back(new Derived());\n\n} // all automatically freed here\n\nint main()\n{\n foo();\n}\nboost::ptr_vector<T>boost::ptr_vector<T>std::vector<std::shared_ptr<T>>"}, {"idx": "webquery-test-1", "doc": "Why are global and static variables initialized to their default values?", "code": "autoauto"}, {"idx": "webquery-test-2", "doc": "Is there a portable equivalent to DebugBreak()/__debugbreak?", "code": "raise(SIGTRAP);\n"}, {"idx": "webquery-test-3", "doc": "BSTR to std::string (std::wstring) and vice versa", "code": "BSTRBSTR// given BSTR bs\nassert(bs != nullptr);\nstd::wstring ws(bs, SysStringLen(bs));\nstd::wstringstd::wstring// given std::wstring ws\nassert(!ws.empty());\nBSTR bs = SysAllocStringLen(ws.data(), ws.size());\nstd::basic_string<typename CharT>::basic_string(const CharT*, size_type)std::basic_string<typename CharT>::basic_string(const CharT*, size_type)std::basic_string<typename CharT>::basic_string(const CharT*, size_type)std::basic_string<typename CharT>::basic_string(const CharT*, size_type)std::basic_string<typename CharT>::basic_string(const CharT*, size_type)std::basic_string<typename CharT>::basic_string(const CharT*, size_type)"}, {"idx": "webquery-test-4", "doc": "A lambda's return type can be deduced by the return value, so why can't a function's?", "code": "-std=c++1ydecltype(auto)decltype(auto)decltype(auto)decltype(auto)template<typename function_type, typename... arg_types>\ndecltype(auto) do_nothing_but_forward(function_type func, arg_types&&... args) {\n return func(std::forward<arg_types>(args)...);\n}\ndecltype(auto)decltype(auto)"}, {"idx": "webquery-test-5", "doc": "What does '&' do in a C++ declaration?", "code": "foo(string const& myname) \nfoo(string const* myname)\nconst string &GetMethodName() { ... }\nclass A\n{\n public:\n int bar() const {return someValue;}\n //Big, expensive to copy class\n}\n\nclass B\n{\npublic:\n A const& getA() { return mA;}\nprivate:\n A mA;\n}\nvoid someFunction()\n{\n B b = B();\n //Access A, ability to call const functions on A\n //No need to check for null, since reference is guaranteed to be valid.\n int value = b.getA().bar(); \n}\nint const& foo() \n{\n int a;\n\n //This is very bad, returning reference to something on the stack. This will\n //crash at runtime.\n return a; \n}\n"}, {"idx": "webquery-test-6", "doc": "How bad is \"if (!this)\" in a C++ member function?", "code": "CThingy *CLookupThingy::Lookup( name ) \n{\n#if !defined(DEBUG)\n if (!this)\n {\n return NULL;\n }\n#endif\n // else do the lookup code...\n}\n"}, {"idx": "webquery-test-7", "doc": "Should mutexes be mutable?", "code": "Mutex mutex ;\n\nint foo(const Object & object)\n{\n Lock<Mutex> lock(mutex) ;\n return object.read() ;\n}\ntemplate <typename T>\nclass Mutexed : public T\n{\n public :\n Mutexed() : T() {}\n // etc.\n\n void lock() { this->m_mutex.lock() ; }\n void unlock() { this->m_mutex.unlock() ; } ;\n\n private :\n Mutex m_mutex ;\n}\nint foo(const Mutexed<Object> & object)\n{\n Lock<Mutexed<Object> > lock(object) ;\n return object.read() ;\n}\nobjectobjectobjectconstconstconstconstconstconsttemplate <typename T>\nclass Mutexed : public T\n{\n public :\n Mutexed() : T() {}\n // etc.\n\n void lock() const { this->m_mutex.lock() ; }\n void unlock() const { this->m_mutex.unlock() ; } ;\n\n private :\n mutable Mutex m_mutex ;\n}\nmutableconstconst"}, {"idx": "webquery-test-8", "doc": "Why use std::bind over lambdas in C++14?", "code": "auto f1 = std::bind(f, 42, _1, std::move(v));\nauto f1 = std::bind(f, 42, _1, std::move(v));\nauto f1 = [v = std::move(v)](auto arg) { f(42, arg, std::move(v)); };\nauto f1 = [v = std::move(v)](auto arg) { f(42, arg, std::move(v)); };\nauto f1 = [v = std::move(v)](auto arg) { f(42, arg, std::move(v)); };\nvoid f(int); void f(char); auto f1 = std::bind(f, _1, 42);\n"}, {"idx": "webquery-test-9", "doc": "Should I copy an std::function or can I always take a reference to it?", "code": "std::functionconstconstconstconst"}, {"idx": "webquery-test-10", "doc": "Argument order to std::min changes compiler output for floating-point", "code": "minsd a,bminsd a,bminsd a,bminsd a,bminsd a,bminsd a,bminsd a,bminsd a,bminsd a,bstd::minstd::minstd::minstd::minstd::minNaN<bNaN<bNaN<bNaN<bNaN<b-ffast-math-ffast-math-ffast-math-fno-math-errno-fno-math-errno-fno-math-errno-fno-math-errnostd::minstd::minclang -funsafe-math-optimizations -ffinite-math-only"}, {"idx": "webquery-test-11", "doc": "How can I have multiple parameter packs in a variadic template?", "code": "#include <iostream>\n\ntemplate <typename... Types>\nstruct foo {};\n\ntemplate < typename... Types1, template <typename...> class T\n , typename... Types2, template <typename...> class V\n , typename U >\nvoid\nbar(const T<Types1...>&, const V<Types2...>&, const U& u)\n{\n std::cout << sizeof...(Types1) << std::endl;\n std::cout << sizeof...(Types2) << std::endl;\n std::cout << u << std::endl;\n}\n\nint\nmain()\n{\n foo<char, int, float> f1;\n foo<char, int> f2;\n bar(f1, f2, 9);\n return 0;\n}\n"}, {"idx": "webquery-test-1", "doc": "How do I make this C++ object non-copyable?", "code": "class Foo {\n private:\n Foo();\n Foo( const Foo& ); // non construction-copyable\n Foo& operator=( const Foo& ); // non copyable\n public:\n static Foo* create();\n}\nclass Foo {\n private:\n Foo();\n public:\n Foo( const Foo& ) = delete; // non construction-copyable\n Foo& operator=( const Foo& ) = delete; // non copyable\n\n static Foo* create();\n}\n"}, {"idx": "webquery-test-2", "doc": "Using std::max_element on a vector<double>", "code": "min_elementmin_elementmin_elementmin_element"}, {"idx": "webquery-test-3", "doc": "How to generate assembly code with clang in Intel syntax?", "code": "-masm=intelclang++ -S -mllvm --x86-asm-syntax=intel test.cpp\n-mllvm <arg>"}, {"idx": "webquery-test-4", "doc": "Loop with a zero execution time", "code": "int main()\n{\n int j = 0 ;\n for( int i = 0; i < 10000; ++i )\n {\n ++j ;\n }\n}\ngcc 4.9gcc 4.9main:\n xorl %eax, %eax #\n ret\n#include <stdio.h>\n\nint main()\n{\n int j = 0 ;\n if( false ) // The loop will never execute\n {\n for( int i = 0; i < 10000; ++i )\n {\n printf( \"%d\\n\", j ) ;\n ++j ;\n }\n }\n}\nint j = 0 ;\nfor( int i = 0; i < 10000; ++i )\n{\n ++j ;\n}\nprintf( \"%d\\n\", j ) ;\nmovl $10000, %esi #,\nmovl $.LC0, %edi #,\nxorl %eax, %eax #\ncall printf #\n5.1.2.3gccgcc"}, {"idx": "webquery-test-5", "doc": "What does the compiler do here: int a = b * (c * d * + e)?", "code": "+"}, {"idx": "webquery-test-6", "doc": "How to copy std::string into std::vector<char>?", "code": "std::vectorstd::string str = \"hello\";\nstd::vector<char> data(str.begin(), str.end());\nstd::string str = \"hello\";\nstd::vector<char> data = /* ... */;\nstd::copy(str.begin(), str.end(), std::back_inserter(data));\n"}, {"idx": "webquery-test-7", "doc": "Reader/Writer Locks in C++", "code": "#include <shared_mutex>\n\ntypedef std::shared_mutex Lock;\ntypedef std::unique_lock< Lock > WriteLock;\ntypedef std::shared_lock< Lock > ReadLock;\n\nLock myLock;\n\nvoid ReadFunction()\n{\n ReadLock r_lock(myLock);\n //Do reader stuff\n}\n\nvoid WriteFunction()\n{\n WriteLock w_lock(myLock);\n //Do writer stuff\n}\n#include <boost/thread/locks.hpp>\n#include <boost/thread/shared_mutex.hpp>\n\ntypedef boost::shared_mutex Lock;\ntypedef boost::unique_lock< Lock > WriteLock;\ntypedef boost::shared_lock< Lock > ReadLock;\n"}, {"idx": "webquery-test-8", "doc": "'vector' in namespace 'std' does not name a type", "code": "vector#include <vector>\n"}, {"idx": "webquery-test-9", "doc": "C++: Life span of temporary arguments?", "code": ";;;;;constMyClass getMyClass();\n\n{\n const MyClass& r = getMyClass(); // full expression ends here\n ...\n} // object returned by getMyClass() is destroyed here\nMyClass obj = getMyClass();"}, {"idx": "webquery-test-1", "doc": "How to speed up g++ compile time (when using a lot of templates)", "code": "-j3-j3"}, {"idx": "webquery-test-2", "doc": "Store derived class objects in base class variables", "code": "vector<Base*> \nC++ish"}, {"idx": "webquery-test-3", "doc": "virtual assignment operator C++", "code": "operator=B::operator=(const B& right)B::operator=(const B& right)class B\n{\npublic:\n virtual B& operator=(const B& right)\n {\n x = right.x;\n return *this;\n }\n\n int x;\n\n};\n\nclass D : public B\n{\npublic:\n virtual D& operator=(const D& right)\n {\n x = right.x;\n y = right.y;\n return *this;\n }\n int y;\n};\nD::operator=(const D& right)D::operator=(const B& right)//Use same B as above\n\nclass D : public B\n{\npublic:\n virtual D& operator=(const D& right)\n {\n x = right.x;\n y = right.y;\n return *this;\n }\n\n\n virtual B& operator=(const B& right)\n {\n x = right.x;\n y = 13;//Default value\n return *this;\n }\n\n int y;\n};\n\n\nint main(int argc, char **argv) \n{\n D d1;\n B &b1 = d1;\n d1.x = 99;\n d1.y = 100;\n printf(\"d1.x d1.y %i %i\\n\", d1.x, d1.y);\n\n D d2;\n B &b2 = d2;\n b2 = b1;\n printf(\"d2.x d2.y %i %i\\n\", d2.x, d2.y);\n return 0;\n}\nd1.x d1.y 99 100\nd2.x d2.y 99 13\nD::operator=(const D& right)B::operator=(const B& right)B::operator=(const B& right)virtual B& operator=(const B& right)\n{\n const D *pD = dynamic_cast<const D*>(&right);\n if(pD)\n {\n x = pD->x;\n y = pD->y;\n }\n else\n {\n x = right.x;\n y = 13;//default value\n }\n\n return *this;\n}\n"}, {"idx": "webquery-test-4", "doc": "g++ linker: force static linking if static library exists?", "code": "g++ -Wl,-Bstatic -lz -lfoo -Wl,-Bdynamic -lbar -Wl,--as-needed\nzlibzlibzlibzlib"}, {"idx": "webquery-test-5", "doc": "What is an iterator's default value?", "code": "container.end() std::vector<X>::iterator iter = std::find(my_vec.begin(), my_vec.end(), x);\n if (iter == my_vec.end()) {\n //no result found; iter points to \"nothing\"\n }\n std::vector<X>::iterator iter; //no particular value\n iter = some_vector.begin(); //iter is now usable\nistream_iteratoristream_iterator"}, {"idx": "webquery-test-6", "doc": "How does the standard library implement std::swap?", "code": "std::swapstd::swaptemplate<typename T> void swap(T& t1, T& t2) {\n T temp = std::move(t1); // or T temp(std::move(t1));\n t1 = std::move(t2);\n t2 = std::move(temp);\n}\nstd::swapstd::swapswapstd::moveswap"}, {"idx": "webquery-test-7", "doc": "Operator overloading outside class", "code": "operator+()string a = \"bar\";\nstring b = \"foo\" + a;\nchar * \"foo\"char * \"foo\"char * \"foo\""}, {"idx": "webquery-test-8", "doc": "'cl' is not recognized as an internal or external command,", "code": "clvcvarsall.batvcvarsall.bat amd64_arm uwp\nx86x86x86x86x86x86x86x86x86x86x86x86x86"}, {"idx": "webquery-test-9", "doc": "Are there practical uses for dynamic-casting to void pointer?", "code": "dynamic_cast<void*>()#include <iostream>\n\nclass B {\npublic:\n virtual ~B() {}\n};\n\nclass D1 : public B {\n};\n\nclass D2 : public B {\n};\n\nclass DD : public D1, public D2 {\n};\n\nnamespace {\n bool eq(B* b1, B* b2) {\n return b1 == b2;\n }\n\n bool eqdc(B* b1, B *b2) {\n return dynamic_cast<void*>(b1) == dynamic_cast<void*>(b2);\n }\n};\n\nint\nmain() {\n DD *dd = new DD();\n D1 *d1 = dynamic_cast<D1*>(dd);\n D2 *d2 = dynamic_cast<D2*>(dd);\n\n std::cout << \"eq: \" << eq(d1, d2) << \", eqdc: \" << eqdc(d1, d2) << \"\\n\";\n return 0;\n}\neq: 0, eqdc: 1\n"}, {"idx": "webquery-test-10", "doc": "Can I use Qt without qmake or Qt Creator?", "code": "CXXFLAGS += -Ipath_to_your_qt_includes\nLDFLAGS += -Lpath_to_your_qt_libs\n\nLDLIBS += -lqt-mt (for Qt3)\nLDLIBS += -lQtCore -lQtGui (for Qt4, add what you need)\n\nmy_prog: my_prog.cpp\nmocm%.cpp: %.h\n moc $< -o $@\n%.moc.cpp%.moc.cpp%.moc.cpp%.moc.cppmy_prog: my_prog.cpp my_prog.moc.cpp\nmy_prog: my_prog.o my_prog.moc.o my_prog.ui.o\n $(CXX) $(LDFLAGS) -o my_prog $^ $(LDLIBS)\n\nmy_prog.o: my_prog.cpp my_prog.ui.h\n"}, {"idx": "webquery-test-11", "doc": "Tools to find included headers which are unused?", "code": "// f1.h\nvoid foo (char);\n\n// f2.h\nvoid foo (int);\n\n\n// bar.cc\n#include \"f1.h\"\n#include \"f2.h\"\n\nint main ()\n{\n foo (0); // Calls 'foo(int)' but all functions were in overload set\n}\n// f1.h\ntemplate <typename T>\nvoid foo (T);\n\n// f2.h\ntemplate <>\nvoid foo (int);\n\n// bar.cc\n#include \"f1.h\"\n#include \"f2.h\"\n\n\nint main ()\n{\n foo (0); // Calls specialization 'foo<int>(int)'\n}\n// A.h\nclass A { };\n\n// foo.h\n#include \"A.h\"\nvoid foo (A const &);\n\n// bar.cc\n#include \"foo.h\"\n\nvoid bar (A const & a)\n{\n foo (a);\n}\n// foo.h\nclass A;\nvoid foo (A const &);\n"}, {"idx": "webquery-test-1", "doc": "How do I specify an integer literal of type unsigned char in C++?", "code": "inline constexpr unsigned char operator \"\" _uchar( unsigned long long arg ) noexcept\n{\n return static_cast< unsigned char >( arg );\n}\n\nunsigned char answer()\n{\n return 42;\n}\n\nint main()\n{\n std::cout << std::min( 42, answer() ); // Compile time error!\n std::cout << std::min( 42_uchar, answer() ); // OK\n}\n"}, {"idx": "webquery-test-2", "doc": "Py_Initialize fails - unable to load the file system codec", "code": "PYTHONPATHPYTHONPATH"}, {"idx": "webquery-test-3", "doc": "How to publicly inherit from a base class but make some of public methods from the base class private in the derived class?", "code": "Base::bar;Base::bar;class Base {\npublic:\n void foo(){}\n void bar(){}\n};\n\nclass Derived : public Base {\nprivate:\n using Base::bar;\n};\nclass Base {\npublic:\n void foo(){}\n void bar(){}\n};\n\nclass Derived : private Base {\npublic:\n using Base::foo;\n};\n"}, {"idx": "webquery-test-4", "doc": "Dereference vector pointer to access element", "code": "intint a = (*vecPtr)[i];\nvector<int>& vecRef = *vecPtr; // vector is not copied here\nint a = vecRef[i];\nvectorvectorvectorvectorvector"}, {"idx": "webquery-test-5", "doc": "understanding of pthread_cond_wait() and pthread_cond_signal()", "code": "pthread_cond_signalpthread_cond_waitthread 1:\n pthread_mutex_lock(&mutex);\n while (!condition)\n pthread_cond_wait(&cond, &mutex);\n /* do something that requires holding the mutex and condition is true */\n pthread_mutex_unlock(&mutex);\n\nthread2:\n pthread_mutex_lock(&mutex);\n /* do something that might make condition true */\n pthread_cond_signal(&cond);\n pthread_mutex_unlock(&mutex);\n"}, {"idx": "webquery-test-6", "doc": "How can I make CMake use GCC instead of Clang on Mac OS X?", "code": "CCCCCCCCcmake -DCMAKE_C_COMPILER=/usr/bin/gcc -DCMAKE_CXX_COMPILER=/usr/bin/g++ ...\n"}, {"idx": "webquery-test-7", "doc": "Returning a const reference to an object instead of a copy", "code": "foo *pFoo = new foo;\nconst std::string &myName = pFoo->getName();\ndelete pFoo;\ncout << myName; // error! dangling reference\n"}, {"idx": "webquery-test-8", "doc": "When should I use raw pointers over smart pointers?", "code": "shared_ptrshared_ptrvoid PrintObject(shared_ptr<const Object> po) //bad\n{\n if(po)\n po->Print();\n else\n log_error();\n}\n\nvoid PrintObject(const Object* po) //good\n{\n if(po)\n po->Print();\n else\n log_error();\n}\nObject* createObject() //bad\n{\n return new Object;\n}\n\nsome_smart_ptr<Object> createObject() //good\n{\n return some_smart_ptr<Object>(new Object);\n}\n"}, {"idx": "webquery-test-9", "doc": "Static library debug symbols", "code": "/ZI/ZI/ZI/ZI/ZI/ZI/ZI/ZI/ZI/ZI"}, {"idx": "webquery-test-10", "doc": "How does weak_ptr work?", "code": "shared_ptrshared_ptrshared_ptrweak_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptrshared_ptr"}, {"idx": "webquery-test-11", "doc": "Detect Windows or Linux in C, C++", "code": "#ifdef _WIN32\n#include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n\n#define DIV 1048576 \n#define WIDTH 7\n#endif\n\n#ifdef linux\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#endif\n\n\nint main(int argc, char *argv[]) \n{\n#ifdef _WIN32\nMEMORYSTATUSEX statex;\n statex.dwLength = sizeof (statex);\n GlobalMemoryStatusEx (&statex);\n\n _tprintf (TEXT(\"There is %*ld %% of memory in use.\\n\"),\n WIDTH, statex.dwMemoryLoad);\n#endif\n\n#ifdef linux\nchar cmd[30];\nint flag = 0; \nFILE *fp;\nchar line[130]; \nint TotalMem, TotalFree, TotalUsed;\n\nflag=0;\nmemcpy (cmd,\"\\0\",30);\nsprintf(cmd,\"free -t -m|grep Total\"); \nfp = popen(cmd, \"r\"); \nwhile ( fgets( line, sizeof line, fp))\n{ \n flag++;\n sscanf(line,\"%*s %d %d %d\",&TotalMem, &TotalUsed, &TotalFree);\n}\npclose(fp); \n\nif(flag)\n printf(\"TotalMem:%d -- TotalUsed:%d -- TotalFree:%d\\n\",TotalMem,TotalUsed,TotalFree);\nelse \n printf(\"not found\\n\");\n#endif\n\n return 0;\n}\n"}, {"idx": "webquery-test-1", "doc": "Why is the code in most STL implementations so convoluted?", "code": "__MY_FILE_H"}, {"idx": "webquery-test-2", "doc": "How to make a function return a pointer to a function? (C++)", "code": "int f(char) {\n return 0;\n}\n\nint (*return_f())(char) {\n return f;\n}\n"}, {"idx": "webquery-test-3", "doc": "iterate vector, remove certain items as I go", "code": "erase()std::vector<std::string>::iterator iter;\nfor (iter = m_vPaths.begin(); iter != m_vPaths.end(); ) {\n if (::DeleteFile(iter->c_str()))\n iter = m_vPaths.erase(iter);\n else\n ++iter;\n}\n"}, {"idx": "webquery-test-4", "doc": "Reverse iteration with an unsigned loop variable", "code": "for (size_t i = n; i --> 0 ;)\n-1"}, {"idx": "webquery-test-5", "doc": "Can we have recursive macros?", "code": "pr(5)pr(5)\n^\npr((5==1)? 1 : pr(5-1))\n ^\n# define EMPTY(...)\n# define DEFER(...) __VA_ARGS__ EMPTY()\n# define OBSTRUCT(...) __VA_ARGS__ DEFER(EMPTY)()\n# define EXPAND(...) __VA_ARGS__\n\n# define pr_id() pr\n# define pr(n) ((n==1)? 1 : DEFER(pr_id)()(n-1))\npr(5) // Expands to ((5==1)? 1 : pr_id ()(5 -1))\nprEXPAND(pr(5)) // Expands to ((5==1)? 1 : ((5 -1==1)? 1 : pr_id ()(5 -1 -1)))\nEXPAND(EXPAND(pr(5))) // Expands to ((5==1)? 1 : ((5 -1==1)? 1 : ((5 -1 -1==1)? 1 : pr_id ()(5 -1 -1 -1))))\n#define EVAL(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))\n#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))\n#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))\n#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))\n#define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__)))\n#define EVAL5(...) __VA_ARGS__\n#define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)\n#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__\n#define INC(x) PRIMITIVE_CAT(INC_, x)\n#define INC_0 1\n#define INC_1 2\n#define INC_2 3\n#define INC_3 4\n#define INC_4 5\n#define INC_5 6\n#define INC_6 7\n#define INC_7 8\n#define INC_8 9\n#define INC_9 9\n\n#define DEC(x) PRIMITIVE_CAT(DEC_, x)\n#define DEC_0 0\n#define DEC_1 0\n#define DEC_2 1\n#define DEC_3 2\n#define DEC_4 3\n#define DEC_5 4\n#define DEC_6 5\n#define DEC_7 6\n#define DEC_8 7\n#define DEC_9 8\n#define CHECK_N(x, n, ...) n\n#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)\n\n#define NOT(x) CHECK(PRIMITIVE_CAT(NOT_, x))\n#define NOT_0 ~, 1,\n\n#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)\n#define COMPL_0 1\n#define COMPL_1 0\n\n#define BOOL(x) COMPL(NOT(x))\n\n#define IIF(c) PRIMITIVE_CAT(IIF_, c)\n#define IIF_0(t, ...) __VA_ARGS__\n#define IIF_1(t, ...) t\n\n#define IF(c) IIF(BOOL(c))\n\n#define EAT(...)\n#define EXPAND(...) __VA_ARGS__\n#define WHEN(c) IF(c)(EXPAND, EAT)\n#define REPEAT(count, macro, ...) \\\n WHEN(count) \\\n ( \\\n OBSTRUCT(REPEAT_INDIRECT) () \\\n ( \\\n DEC(count), macro, __VA_ARGS__ \\\n ) \\\n OBSTRUCT(macro) \\\n ( \\\n DEC(count), __VA_ARGS__ \\\n ) \\\n )\n#define REPEAT_INDIRECT() REPEAT\n\n//An example of using this macro\n#define M(i, _) i\nEVAL(REPEAT(8, M, ~)) // 0 1 2 3 4 5 6 7\n"}, {"idx": "webquery-test-6", "doc": "Constant-sized vector", "code": "std::vector<int> v(10);\nv.size(); //returns 10\nstd::vector<int> v;\nv.reserve(10);\nv.size(); //returns 0\n"}, {"idx": "webquery-test-7", "doc": "Generate sha256 with OpenSSL and C++", "code": "void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])\n{\n int i = 0;\n\n for(i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n sprintf(outputBuffer + (i * 2), \"%02x\", hash[i]);\n }\n\n outputBuffer[64] = 0;\n}\n\n\nvoid sha256_string(char *string, char outputBuffer[65])\n{\n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, string, strlen(string));\n SHA256_Final(hash, &sha256);\n int i = 0;\n for(i = 0; i < SHA256_DIGEST_LENGTH; i++)\n {\n sprintf(outputBuffer + (i * 2), \"%02x\", hash[i]);\n }\n outputBuffer[64] = 0;\n}\n\nint sha256_file(char *path, char outputBuffer[65])\n{\n FILE *file = fopen(path, \"rb\");\n if(!file) return -534;\n\n unsigned char hash[SHA256_DIGEST_LENGTH];\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n const int bufSize = 32768;\n unsigned char *buffer = malloc(bufSize);\n int bytesRead = 0;\n if(!buffer) return ENOMEM;\n while((bytesRead = fread(buffer, 1, bufSize, file)))\n {\n SHA256_Update(&sha256, buffer, bytesRead);\n }\n SHA256_Final(hash, &sha256);\n\n sha256_hash_string(hash, outputBuffer);\n fclose(file);\n free(buffer);\n return 0;\n}\nstatic unsigned char buffer[65];\nsha256(\"string\", buffer);\nprintf(\"%s\\n\", buffer);\n"}, {"idx": "webquery-test-8", "doc": "Concurrency: Atomic and volatile in C++11 memory model", "code": "volatilevolatilevolatilevolatilestd::atomic<int> ai;\naistd::memory_order_seq_cststd::memory_order_seq_cstxxxxx=1x=1x=1x=1x=1x=1std::memory_order_relaxedstd::memory_order_relaxedexchange()exchange()exchange()exchange()"}, {"idx": "webquery-test-1", "doc": "Is it possible to force a function not to be inlined?", "code": "__declspec(noinline)class X {\n __declspec(noinline) int member_func() {\n return 0; \n }\n};\n/clr"}, {"idx": "webquery-test-2", "doc": "Why does this delay-loop start to run faster after several iterations with no sleep?", "code": "usleepusleepintintclock()clock()runrunrunrunaddaddcall"}, {"idx": "webquery-test-3", "doc": "With \"-fno-exceptions\", what happens with \"new T\"?", "code": "operator newoperator newnew Tnew T-fno-exception-fno-exception-fno-exceptionnew Tnew T"}, {"idx": "webquery-test-4", "doc": "When does Endianness become a factor?", "code": "read()read()uint32_t n = get_number();\n\nunsigned char bytesLE[4] = { n, n >> 8, n >> 16, n >> 24 }; // little-endian order\nunsigned char bytesBE[4] = { n >> 24, n >> 16, n >> 8, n }; // big-endian order\n\nwrite(bytes..., 4);\nreinterpret_cast<unsigned char *>(&n)unsigned char buf[4] = read_data();\n\nuint32_t n_LE = buf[0] + buf[1] << 8 + buf[2] << 16 + buf[3] << 24; // little-endian\nuint32_t n_BE = buf[3] + buf[2] << 8 + buf[1] << 16 + buf[0] << 24; // big-endian\nuint32_t n = *reinterpret_cast<uint32_t*>(buf)double"}, {"idx": "webquery-test-5", "doc": "Template typedefs - What's your work around?", "code": "template <typename T>\nstruct my_string_map {\n typedef std::map<std::string, T> type;\n};\n\n// Invoke:\n\nmy_string_map<int>::type my_str_int_map;\nallocator::rebind<U>"}, {"idx": "webquery-test-6", "doc": "Destructor called after throwing from a constructor", "code": "X(int)X(int)X(int)[C++11: 15.2/2]:"}, {"idx": "webquery-test-7", "doc": "Clang-format line breaks", "code": "libclangstd::vector<std::string> get_vec()\n{\n return std::vector<std::string> { //\n \"this is a test\", //\n \"some of the lines are longer\", //\n \"than other, but I would like\", //\n \"to keep them on separate lines\" //\n };\n}\n// clang-format off// clang-format offclang-formatstatic luaL_Reg const methods[] = {\n {\"matches\", &dispatch::intf_match_unit},\n {\"to_recall\", &dispatch::intf_put_recall_unit},\n {\"to_map\", &dispatch::intf_put_unit},\n {\"erase\", &dispatch::intf_erase_unit},\n {\"clone\", intf_copy_unit},\n {\"extract\", &dispatch::intf_extract_unit},\n {\"advance\", intf_advance_unit},\n};\n constexpr float shadow_skew_hardcoded[16] =\n { 1.0f, 0.0f, 0.0f, 0.0f,\n 0.5f, 0.5f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f };\n"}, {"idx": "webquery-test-8", "doc": "Is the compiler allowed to optimize out heap memory allocations?", "code": "N3664N36645newnew#include <cstddef>\n\nextern void* operator new(std::size_t n);\n\ntemplate<typename T>\nT* create() { return new T(); }\n\nint main() {\n auto result = 0;\n for (auto i = 0; i < 1000000; ++i) {\n result += (create<int>() != nullptr);\n }\n\n return result;\n}\nmain: # @main\n movl $1000000, %eax # imm = 0xF4240\n ret\n"}, {"idx": "webquery-test-9", "doc": "Using libstdc++ compiled libraries with clang++ -stdlib=libc++", "code": "std::stringstd::stringstd::stringstd::stringstd::stringstd::stringstd::stringstd::std::std::"}, {"idx": "webquery-test-10", "doc": "Why don't I need to specify \"typename\" before a dependent type in C++20?", "code": "typenametypenametypenamestatic_casttemplate <typename T> struct X : T::type { }; // always ok\n"}, {"idx": "webquery-test-11", "doc": "How to write custom input stream in C++", "code": "std::streambufstd::streambufstd::streambufstd::streambufstd::streambufclass compressbuf\n : public std::streambuf {\n std::streambuf* sbuf_;\n char* buffer_;\n // context for the compression\npublic:\n compressbuf(std::streambuf* sbuf)\n : sbuf_(sbuf), buffer_(new char[1024]) {\n // initialize compression context\n }\n ~compressbuf() { delete[] this->buffer_; }\n int underflow() {\n if (this->gptr() == this->egptr()) {\n // decompress data into buffer_, obtaining its own input from\n // this->sbuf_; if necessary resize buffer\n // the next statement assumes \"size\" characters were produced (if\n // no more characters are available, size == 0.\n this->setg(this->buffer_, this->buffer_, this->buffer_ + size);\n }\n return this->gptr() == this->egptr()\n ? std::char_traits<char>::eof()\n : std::char_traits<char>::to_int_type(*this->gptr());\n }\n};\nunderflow()underflow()std::istreamstd::ifstream fin(\"some.file\");\ncompressbuf sbuf(fin.rdbuf());\nstd::istream in(&sbuf);\nicompressstreamicompressstreamicompressstreamicompressstreamstruct compressstream_base {\n compressbuf sbuf_;\n compressstream_base(std::streambuf* sbuf): sbuf_(sbuf) {}\n};\nclass icompressstream\n : virtual compressstream_base\n , public std::istream {\npublic:\n icompressstream(std::streambuf* sbuf)\n : compressstream_base(sbuf)\n , std::ios(&this->sbuf_)\n , std::istream(&this->sbuf_) {\n }\n};\n"}, {"idx": "webquery-test-1", "doc": "Why is sizeof(unsigned double) equal to 4?", "code": "unsigned doublewarning C4076: 'unsigned' : can not be used with type 'double'doubledoubledoubledoubleunsigned double a = 1.0;\nwarning C4076: 'unsigned' : can not be used with type 'double'\nwarning C4244: 'initializing' : conversion from 'double' to 'unsigned int', possible loss of data\n"}, {"idx": "webquery-test-2", "doc": "How do I get the intersection between two arrays as a new array?", "code": "foreach element e in array A\n insert e into hash table H\n\nforeach element e in array B\n if H contains e \n print e\nO(N)O(N)"}, {"idx": "webquery-test-3", "doc": "CMake with include and source paths - basic setup", "code": "CMakeLists.txtroot\n|-MainProject\n| |-inc\n| | '-main.h\n| |-src\n| | |-main.cpp\n| | '-CMakeLists.txt\n| '-CMakeLists.txt \n|-LibProject\n| |-inc\n| | '-test.h\n| |-src\n| | |-test.cpp\n| | '-CMakeLists.txt\n| '-CMakeLists.txt\n'-CMakeLists.txt\nroot/CMakeLists.txtproject(MyProject)\nadd_subdirectory(MainProject)\nadd_subdirectory(LibProject)\nLibProject/CMakeLists.txtLibProject/CMakeLists.txtadd_subdirectory(src)\nLibProject/src/CMakeLists.txt# Notice name prefix of this variable, set by CMake according\n# to value given with \"project()\" in the root CMakeLists.txt.\ninclude_directories(${MyProject_SOURCE_DIR}/LibProject/inc)\nadd_library(LibProject test.cpp)\nMainProject/src/CMakeLists.txtinclude_directories(${MyProject_SOURCE_DIR}/MainProject/inc)\n# I assume you want to use LibProject as a library in MainProject.\ninclude_directories(${MyProject_SOURCE_DIR}/LibProject/inc)\nlink_directories(${MyProject_SOURCE_DIR}/LibProject/src)\nadd_executable(MainProject main.cpp)\ntarget_link_libraries(MainProject LibProject)\n$ cd root\n$ mkdir build\n$ cd build\n$ cmake ..\n$ make\n"}, {"idx": "webquery-test-4", "doc": "How to check if a CPU supports the SSE3 instruction set?", "code": "#ifdef _WIN32\n\n// Windows\n#define cpuid(info, x) __cpuidex(info, x, 0)\n\n#else\n\n// GCC Intrinsics\n#include <cpuid.h>\nvoid cpuid(int info[4], int InfoType){\n __cpuid_count(InfoType, 0, info[0], info[1], info[2], info[3]);\n}\n\n#endif\n// Misc.\nbool HW_MMX;\nbool HW_x64;\nbool HW_ABM; // Advanced Bit Manipulation\nbool HW_RDRAND;\nbool HW_BMI1;\nbool HW_BMI2;\nbool HW_ADX;\nbool HW_PREFETCHWT1;\n\n// SIMD: 128-bit\nbool HW_SSE;\nbool HW_SSE2;\nbool HW_SSE3;\nbool HW_SSSE3;\nbool HW_SSE41;\nbool HW_SSE42;\nbool HW_SSE4a;\nbool HW_AES;\nbool HW_SHA;\n\n// SIMD: 256-bit\nbool HW_AVX;\nbool HW_XOP;\nbool HW_FMA3;\nbool HW_FMA4;\nbool HW_AVX2;\n\n// SIMD: 512-bit\nbool HW_AVX512F; // AVX512 Foundation\nbool HW_AVX512CD; // AVX512 Conflict Detection\nbool HW_AVX512PF; // AVX512 Prefetch\nbool HW_AVX512ER; // AVX512 Exponential + Reciprocal\nbool HW_AVX512VL; // AVX512 Vector Length Extensions\nbool HW_AVX512BW; // AVX512 Byte + Word\nbool HW_AVX512DQ; // AVX512 Doubleword + Quadword\nbool HW_AVX512IFMA; // AVX512 Integer 52-bit Fused Multiply-Add\nbool HW_AVX512VBMI; // AVX512 Vector Byte Manipulation Instructions\n\nint info[4];\ncpuid(info, 0);\nint nIds = info[0];\n\ncpuid(info, 0x80000000);\nunsigned nExIds = info[0];\n\n// Detect Features\nif (nIds >= 0x00000001){\n cpuid(info,0x00000001);\n HW_MMX = (info[3] & ((int)1 << 23)) != 0;\n HW_SSE = (info[3] & ((int)1 << 25)) != 0;\n HW_SSE2 = (info[3] & ((int)1 << 26)) != 0;\n HW_SSE3 = (info[2] & ((int)1 << 0)) != 0;\n\n HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0;\n HW_SSE41 = (info[2] & ((int)1 << 19)) != 0;\n HW_SSE42 = (info[2] & ((int)1 << 20)) != 0;\n HW_AES = (info[2] & ((int)1 << 25)) != 0;\n\n HW_AVX = (info[2] & ((int)1 << 28)) != 0;\n HW_FMA3 = (info[2] & ((int)1 << 12)) != 0;\n\n HW_RDRAND = (info[2] & ((int)1 << 30)) != 0;\n}\nif (nIds >= 0x00000007){\n cpuid(info,0x00000007);\n HW_AVX2 = (info[1] & ((int)1 << 5)) != 0;\n\n HW_BMI1 = (info[1] & ((int)1 << 3)) != 0;\n HW_BMI2 = (info[1] & ((int)1 << 8)) != 0;\n HW_ADX = (info[1] & ((int)1 << 19)) != 0;\n HW_SHA = (info[1] & ((int)1 << 29)) != 0;\n HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0;\n\n HW_AVX512F = (info[1] & ((int)1 << 16)) != 0;\n HW_AVX512CD = (info[1] & ((int)1 << 28)) != 0;\n HW_AVX512PF = (info[1] & ((int)1 << 26)) != 0;\n HW_AVX512ER = (info[1] & ((int)1 << 27)) != 0;\n HW_AVX512VL = (info[1] & ((int)1 << 31)) != 0;\n HW_AVX512BW = (info[1] & ((int)1 << 30)) != 0;\n HW_AVX512DQ = (info[1] & ((int)1 << 17)) != 0;\n HW_AVX512IFMA = (info[1] & ((int)1 << 21)) != 0;\n HW_AVX512VBMI = (info[2] & ((int)1 << 1)) != 0;\n}\nif (nExIds >= 0x80000001){\n cpuid(info,0x80000001);\n HW_x64 = (info[3] & ((int)1 << 29)) != 0;\n HW_ABM = (info[2] & ((int)1 << 5)) != 0;\n HW_SSE4a = (info[2] & ((int)1 << 6)) != 0;\n HW_FMA4 = (info[2] & ((int)1 << 16)) != 0;\n HW_XOP = (info[2] & ((int)1 << 11)) != 0;\n}\nymmymmymmymm"}, {"idx": "webquery-test-5", "doc": "C++ alignment when printing cout <<", "code": "#include <iomanip>#include <iomanip>// using standard iomanip facilities\ncout << setw(20) << \"Artist\"\n << setw(20) << \"Title\"\n << setw(8) << \"Price\";\n// ... not going to try to write the numeric formatting...\n// using Boost.Format\ncout << format(\"%-20s %-20s %-8s\\n\") % \"Artist\" % \"Title\" % \"Price\";\ncout << format(\"%-20s %-20s %8.2f\\n\") % \"Merle\" % \"Blue\" % 12.99;\n"}, {"idx": "webquery-test-6", "doc": "Static variables in C++", "code": "staticstaticstaticstaticstaticstaticstaticstatic"}, {"idx": "webquery-test-7", "doc": "Pointer values are different but they compare equal. Why?", "code": "CCCCccccc"}, {"idx": "webquery-test-8", "doc": "C++, How to determine if a Windows Process is running?", "code": "GetExitCodeProcessGetExitCodeProcess"}, {"idx": "webquery-test-9", "doc": "Pointer to incomplete class type is not allowed", "code": "class Wielrenner;\nclass Wielrenner\n{\n /* class members */\n};\n#include \"wielrenner.h\"#include \"wielrenner.h\""}, {"idx": "webquery-test-10", "doc": "Creating JSON arrays in Boost using Property Trees", "code": "#include <boost/property_tree/ptree.hpp>\nusing boost::property_tree::ptree;\n\nptree pt;\nptree children;\nptree child1, child2, child3;\n\nchild1.put(\"\", 1);\nchild2.put(\"\", 2);\nchild3.put(\"\", 3);\n\nchildren.push_back(std::make_pair(\"\", child1));\nchildren.push_back(std::make_pair(\"\", child2));\nchildren.push_back(std::make_pair(\"\", child3));\n\npt.add_child(\"MyArray\", children);\n\nwrite_json(\"test1.json\", pt);\n{\n \"MyArray\":\n [\n \"1\",\n \"2\",\n \"3\"\n ]\n}\nptree pt;\nptree children;\nptree child1, child2, child3;\n\n\nchild1.put(\"childkeyA\", 1);\nchild1.put(\"childkeyB\", 2);\n\nchild2.put(\"childkeyA\", 3);\nchild2.put(\"childkeyB\", 4);\n\nchild3.put(\"childkeyA\", 5);\nchild3.put(\"childkeyB\", 6);\n\nchildren.push_back(std::make_pair(\"\", child1));\nchildren.push_back(std::make_pair(\"\", child2));\nchildren.push_back(std::make_pair(\"\", child3));\n\npt.put(\"testkey\", \"testvalue\");\npt.add_child(\"MyArray\", children);\n\nwrite_json(\"test2.json\", pt);\n{\n \"testkey\": \"testvalue\",\n \"MyArray\":\n [\n {\n \"childkeyA\": \"1\",\n \"childkeyB\": \"2\"\n },\n {\n \"childkeyA\": \"3\",\n \"childkeyB\": \"4\"\n },\n {\n \"childkeyA\": \"5\",\n \"childkeyB\": \"6\"\n }\n ]\n}\n"}, {"idx": "webquery-test-11", "doc": "Why would one use MACRO+0 !=0", "code": "#iffoofoofoofoofoofoofoofoo#if 42 + 0 - 0\n#if 42 + -\nbar#if SOMETHING_SUPPORTED#if SOMETHING_SUPPORTEDIDENT+0SOMETHING_SUPPORTED -DSOMETHING_SUPPORTED=$SHELL_VAR # oops, SHELL_VAR expanded to nothing\n #define SOMETHING_SUPPORTED /* oops, forgot \"1\" */\n#define#define#define#define #if SOMETHING_SUPPORTED+0\nSOMETHING_SUPPORTED#ifndef SOMETHING_SUPPORTED\n#define SOMETHING_SUPPORTED 0\n#endif\n#if SOMETHING_SUPPORTED#if SOMETHING_SUPPORTED"}, {"idx": "webquery-test-12", "doc": "C++ ifstream error using string as opening file path.", "code": "ifstream file(filename);\nifstream file(filename.c_str());\nifstreamifstreamifstream"}, {"idx": "webquery-test-1", "doc": "What can make C++ RTTI undesirable to use?", "code": "#include \"llvm/Constants.h\"\nusing namespace llvm;\nbool isConstantInt(Value *V) { return isa<ConstantInt>(V); }\n#include \"llvm/Constants.h\"\nusing namespace llvm;\nbool isConstantInt(Value *V) { return dynamic_cast<ConstantInt*>(V) != 0; }\n // (X*2) - X -> X\n if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())))\n return Op1;\n"}, {"idx": "webquery-test-2", "doc": "how to catch unknown exception and print it", "code": "std::exceptiontry\n{\n // code that could cause exception\n}\ncatch (const std::exception &exc)\n{\n // catch anything thrown within try block that derives from std::exception\n std::cerr << exc.what();\n}\nstd::exceptionstd::exceptionstd::exceptiontry\n{\n}\ncatch (...)\n{\n}\n"}, {"idx": "webquery-test-3", "doc": "I cannot pass lambda as std::function", "code": "std::function<...>auto lambda = [](const std::string& s) { return std::stoi(s); };\nstd::function<int(const std::string&)>std::function<int(const std::string&)>int f(std::string const&) {return 0;}\n\nint main()\n{\n std::vector<int> vec;\n C<int> c;\n c.func(vec, f);\n}\nstd::functionstd::function<int(const std::string&)> lambda = [](const std::string& s) { return std::stoi(s); };\nstd::functiontemplate<typename T>\nclass C{\n public:\n void func(std::vector<T>& vec, std::function<T( const std::string)> f){\n //Do Something\n }\n\n // or\n void func(std::vector<T>& vec, std::function<T( const std::string)> const& f){\n //Do Something\n }\n\n // or\n template<typename F> func(std::vector<T>& vec, F f){\n //Do Something\n }\n};\n"}, {"idx": "webquery-test-4", "doc": "C++ Lambdas: Difference between \"mutable\" and capture-by-reference", "code": "xxxa();\nstd::cout << x << \"----\\n\";\nb();\nstd::cout << x << '\\n';\n6\n5\n----\n6\n6\nconstmutable int x = 5;\n auto a = [=]() mutable { ++x; std::cout << x << '\\n'; };\n\n==>\n\n int x = 5;\n\n class __lambda_a {\n int x;\n public:\n __lambda_a () : x($lookup-one-outer$::x) {}\n inline void operator() { ++x; std::cout << x << '\\n'; } \n } a;\n auto b = [&]() { ++x; std::cout << x << '\\n'; };\n\n==>\n\n int x = 5;\n\n class __lambda_b {\n int &x;\n public:\n __lambda_b() : x($lookup-one-outer$::x) {}\n inline void operator() const { ++x; std::cout << x << '\\n'; } \n // ^^^^^\n } b;\nconstconstxxx"}, {"idx": "webquery-test-5", "doc": "how to make an application thread safe?", "code": "boost::mutex m_mutexboost::mutex m_mutex"}, {"idx": "webquery-test-6", "doc": "Do I need to put constexpr after else-if?", "code": "if constexpr (std::is_same_v<int, T>)\n return {a, 0.0};\nelse // {\n if (std::is_same_v<double, T>)\n return {0, a};\n else\n return {0, 0.0};\n// }\nelse if (/*...*/)else if (/*...*/){ /*...*/ }"}, {"idx": "webquery-test-7", "doc": "How does C++ STL unordered_map resolve collisions?", "code": "bucket_countbucket_countbucket_count()bucket_count()std::unordered_setstd::unordered_set"}, {"idx": "webquery-test-8", "doc": "Why is statically linking glibc discouraged?", "code": "dlopendlopendlopenlibc.so.6libc.so.6libc.so.6libc.so.6stdoutstdoutgetaddrinfogetaddrinfogetaddrinfogetaddrinfogetaddrinfoiconviconv"}, {"idx": "webquery-test-9", "doc": "Lambda expressions as class template parameters", "code": "Foo<decltype([]()->void { })> foo;\ndecltypedecltypeauto my_comp = [](const std::string& left, const std::string& right) -> bool {\n // whatever\n}\n\ntypedef std::unordered_map<\n std::string,\n std::string,\n std::hash<std::string>,\n decltype(my_comp)\n > map_type;\n"}, {"idx": "webquery-test-1", "doc": "int vs const int&", "code": "const T&const T&std::vector<T>::push_backstd::vector<T>::push_backstd::vector<T> v;\n...\nif (v.size())\n v.push_back(v[0]); // Add first element also as last element\nstd::vector::push_backvoid std::vector<T>::push_back(T x)void std::vector<T>::push_back(T x)struct P2d\n{ \n double x, y;\n P2d(double x, double y) : x(x), y(y) {}\n P2d& operator+=(const P2d& p) { x+=p.x; y+=p.y; return *this; }\n P2d& operator-=(const P2d& p) { x-=p.x; y-=p.y; return *this; }\n};\n\nstruct Rect\n{\n P2d tl, br;\n Rect(const P2d& tl, const P2d& br) : tl(tl), bt(br) {}\n Rect& operator+=(const P2d& p) { tl+=p; br+=p; return *this; }\n Rect& operator-=(const P2d& p) { tl-=p; br-=p; return *this; }\n};\nP2dP2dmyrect -= myrect.tl;tl -= p;tl -= p;tl -= p;tl -= p;tl -= p;tl -= p;constconst T&constpush_backpush_backpush_backpush_backpush_back"}, {"idx": "webquery-test-2", "doc": "Performance hit from C++ style casts?", "code": "dynamic_castint x;\nfloat f = 123.456;\n\nx = (int) f;\nx = static_cast<int>(f);\n00401041 fld dword ptr [ebp-8]\n00401044 call __ftol (0040110c)\n00401049 mov dword ptr [ebp-4],eax\ndynamic_cast"}, {"idx": "webquery-test-3", "doc": "invalid conversion from `void*' to `char*' when using malloc?", "code": "malloc()char *foo = (char*)malloc(1);\n"}, {"idx": "webquery-test-4", "doc": "What are the definitions for LPARAM and WPARAM?", "code": "LPARAMLPARAMLPARAMLPARAMWPARAMWPARAMWPARAMWPARAM"}, {"idx": "webquery-test-5", "doc": "Why there is no pop_front method in C++ std::vector?", "code": "std::vectorstd::deque"}, {"idx": "webquery-test-6", "doc": "Parallel Loops in C++", "code": "std::vector<std::string> foo;\nstd::for_each(\n std::execution::par,\n foo.begin(),\n foo.end(),\n [](auto&& item)\n {\n //do stuff with item\n });\n"}, {"idx": "webquery-test-7", "doc": "std::set with user defined type, how to ensure no duplicates", "code": "operator==operator==operator==operator==operator=="}, {"idx": "webquery-test-8", "doc": "Illegal token on right side of ::", "code": "maxmaxNOMINMAXNOMINMAX<limits><limits><limits><limits>(std::numeric_limits<T>::max)()std::numeric_limits<T>::min()"}, {"idx": "webquery-test-9", "doc": "casting non const to const in c++", "code": "const_castclass foo {\n int i;\npublic:\n foo(int i) : i(i) { }\n\n int bar() const {\n return i; \n }\n\n int bar() { // not const\n i++;\n return const_cast<const foo*>(this)->bar(); \n }\n};\n"}, {"idx": "webquery-test-10", "doc": "error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj", "code": ".lib.lib.lib.lib"}, {"idx": "webquery-test-1", "doc": "Does C++ support compile-time counters?", "code": "template< size_t n > // This type returns a number through function lookup.\nstruct cn // The function returns cn<n>.\n { char data[ n + 1 ]; }; // The caller uses (sizeof fn() - 1).\n\ntemplate< typename id, size_t n, size_t acc >\ncn< acc > seen( id, cn< n >, cn< acc > ); // Default fallback case.\n\n/* Evaluate the counter by finding the last defined overload.\n Each function, when defined, alters the lookup sequence for lower-order\n functions. */\n#define counter_read( id ) \\\n( sizeof seen( id(), cn< 1 >(), cn< \\\n( sizeof seen( id(), cn< 2 >(), cn< \\\n( sizeof seen( id(), cn< 4 >(), cn< \\\n( sizeof seen( id(), cn< 8 >(), cn< \\\n( sizeof seen( id(), cn< 16 >(), cn< \\\n( sizeof seen( id(), cn< 32 >(), cn< 0 \\\n/* Add more as desired; trimmed for Stack Overflow code block. */ \\\n >() ).data - 1 ) \\\n >() ).data - 1 ) \\\n >() ).data - 1 ) \\\n >() ).data - 1 ) \\\n >() ).data - 1 ) \\\n >() ).data - 1 )\n\n/* Define a single new function with place-value equal to the bit flipped to 1\n by the increment operation.\n This is the lowest-magnitude function yet undefined in the current context\n of defined higher-magnitude functions. */\n#define counter_inc( id ) \\\ncn< counter_read( id ) + 1 > \\\nseen( id, cn< ( counter_read( id ) + 1 ) & ~ counter_read( id ) >, \\\n cn< ( counter_read( id ) + 1 ) & counter_read( id ) > )\nstruct my_cnt {};\n\nint const a = counter_read( my_cnt );\ncounter_inc( my_cnt );\ncounter_inc( my_cnt );\ncounter_inc( my_cnt );\ncounter_inc( my_cnt );\ncounter_inc( my_cnt );\n\nint const b = counter_read( my_cnt );\n\ncounter_inc( my_cnt );\n\n#include <iostream>\n\nint main() {\n std::cout << a << ' ' << b << '\\n';\n\n std::cout << counter_read( my_cnt ) << '\\n';\n}\nconstexprconstexpr#define COUNTER_READ_CRUMB( TAG, RANK, ACC ) counter_crumb( TAG(), constant_index< RANK >(), constant_index< ACC >() )\n#define COUNTER_READ( TAG ) COUNTER_READ_CRUMB( TAG, 1, COUNTER_READ_CRUMB( TAG, 2, COUNTER_READ_CRUMB( TAG, 4, COUNTER_READ_CRUMB( TAG, 8, \\\n COUNTER_READ_CRUMB( TAG, 16, COUNTER_READ_CRUMB( TAG, 32, COUNTER_READ_CRUMB( TAG, 64, COUNTER_READ_CRUMB( TAG, 128, 0 ) ) ) ) ) ) ) )\n\n#define COUNTER_INC( TAG ) \\\nconstexpr \\\nconstant_index< COUNTER_READ( TAG ) + 1 > \\\ncounter_crumb( TAG, constant_index< ( COUNTER_READ( TAG ) + 1 ) & ~ COUNTER_READ( TAG ) >, \\\n constant_index< ( COUNTER_READ( TAG ) + 1 ) & COUNTER_READ( TAG ) > ) { return {}; }\n\n#define COUNTER_LINK_NAMESPACE( NS ) using NS::counter_crumb;\n\ntemplate< std::size_t n >\nstruct constant_index : std::integral_constant< std::size_t, n > {};\n\ntemplate< typename id, std::size_t rank, std::size_t acc >\nconstexpr constant_index< acc > counter_crumb( id, constant_index< rank >, constant_index< acc > ) { return {}; } // found by ADL via constant_index\ncounter_crumbcounter_crumbcounter_crumbCOUNTER_LINK_NAMESPACE"}, {"idx": "webquery-test-2", "doc": "Explicitly exporting shared library functions in Linux", "code": "__attribute__((visibility(\"default\")))\n__declspec(dllimport)#if defined(_MSC_VER)\n // Microsoft \n #define EXPORT __declspec(dllexport)\n #define IMPORT __declspec(dllimport)\n#elif defined(__GNUC__)\n // GCC\n #define EXPORT __attribute__((visibility(\"default\")))\n #define IMPORT\n#else\n // do nothing and hope for the best?\n #define EXPORT\n #define IMPORT\n #pragma warning Unknown dynamic link import/export semantics.\n#endif\nMY_LIB_PUBLICMY_LIB_PUBLICMY_LIB_PUBLIC#if MY_LIB_COMPILING\n# define MY_LIB_PUBLIC EXPORT\n#else\n# define MY_LIB_PUBLIC IMPORT\n#endif\nMY_LIB_PUBLIC void foo();\n\nclass MY_LIB_PUBLIC some_type\n{\n // ...\n};\n"}, {"idx": "webquery-test-3", "doc": "How are exceptions implemented under the hood?", "code": "GOTOGOTOGOTOGOTOGOTO[Browser][Browser]GOTO"}, {"idx": "webquery-test-4", "doc": "Equivalent of %02d with std::stringstream?", "code": "<iomanip><iomanip><iomanip>stream << std::setfill('0') << std::setw(2) << value;\nstream << myfillandw( '0', 2 ) << value;\nstruct myfillandw\n{\n myfillandw( char f, int w )\n : fill(f), width(w) {}\n\n char fill;\n int width;\n};\n\nstd::ostream& operator<<( std::ostream& o, const myfillandw& a )\n{\n o.fill( a.fill );\n o.width( a.width );\n return o;\n}\n"}, {"idx": "webquery-test-5", "doc": "Should I switch from using boost::shared_ptr to std::shared_ptr?", "code": "std::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::shared_ptrstd::tr1::shared_ptr#if __cplusplus > 199711L\n#include <memory>\nnamespace MyProject\n{\n using std::shared_ptr;\n}\n#else\n#include <boost/shared_ptr.hpp>\nnamespace MyProject\n{\n using boost::shared_ptr;\n}\n#endif\n"}, {"idx": "webquery-test-6", "doc": "DSO missing from command line", "code": "-lpthread"}, {"idx": "webquery-test-7", "doc": "When a function has a specific-size array parameter, why is it replaced with a pointer?", "code": "void foo ( char a[100] );\nvoid foo ( char * a );\nvoid foo ( char (&a)[100] );\nvoid foo (char (&a)[100]);\n)))&&&char"}, {"idx": "webquery-test-8", "doc": "Uses of unnamed namespace in C++", "code": "staticstatic#include"}, {"idx": "webquery-test-9", "doc": "How should I write ISO C++ Standard conformant custom new and delete operators?", "code": "newnewnewoperator newvoid* operator new (std::size_t size) throw (std::bad_alloc);\nsizedeletemalloc()newnewnewnewnewnew_handlernew_handlernewnew_handlernew_handlernew_handlernew_handlernew_handlerset_new_handler#include <iostream>\n#include <cstdlib>\n\n// function to call if operator new can't allocate enough memory or error arises\nvoid outOfMemHandler()\n{\n std::cerr << \"Unable to satisfy request for memory\\n\";\n\n std::abort();\n}\n\nint main()\n{\n //set the new_handler\n std::set_new_handler(outOfMemHandler);\n\n //Request huge memory size, that will cause ::operator new to fail\n int *pBigDataArray = new int[100000000L];\n\n return 0;\n}\noperator newoperator newoperator newoperator newoperator newoperator new"}, {"idx": "webquery-test-1", "doc": "Better variable exploring when debugging C++ code with Eclipse/CDT", "code": "mingw-get install gdb-python\nmingw-get install gdb-python\n"}, {"idx": "webquery-test-2", "doc": "Why is strncpy insecure?", "code": "strncpy()"}, {"idx": "webquery-test-3", "doc": "Why does C++ output negative numbers when using modulo?", "code": "idividividividividivdividend = quotient*divisor + remainder"}, {"idx": "webquery-test-4", "doc": "gsl::not_null<T*> vs. std::reference_wrapper<T> vs. T&", "code": "reference_wrapper<T>reference_wrapper<T>reference_wrapper<T>reference_wrapper<T>reference_wrapper<T>not_null<T*>reference_wrapper<T>"}, {"idx": "webquery-test-5", "doc": "Enum variable default value?", "code": "int main() {\n int i; //indeterminate value\n std::cout << i; //undefined behavior\n};\nenum SomeEnum { \n EValue1 = 1, \n EValue2 = 4, \n};\nSomeEnum e; // e is 0\nint i; // i is 0\n\nint main()\n{\n cout << e << \" \" << i; //prints 0 0 \n}\neeeee"}, {"idx": "webquery-test-6", "doc": "What is the recommended way to align memory in C++11", "code": "new[Memory returned][ptr to start of memory][aligned memory][extra memory]\nvoid * RingBuffer::operator new(size_t request)\n{\n static const size_t ptr_alloc = sizeof(void *);\n static const size_t align_size = 64;\n static const size_t request_size = sizeof(RingBuffer)+align_size;\n static const size_t needed = ptr_alloc+request_size;\n\n void * alloc = ::operator new(needed);\n void *ptr = std::align(align_size, sizeof(RingBuffer),\n alloc+ptr_alloc, request_size);\n\n ((void **)ptr)[-1] = alloc; // save for delete calls to use\n return ptr; \n}\n\nvoid RingBuffer::operator delete(void * ptr)\n{\n if (ptr) // 0 is valid, but a noop, so prevent passing negative memory\n {\n void * alloc = ((void **)ptr)[-1];\n ::operator delete (alloc);\n }\n}\nRingBufferRingBuffer"}, {"idx": "webquery-test-7", "doc": "Complex C declaration", "code": "foofloat * (*(*float * (*(*float * (*(*float * (*(float * (*(float * (*(float * (*float * (*float * (*float * (*float * (*float * (*float * (*float * (*float * (*float * (float * (float * (float *float *float *float *float *float * ( *(* foo())[SIZE][SIZE])()typedef// Function that returns a pointer to float\ntypedef float* PFloatFunc ();\n\n// Array of pointers to PFloatFunc functions\ntypedef PFloatFunc* PFloatFuncArray2D[SIZE][SIZE];\n\n// Function that returns a pointer to a PFloatFuncArray2D\nPFloatFuncArray2D* foo();\n"}, {"idx": "webquery-test-8", "doc": "C++ std::vector emplace vs insert", "code": "struct Foo\n{\n Foo(int n, double x);\n};\n\nstd::vector<Foo> v;\nv.emplace(someIterator, 42, 3.1416);\nv.insert(someIterator, Foo(42, 3.1416));\n"}, {"idx": "webquery-test-1", "doc": "How to call through a member function pointer?", "code": "(bigCat.*pcat)();\n^ ^\n()()"}, {"idx": "webquery-test-2", "doc": "How to compile C code with anonymous structs / unions?", "code": "-fms-extensions"}, {"idx": "webquery-test-3", "doc": "How can I get a process handle by its name in C++?", "code": "#include <cstdio>\n#include <windows.h>\n#include <tlhelp32.h>\n\nint main( int, char *[] )\n{\n PROCESSENTRY32 entry;\n entry.dwSize = sizeof(PROCESSENTRY32);\n\n HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);\n\n if (Process32First(snapshot, &entry) == TRUE)\n {\n while (Process32Next(snapshot, &entry) == TRUE)\n {\n if (stricmp(entry.szExeFile, \"target.exe\") == 0)\n { \n HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);\n\n // Do stuff..\n\n CloseHandle(hProcess);\n }\n }\n }\n\n CloseHandle(snapshot);\n\n return 0;\n}\n#include <cstdio>\n#include <windows.h>\n#include <tlhelp32.h>\n\nvoid EnableDebugPriv()\n{\n HANDLE hToken;\n LUID luid;\n TOKEN_PRIVILEGES tkp;\n\n OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);\n\n LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid);\n\n tkp.PrivilegeCount = 1;\n tkp.Privileges[0].Luid = luid;\n tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n\n AdjustTokenPrivileges(hToken, false, &tkp, sizeof(tkp), NULL, NULL);\n\n CloseHandle(hToken); \n}\n\nint main( int, char *[] )\n{\n EnableDebugPriv();\n\n PROCESSENTRY32 entry;\n entry.dwSize = sizeof(PROCESSENTRY32);\n\n HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);\n\n if (Process32First(snapshot, &entry) == TRUE)\n {\n while (Process32Next(snapshot, &entry) == TRUE)\n {\n if (stricmp(entry.szExeFile, \"target.exe\") == 0)\n { \n HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);\n\n // Do stuff..\n\n CloseHandle(hProcess);\n }\n }\n }\n\n CloseHandle(snapshot);\n\n return 0;\n}\n"}, {"idx": "webquery-test-4", "doc": "How do I avoid implicit conversions on non-constructing functions?", "code": "void function(int); // this will be selected for int only\n\ntemplate <class T>\nvoid function(T) = delete; // C++11 \nfunction<int>function<int>void function(int) {}\n\ntemplate <class T>\nvoid function(T) = delete; // C++11 \n\n\nint main() {\n function(1);\n function(char(1)); // line 12\n} \nprog.cpp: In function 'int main()':\nprog.cpp:4:6: error: deleted function 'void function(T) [with T = char]'\nprog.cpp:12:20: error: used here\n// because this ugly code will give you compilation error for all other types\nclass DeleteOverload\n{\nprivate:\n DeleteOverload(void*);\n};\n\n\ntemplate <class T>\nvoid function(T a, DeleteOverload = 0);\n\nvoid function(int a)\n{}\n"}, {"idx": "webquery-test-5", "doc": "Using Visual Studio project properties effectively for multiple projects and configurations", "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup Label=\"UserMacros\">\n <!--debug suffix-->\n <DebugSuffix Condition=\"'$(Configuration)'=='Debug'\">-d</DebugSuffix>\n <DebugSuffix Condition=\"'$(Configuration)'!='Debug'\"></DebugSuffix>\n <!--platform-->\n <ShortPlatform Condition=\"'$(Platform)' == 'Win32'\">x86</ShortPlatform>\n <ShortPlatform Condition=\"'$(Platform)' == 'x64'\">x64</ShortPlatform>\n <!--toolset-->\n <Toolset Condition=\"'$(PlatformToolset)' == 'v90'\">vc90</Toolset>\n <Toolset Condition=\"'$(PlatformToolset)' == 'v100'\">vc100</Toolset>\n </PropertyGroup>\n <!--target-->\n <PropertyGroup>\n <TargetName>$(ProjectName)-$(Toolset)-$(ShortPlatform)$(DebugSuffix)</TargetName>\n </PropertyGroup>\n</Project>\n"}, {"idx": "webquery-test-6", "doc": "PCH Warning: header stop cannot be in a macro or #if block - Visual C++ 2010 Express SP1 ", "code": "#pragma once#pragma once"}, {"idx": "webquery-test-7", "doc": "How to get a stack trace for C++ using gcc with line number information?", "code": "#include <stdio.h>\n#include <stdlib.h>\n#include <sys/wait.h>\n#include <unistd.h>\n#include <sys/prctl.h>\n\nvoid print_trace() {\n char pid_buf[30];\n sprintf(pid_buf, \"%d\", getpid());\n char name_buf[512];\n name_buf[readlink(\"/proc/self/exe\", name_buf, 511)]=0;\n prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);\n int child_pid = fork();\n if (!child_pid) {\n dup2(2,1); // redirect output to stderr - edit: unnecessary?\n execl(\"/usr/bin/gdb\", \"gdb\", \"--batch\", \"-n\", \"-ex\", \"thread\", \"-ex\", \"bt\", name_buf, pid_buf, NULL);\n abort(); /* If gdb failed to start */\n } else {\n waitpid(child_pid,NULL,0);\n }\n}\n0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6\n[Current thread is 0 (process 15573)]\n#0 0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6\n#1 0x0000000000400bd5 in print_trace () at ./demo3b.cpp:496\n2 0x0000000000400c09 in recursive (i=2) at ./demo3b.cpp:636\n3 0x0000000000400c1a in recursive (i=1) at ./demo3b.cpp:646\n4 0x0000000000400c1a in recursive (i=0) at ./demo3b.cpp:646\n5 0x0000000000400c46 in main (argc=1, argv=0x7fffe3b2b5b8) at ./demo3b.cpp:70\n"}, {"idx": "webquery-test-8", "doc": "Passing integers as constant references versus copying", "code": "intint"}, {"idx": "webquery-test-9", "doc": "When does a constexpr function get evaluated at compile time?", "code": "constexprconstexprconstexprconstexprconstexprconstexprconstexpr"}, {"idx": "webquery-test-10", "doc": "Static variables initialisation order", "code": "main()"}, {"idx": "webquery-test-11", "doc": "What's the proper way to enable AddressSanitizer in CMake that works in Xcode", "code": "-fsanitize=addressadd_compile_options(-fsanitize=address)\nadd_link_options(-fsanitize=address)\ntarget_compile_options(asan-target PRIVATE -fsanitize=address)\ntarget_link_options(asan-target PRIVATE -fsanitize=address)\n"}, {"idx": "webquery-test-1", "doc": "What is constructor inheritance?", "code": "struct B\n{\n B(int); // normal constructor 1\n B(string); // normal constructor 2\n};\n\nstruct D : B\n{\n using B::B; // inherit constructors from B\n};\nD::D(int); // inherited\nD::D(string); // inherited\nD::D(int x) : B(x) {}\nD::D(string s) : B(s) {}\n"}, {"idx": "webquery-test-2", "doc": "C++: Mysteriously huge speedup from keeping one operand in a register", "code": "addsd -72(%rbp), %xmm0addsd -72(%rbp), %xmm0addsd -72(%rbp), %xmm0)addsd -72(%rbp), %xmm0)"}, {"idx": "webquery-test-3", "doc": "Returning temporary object and binding to const reference", "code": "foo()"}, {"idx": "webquery-test-4", "doc": "C++ ifstream failbit and badbit", "code": "failbitfailbiteofbiteofbiteofbiteofbit"}, {"idx": "webquery-test-5", "doc": "Why does using the ternary operator to return a string generate considerably different code from returning in an equivalent if/else block?", "code": "std::stringstd::stringstd::string"}, {"idx": "webquery-test-6", "doc": "Why I have to write std::cout and not also std::<<", "code": "<<<<<<<<<<operator<<operator<<<iostream>template<typename traits>\nstd::basic_ostream<char, traits>& operator<<(std::basic_ostream<char, traits>&,\n const char*);\nstdstdstd::ostreamstd::ostreamstd::ostreamstd::ostreamoperator<<namespace my_namespace\n{\n struct X {};\n\n void find_me(X) {}\n}\n\nint main()\n{\n my_namespace::X x;\n find_me(x); // finds my_namespace::find_me because of the argument type\n}\nnamespace my_namespace\n{\n struct X\n {\n void find_me(X, int) {}\n void search();\n };\n void find_me(X, double) {}\n\n void X::search() {\n find_me(*this, 2.5); // only finds X::find_me(int)\n // pure unqualified lookup (1st step) finds the member function\n // argument-dependent lookup is not performed\n }\n}\nnamespace my_namespace\n{\n struct X\n {\n void operator<<(int) {}\n void search();\n };\n void operator<<(X, double) {}\n\n void X::search() {\n *this << 2.5; // find both because both steps are always performed\n // and overload resolution selects the free function\n }\n}\n"}, {"idx": "webquery-test-7", "doc": "Can using a lambda in header files violate the ODR?", "code": "fextern inlinefDDDDDDCC"}, {"idx": "webquery-test-1", "doc": "How to get a random element from a C++ container?", "code": "#include <random>\n#include <iterator>\n\ntemplate<typename Iter, typename RandomGenerator>\nIter select_randomly(Iter start, Iter end, RandomGenerator& g) {\n std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);\n std::advance(start, dis(g));\n return start;\n}\n\ntemplate<typename Iter>\nIter select_randomly(Iter start, Iter end) {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n return select_randomly(start, end, gen);\n}\n#include <vector>\nusing namespace std;\n\nvector<int> foo;\n/* .... */\nint r = *select_randomly(foo.begin(), foo.end());\n"}, {"idx": "webquery-test-2", "doc": "C++ inserting unique_ptr in map", "code": "ObjectArrayObjectArray myMap;\nmyMap.insert(std::make_pair(0, std::unique_ptr<Class1>(new Class1())));\nObjectArray myMap;\nmyMap[0] = std::unique_ptr<Class1>(new Class1());\n0std::make_unique()std::make_unique()std::make_unique()myMap[0] = std::make_unique<Class1>();\n"}, {"idx": "webquery-test-3", "doc": "How do I find the largest int in a std::set<int>?", "code": "if(!myset.empty())\n *myset.rbegin();\nelse\n //the set is empty\n"}, {"idx": "webquery-test-4", "doc": "What is (x & 1) and (x >>= 1)?", "code": "x & 1x & 1x & 1x & 1x & 1x & 1x & 1x & 1x >>= 1x >>= 1x >>= 1x"}, {"idx": "webquery-test-5", "doc": "C++ pure virtual function have body", "code": "<class name>::<function name>struct S \n{\n virtual void foo() = 0;\n};\n\nvoid S::foo() \n{\n // body for pure virtual function `S::foo`\n}\n\nstruct D : S \n{\n void foo() \n {\n S::foo(); \n // Non-virtual call to `S::foo` from derived class\n\n this->S::foo(); \n // Alternative syntax to perform the same non-virtual call \n // to `S::foo` from derived class\n }\n};\n\nint main() \n{\n D d;\n\n d.S::foo(); \n // Another non-virtual call to `S::foo`\n}\n"}, {"idx": "webquery-test-6", "doc": "std::transform() and toupper(), no matching function", "code": "::toupper::toupper::toupper::toupperstd::transform(s.begin(), s.end(), std::back_inserter(out), ::toupper);\ntouppertouppertouppertoupperstd::toupper(int (*)(int))std::toupper\n//see the last argument, how it is casted to appropriate type\nstd::transform(s.begin(), s.end(), std::back_inserter(out),(int (*)(int))std::toupper);\n"}, {"idx": "webquery-test-7", "doc": "Why does the = operator work on structs without having been defined?", "code": "struct some_struct: public some_base\n{ \n std::string str1;\n int a;\n float b;\n char* c;\n std::string str2;\n};\nstruct some_struct: public some_base\n{ \n std::string str1;\n int a;\n float b;\n char* c;\n std::string str2;\n\n // Conceptually two different versions of the default constructor are built\n // One is for value-initialization the other for zero-initialization\n // The one used depends on how the object is declared.\n // some_struct* a = new some_struct; // value-initialized\n // some_struct* b = new some_struct(); // zero-initialized\n // some_struct c; // value-initialized\n // some_struct d = some_struct(); // zero-initialized\n // Note: Just because there are conceptually two constructors does not mean\n // there are actually two built.\n\n // value-initialize version\n some_struct()\n : some_base() // value-initialize base (if compiler generated)\n , str1() // has a normal constructor so just call it\n // PODS not initialized\n , str2()\n {}\n\n // zero-initialize version\n some_struct()\n : some_base() // zero-initialize base (if compiler generated)\n , str1() // has a normal constructor so just call it.\n , a(0)\n , b(0)\n , c(0) // 0 is NULL\n , str2()\n // Initialize all padding to zero\n {}\n\n some_struct(some_struct const& copy)\n : some_base(copy)\n , str1(copy.str1)\n , a(copy.a)\n , b(copy.b)\n , c(copy.c)\n , str2(copy.str2)\n {}\n\n some_struct& operator=(some_struct const& copy)\n {\n some_base::operator=(copy);\n str1 = copy.str1;\n a = copy.a;\n b = copy.b;\n c = copy.c;\n str2 = copy.str2;\n return *this;\n }\n\n ~some_struct()\n {}\n // Note the below is pseudo code\n // Also note member destruction happens after user code.\n // In the compiler generated version the user code is empty\n : ~str2()\n // PODs don't have destructor\n , ~str1()\n , ~some_base();\n // End of destructor here.\n\n // In C++11 we also have Move constructor and move assignment.\n some_struct(some_struct&& copy)\n // ^^^^ Notice the double &&\n : some_base(std::move(copy))\n , str1(std::move(copy.str1))\n , a(std::move(copy.a))\n , b(std::move(copy.b))\n , c(std::move(copy.c))\n , str2(std::move(copy.str2))\n {}\n\n some_struct& operator=(some_struct&& copy)\n // ^^^^ Notice the double &&\n {\n some_base::operator=(std::move(copy));\n str1 = std::move(copy.str1);\n a = std::move(copy.a);\n b = std::move(copy.b);\n c = std::move(copy.c);\n str2 = std::move(copy.str2);\n return *this;\n } \n};\n"}, {"idx": "webquery-test-8", "doc": "Linking different libraries for Debug and Release builds in Cmake on windows?", "code": "target_link_libraries(<target> [lib1 [lib2 [...]]] [[debug|optimized|general] <lib>] ...)\nadd_executable( MyEXE ${SOURCES})\n\ntarget_link_libraries( MyEXE debug 3PDebugLib)\ntarget_link_libraries( MyEXE optimized 3PReleaseLib)\n"}, {"idx": "webquery-test-1", "doc": "std::put_time implementation status in GCC?", "code": "std::get_timestd::get_time"}, {"idx": "webquery-test-2", "doc": "Correct usage of rvalue references as parameters", "code": "Loadprobestruct probe {\n probe(const char* ) { std::cout << \"ctr \" << std::endl; }\n probe(const probe& ) { std::cout << \"copy\" << std::endl; }\n probe(probe&& ) { std::cout << \"move\" << std::endl; }\n};\nvoid f(const probe& p) {\n probe q(p);\n // use q;\n}\nf(\"foo\");ctr\ncopy\nprobeprobeprobeprobeprobeprobeprobeppvoid f(probe p) {\n // use p;\n}\nf(\"foo\");ctr\nppstruct foo {\n probe p;\n foo(const probe& q) : p(q) { }\n};\nprobeprobeprobeprobeprobeprobeprobe& operator =(const probe& other) {\n probe tmp(other);\n swap(tmp);\n return *this;\n}\nprobe& operator =(probe tmp) {\n swap(tmp);\n return *this;\n}\nprobe& operator =(probe&&);\ng(\"foo\");g(\"foo\");void g(probe);\nvoid g(probe&&);\n"}, {"idx": "webquery-test-3", "doc": "When to use const char * and when to use const char []", "code": "char text[] = \"text\"; \nNULLNULLNULLchar *text = \"text\"; \nconstconst char*text = \"text\";\nstrlen()strlen()strlen()const char text[]const char text[]constconstconst"}, {"idx": "webquery-test-4", "doc": "Is constexpr supported with lambda functions / expressions?", "code": "constexprconstexprconstexprconstexpr"}, {"idx": "webquery-test-5", "doc": "What is an `int foo::*bar::*`?", "code": "struct bar;\n\nstruct foo\n{\n int y; \n int bar::* whatever;\n};\n\nstruct bar\n{\n foo aFoo;\n};\n\nint bar::* foo::* ptr = &foo::whatever;\nptrptrptrptrptrstruct bar\n{\n foo aFoo;\n\n int really;\n};\n\nint bar::* foo::* ptr = &foo::whatever;\nfoo fleh;\nfleh.whatever = &bar::really;\nbar blah;\nblah.*(fleh.*ptr) = 42;\nstd::cout << blah.really << std::endl;\n"}, {"idx": "webquery-test-6", "doc": "know if .lib is static or import", "code": "lib /list foo.lib\n"}, {"idx": "webquery-test-7", "doc": "Is this std::ref behaviour logical?", "code": "f2template<class T>\nvoid f2(T arg)\n{\n arg.get() = xx;\n}\nstd::refstd::reff1f1f1f1f1"}, {"idx": "webquery-test-8", "doc": "How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found", "code": "-static-libstdc++"}, {"idx": "webquery-test-1", "doc": "How can I iterate over a packed variadic template argument list?", "code": "anyanyany#include <vector>\n#include <iostream>\n\nstruct any {\n enum type {Int, Float, String};\n any(int e) { m_data.INT = e; m_type = Int;}\n any(float e) { m_data.FLOAT = e; m_type = Float;}\n any(char* e) { m_data.STRING = e; m_type = String;}\n type get_type() const { return m_type; }\n int get_int() const { return m_data.INT; }\n float get_float() const { return m_data.FLOAT; }\n char* get_string() const { return m_data.STRING; }\nprivate:\n type m_type;\n union {\n int INT;\n float FLOAT;\n char *STRING;\n } m_data;\n};\n\ntemplate <class ...Args>\nvoid foo_imp(const Args&... args)\n{\n std::vector<any> vec = {args...};\n for (unsigned i = 0; i < vec.size(); ++i) {\n switch (vec[i].get_type()) {\n case any::Int: std::cout << vec[i].get_int() << '\\n'; break;\n case any::Float: std::cout << vec[i].get_float() << '\\n'; break;\n case any::String: std::cout << vec[i].get_string() << '\\n'; break;\n }\n }\n}\n\ntemplate <class ...Args>\nvoid foo(Args... args)\n{\n foo_imp(any(args)...); //pass each arg to any constructor, and call foo_imp with resulting any objects\n}\n\nint main()\n{\n char s[] = \"Hello\";\n foo(1, 3.4f, s);\n}\n"}, {"idx": "webquery-test-2", "doc": "MSVCP140.dll missing", "code": "Project tab -> properties - > configuration properties -> C/C++ -> Code GenerationProject tab -> properties - > configuration properties -> C/C++ -> Code GenerationProject tab -> properties - > configuration properties -> C/C++ -> Code Generation"}, {"idx": "webquery-test-3", "doc": "Why is address of char data not displayed?", "code": "char *char *cout << \"address of char :\" << (void *) &b << endlstatic_castcout << \"address of char :\" << static_cast<void *>(&b) << endl;\n"}, {"idx": "webquery-test-4", "doc": "Getting a bunch of crosses initialization error", "code": "switchswitch(k)\n{\n case 1:\n int t = 4;\n break;\n default:\n break;\n}\nswitch(k)\n{\n case 1:\n {\n int t = 4;\n }\n break;\n default:\n break;\n}\n{int t = 0;\nswitch(k)\n{\n case 1:\n t = 4;\n break;\n default:\n break;\n}\n"}, {"idx": "webquery-test-5", "doc": "How is vector<vector<int>> \"heavier\" than vector<pair<int,int>>?", "code": "std::vector<std::pair<int, int>>\nstd::vector<std::vector<int>>\nstd::vectorint"}, {"idx": "webquery-test-6", "doc": "string::size_type instead of int", "code": "string::size_type"}, {"idx": "webquery-test-7", "doc": "how do you insert the value in a sorted vector?", "code": "template< typename T >\ntypename std::vector<T>::iterator \n insert_sorted( std::vector<T> & vec, T const& item )\n{\n return vec.insert\n ( \n std::upper_bound( vec.begin(), vec.end(), item ),\n item \n );\n}\ntemplate< typename T, typename Pred >\ntypename std::vector<T>::iterator\n insert_sorted( std::vector<T> & vec, T const& item, Pred pred )\n{\n return vec.insert\n ( \n std::upper_bound( vec.begin(), vec.end(), item, pred ),\n item \n );\n}\nO(log N)O(log N)O(log N)std::set<T>std::set<T>vectorvectorvectorvectorvectorvectorvectorvectorvectorvectorvectorvector"}, {"idx": "webquery-test-8", "doc": "Is f(void) deprecated in modern C and C++?", "code": "int f(void)int f(void)int f(void)int f(void)"}, {"idx": "webquery-test-9", "doc": "Why do you use std::move when you have && in C++11?", "code": "T&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tT&& tTTTT"}, {"idx": "webquery-test-10", "doc": "Tail recursion in C++", "code": "unsigned int f( unsigned int a ) {\n if ( a == 0 ) {\n return a;\n }\n return f( a - 1 ); // tail recursion\n}\n"}, {"idx": "webquery-test-11", "doc": "C++ cannot convert from base A to derived type B via virtual base A", "code": "BBBBBvirtualvirtualvirtualvirtualvirtualvirtualvirtualstatic_caststatic_caststatic_cast"}, {"idx": "webquery-test-1", "doc": "Destructors of builtin types (int, char etc..)", "code": "template<typename T>\nstruct C {\n // ...\n ~C() {\n for(size_t i = 0; i<elements; i++)\n buffer[i].~T();\n }\n};\nintint~~~"}, {"idx": "webquery-test-2", "doc": "Why can't we declare a namespace within a class?", "code": "class Foo\n{\n namespace bar\n {\n ..stuff..\n }\n\n .. more stuff ..\n\n namespace bar\n {\n ..still more stuff..\n }\n};\n"}, {"idx": "webquery-test-3", "doc": "Return a 2d array from a function", "code": " #include <cstdio>\n\n // Returns a pointer to a newly created 2d array the array2D has size [height x width]\n\n int** create2DArray(unsigned height, unsigned width)\n {\n int** array2D = 0;\n array2D = new int*[height];\n \n for (int h = 0; h < height; h++)\n {\n array2D[h] = new int[width];\n \n for (int w = 0; w < width; w++)\n {\n // fill in some initial values\n // (filling in zeros would be more logic, but this is just for the example)\n array2D[h][w] = w + width * h;\n }\n }\n \n return array2D;\n }\n \n int main()\n {\n printf(\"Creating a 2D array2D\\n\");\n printf(\"\\n\");\n \n int height = 15;\n int width = 10;\n int** my2DArray = create2DArray(height, width);\n printf(\"Array sized [%i,%i] created.\\n\\n\", height, width);\n \n // print contents of the array2D\n printf(\"Array contents: \\n\");\n \n for (int h = 0; h < height; h++)\n {\n for (int w = 0; w < width; w++)\n {\n printf(\"%i,\", my2DArray[h][w]);\n }\n printf(\"\\n\");\n }\n \n // important: clean up memory\n printf(\"\\n\");\n printf(\"Cleaning up memory...\\n\");\n for (int h = 0; h < height; h++) // loop variable wasn't declared\n {\n delete [] my2DArray[h];\n }\n delete [] my2DArray;\n my2DArray = 0;\n printf(\"Ready.\\n\");\n \n return 0;\n }\n"}, {"idx": "webquery-test-4", "doc": "reading a line from ifstream into a string variable", "code": "std::getline()std::getline() istream & getline(istream & is,std::string& str)\nstd::getline(read,x);\n"}, {"idx": "webquery-test-5", "doc": "Are static variables in a base class shared by all derived classes?", "code": "staticVarclass Base {\n static int staticVarInst;\npublic:\n virtual int &staticVar() { return staticVarInst; }\n}\nclass Derived: public Base {\n static int derivedStaticVarInst;\npublic:\n virtual int &staticVar() { return derivedStaticVarInst; }\n}\nstaticVar() = 5;\ncout << staticVar();\n"}, {"idx": "webquery-test-6", "doc": "C++11 Range-based for-loop efficiency \"const auto &i\" versus \"auto i\"", "code": "const&T // I'm copying this\nT& // I'm modifying this\nconst T& // I'm reading this\nTT"}, {"idx": "webquery-test-7", "doc": "How do traits classes work and what do they do?", "code": "iterator_traitsiterator_traitsiterator_traits<vector<int>::iterator>::value_type x;\niterator_traits<int*>::value_type y;\n// `x` and `y` have type int.\n<iterator>template <typename T>\nstruct iterator_traits<T*> {\n typedef T value_type;\n // \u2026\n};\niterator_traitsiterator_traitsiterator_traitsiterator_traits"}, {"idx": "webquery-test-8", "doc": "Is there a difference between universal references and forwarding references?", "code": "Pstd::forwardTtemplate <class T> void foo(T&& ); // <== \n"}, {"idx": "webquery-test-9", "doc": "Catch Multiple Custom Exceptions? - C++", "code": "std::exceptiontry\n{\n // throws something\n}\ncatch ( const MostSpecificException& e )\n{\n // handle custom exception\n}\ncatch ( const LessSpecificException& e )\n{\n // handle custom exception\n}\ncatch ( const std::exception& e )\n{\n // standard exceptions\n}\ncatch ( ... )\n{\n // everything else\n}\nthrowthrowthrowtry\n{\n // code throws some subclass of std::exception\n}\ncatch ( const std::exception& e )\n{\n std::cerr << \"ERROR: \" << e.what() << std::endl;\n}\n"}, {"idx": "webquery-test-10", "doc": "Why is size_t unsigned?", "code": "size_tptrdiff_tptrdiff_tstring( \"Hi\" ).length() < -3string( \"Hi\" ).length() < -3string( \"Hi\" ).length() < -3"}, {"idx": "webquery-test-11", "doc": "shared_from_this causing bad_weak_ptr", "code": "tcp_connectiontcp_connectionboost::bindboost::bindclientsvoid start_accept()\n{\n tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);\n acceptor_.async_accept(new_connection->socket(),\n boost::bind(\n &tcp_server::handle_accept,\n this, new_connection, asio::placeholders::error\n )\n );\n}\n\nvoid handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)\n{\n if (!error)\n {\n client->start();\n start_accept();\n }\n}\ntcp_connectiontcp_connection#include <iostream>\n#include <boost/bind.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/enable_shared_from_this.hpp>\n#include <boost/asio.hpp>\n#include <boost/thread.hpp>\n\nnamespace asio = boost::asio;\nusing asio::ip::tcp;\n\nclass tcp_connection : public boost::enable_shared_from_this<tcp_connection>\n{\npublic:\n typedef boost::shared_ptr<tcp_connection> sptr;\n\n tcp_connection(asio::io_service& io_service) : socket_(io_service), timer_(io_service)\n {\n }\n\n void start()\n {\n std::cout << \"Created tcp_connection session\\n\";\n\n // post some work bound to this object; if you don't, the client gets\n // 'garbage collected' as the ref count goes to zero\n do_hello();\n }\n\n ~tcp_connection() {\n std::cout << \"Destroyed tcp_connection\\n\";\n }\n\n tcp::socket& socket()\n {\n return socket_;\n }\n\n private:\n tcp::socket socket_;\n asio::deadline_timer timer_;\n\n void do_hello(boost::system::error_code const& ec = {}) {\n if (!ec) {\n asio::async_write(socket_, asio::buffer(\"Hello world\\n\"),\n boost::bind(&tcp_connection::handle_written, shared_from_this(), asio::placeholders::error, asio::placeholders::bytes_transferred)\n );\n }\n }\n\n void handle_written(boost::system::error_code const& ec, size_t /*bytes_transferred*/) {\n if (!ec) {\n timer_.expires_from_now(boost::posix_time::seconds(1));\n timer_.async_wait(boost::bind(&tcp_connection::do_hello, shared_from_this(), asio::placeholders::error));\n }\n }\n};\n\nclass tcp_server\n{\npublic:\n tcp_server(asio::io_service& io_service)\n : io_service_(io_service),\n acceptor_(io_service, tcp::endpoint(tcp::v4(), 6767))\n {\n start_accept();\n }\n\nprivate:\n void start_accept()\n {\n tcp_connection::sptr new_connection = boost::make_shared<tcp_connection>(io_service_);\n acceptor_.async_accept(new_connection->socket(),\n boost::bind(\n &tcp_server::handle_accept,\n this, new_connection, asio::placeholders::error\n )\n );\n }\n\n void handle_accept(tcp_connection::sptr client, boost::system::error_code const& error)\n {\n if (!error)\n {\n client->start();\n start_accept();\n }\n }\n\n asio::io_service& io_service_;\n tcp::acceptor acceptor_;\n};\n\nint main()\n{\n try\n {\n asio::io_service io_service;\n tcp_server server(io_service);\n\n boost::thread(boost::bind(&asio::io_service::run, &io_service)).detach();\n\n boost::this_thread::sleep_for(boost::chrono::seconds(4));\n io_service.stop();\n }\n catch (std::exception& e)\n {\n std::cerr << \"Exception: \" << e.what() << \"\\n\";\n }\n}\nsehe@desktop:/tmp$ time (./test& (for a in {1..4}; do nc 127.0.0.1 6767& done | nl&); sleep 2; killall nc; wait)\nCreated tcp_connection session\nCreated tcp_connection session\n 1 Hello world\nCreated tcp_connection session\n 2 Hello world\nCreated tcp_connection session\n 3 Hello world\n 4 Hello world\n 5 Hello world\n 6 Hello world\n 7 Hello world\n 8 Hello world\n 9 Hello world\n 10 Hello world\n 11 Hello world\n 12 Hello world\n 13 \nDestroyed tcp_connection\nDestroyed tcp_connection\nDestroyed tcp_connection\nDestroyed tcp_connection\nDestroyed tcp_connection\n\nreal 0m4.003s\nuser 0m0.000s\nsys 0m0.015s\n"}, {"idx": "webquery-test-12", "doc": "Why can't a derived class call protected member function in this code?", "code": "protectedpointer->memberpointer->memberpointer->membersomethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()somethingProtected()b.somethingProtected()void Derived::somethingDerived()\n{\n Base *b = this;\n b->somethingProtected(); // ERROR\n this->somethingProtected(); // OK\n}\n"}, {"idx": "webquery-test-13", "doc": "How to create an std::function from a move-capturing lambda expression?", "code": "template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);template<class F> function(F f);operator =operator =template<class F> function& operator=(F&& f);template<class F> function& operator=(F&& f);std::functionstd::function"}, {"idx": "webquery-test-14", "doc": "cmake - find_library - custom library location", "code": "HINTSHINTSfind_library(CURL_LIBRARY\n NAMES curl curllib libcurl_imp curllib_static\n HINTS \"${CMAKE_PREFIX_PATH}/curl/lib\"\n)\nBOOST_DIR"}, {"idx": "webquery-test-1", "doc": "Easiest way to rotate by 90 degrees an image using OpenCV?", "code": "cv::rotate(image, image, cv::ROTATE_90_CLOCKWISE);\nROTATE_90_CLOCKWISE\nROTATE_180\nROTATE_90_COUNTERCLOCKWISE\n"}, {"idx": "webquery-test-2", "doc": "How can I emulate destructuring in C++?", "code": "struct animal {\n std::string species;\n int weight;\n std::string sound;\n};\n\nint main()\n{\n auto pluto = animal { \"dog\", 23, \"woof\" };\n\n auto [ species, weight, sound ] = pluto;\n\n std::cout << \"species=\" << species << \" weight=\" << weight << \" sound=\" << sound << \"\\n\";\n}\n"}, {"idx": "webquery-test-3", "doc": "Contents of a static library", "code": "ar -t-t"}, {"idx": "webquery-test-4", "doc": "How to declare a static const char* in your header file?", "code": "private:\n static const char *SOMETHING;\n static const int MyInt = 8; // would be ok\nconst char *YourClass::SOMETHING = \"something\";\n"}, {"idx": "webquery-test-5", "doc": "Are C++ enums slower to use than integers?", "code": "intintintint:S-S"}, {"idx": "webquery-test-6", "doc": "How to parse ini file with Boost", "code": "#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\n...\n\nboost::property_tree::ptree pt;\nboost::property_tree::ini_parser::read_ini(\"config.ini\", pt);\nstd::cout << pt.get<std::string>(\"Section1.Value1\") << std::endl;\nstd::cout << pt.get<std::string>(\"Section1.Value2\") << std::endl;\n"}, {"idx": "webquery-test-7", "doc": "Convert RGB to Black & White in OpenCV", "code": "// C\nIplImage* im_gray = cvLoadImage(\"image.jpg\",CV_LOAD_IMAGE_GRAYSCALE);\n\n// C++ (OpenCV 2.0)\nMat im_gray = imread(\"image.jpg\",CV_LOAD_IMAGE_GRAYSCALE);\nim_rgb// C\nIplImage *im_rgb = cvLoadImage(\"image.jpg\");\nIplImage *im_gray = cvCreateImage(cvGetSize(im_rgb),IPL_DEPTH_8U,1);\ncvCvtColor(im_rgb,im_gray,CV_RGB2GRAY);\n\n// C++\nMat im_rgb = imread(\"image.jpg\");\nMat im_gray;\ncvtColor(im_rgb,im_gray,CV_RGB2GRAY);\n// C\nIplImage* im_bw = cvCreateImage(cvGetSize(im_gray),IPL_DEPTH_8U,1);\ncvThreshold(im_gray, im_bw, 128, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);\n\n// C++\nMat img_bw = im_gray > 128;\n// C\ncvSaveImage(\"image_bw.jpg\",img_bw);\n\n// C++\nimwrite(\"image_bw.jpg\", img_bw);\n"}, {"idx": "webquery-test-8", "doc": "Recommended values for OpenCV detectMultiScale() parameters", "code": "scaleFactorscaleFactorscaleFactorscaleFactorscaleFactorscaleFactorscaleFactorscaleFactor"}, {"idx": "webquery-test-9", "doc": "One liner to convert from list<T> to vector<T>", "code": "std::vector<T> v{ std::begin(l), std::end(l) };\nllstd::vector<T> v{ std::make_move_iterator(std::begin(l)), \n std::make_move_iterator(std::end(l)) };\n"}, {"idx": "webquery-test-1", "doc": "Are all integer values perfectly represented as doubles?", "code": "mantissa * 2^exponent bits range precision\n float 32 1.5E-45 .. 3.4E38 7- 8 digits\n double 64 5.0E-324 .. 1.7E308 15-16 digits\n long double 80 1.9E-4951 .. 1.1E4932 19-20 digits\nintint#include <iostream>\n#include <limits>\nusing namespace std;\n\nint main() {\n double test;\n volatile int test_int;\n for(int i=0; i< std::numeric_limits<int>::max(); i++) {\n test = i;\n test_int = test;\n\n // compare int with int:\n if (test_int != i)\n std::cout<<\"found integer i=\"<<i<<\", test=\"<<test<<std::endl;\n }\n return 0;\n}\n2^exponent"}, {"idx": "webquery-test-2", "doc": "What is 1LL or 2LL in C and C++?", "code": "LLLL2LL2LLLLLL1 << 40\n1LL << 40\n1111"}, {"idx": "webquery-test-3", "doc": "Linker returns \"relocation has an invalid symbol at symbol index...\"", "code": "mainmainint main()\n{\n // TODO: implementation\n}\n"}, {"idx": "webquery-test-4", "doc": "inline function members inside a class", "code": "inlinereturn stuffclass MyClass\n{\npublic:\n int f() const { return m_i; }\n int g() const;\n\nprivate:\n int m_i;\n};\n\ninline int MyClass::g() const\n{\n return m_i;\n}\n\n// both member-functions behave equally (except for naming)\n"}, {"idx": "webquery-test-5", "doc": "How can I avoid the Diamond of Death when using multiple inheritance?", "code": "class A {};\nclass B : public A {};\nclass C : public A {};\nclass D : public B, public C {};\nclass A {};\nclass B : virtual public A {};\nclass C : virtual public A {};\nclass D : public B, public C {};\n"}, {"idx": "webquery-test-6", "doc": "Iterating through vector<unique_ptr<mytype>> using C++11 for() loops", "code": "for (auto i: AVLTree) { ... }\nAVLTree.begin()AVLTree.begin()AVLTree.begin()AVLTree.begin()for (auto& i: AVLTree) { ... }\nfor (auto const& i: AVLTree) { ... }\n"}, {"idx": "webquery-test-7", "doc": "What's the point of a final virtual function?", "code": "finalfinalfinalstruct Base {\n void test() { std::cout << \"Base::test()\\n\"; }\n};\n\nvoid run(Base *o) {\n o->test();\n}\n\n\n// Some other developer derives a class\nstruct Derived : Base {\n void test() { std::cout << \"Derived::test()\\n\"; }\n};\n\nint main() {\n Derived o;\n o.test();\n run(&o);\n}\nBaseBasestruct Base {\n virtual void test() final { ... }\n};\nBase::foo()<source>:14:13: error: declaration of 'test' overrides a 'final' function\n void test() { std::cout << \"Derived::test()\\n\"; }\n ^\n<source>:4:22: note: overridden virtual function is here\n virtual void test() final { std::cout << \"Base::test()\\n\"; }\n ^\nvirtual finalvirtual finalstruct Derived : Base {\n void test(int = 0) { std::cout << \"Derived::test()\\n\"; }\n};\nBase::test()Base::test()Base::test()Base::test()virtualvirtual"}, {"idx": "webquery-test-8", "doc": "Missing C++ header <__debug> after updating OSX Command Line Tools 6.3", "code": "commandlinetoolsosx10.10forxcode6.2.dmgcommandlinetoolsosx10.10forxcode6.2.dmg__debug#ifdef _LIBCPP_DEBUG\n# include <__debug>\n#else\n# define _LIBCPP_ASSERT(x, m) ((void)0)\n#endif\n"}, {"idx": "webquery-test-9", "doc": "Static functions outside classes", "code": "staticstaticstatic"}, {"idx": "webquery-test-10", "doc": "Pause Console in C++ program", "code": "cin.get()system()#define--keep-alive-when-dead"}, {"idx": "webquery-test-11", "doc": "How can I use C++ 11 features in Clang?", "code": "-std=c++11\n-std=c++1y\n"}]