What are some fun C++ tricks

This one applies to all languages so far:


A REALLY fast way of swaping a and b.

#include <iostream>
#include <string>

using namespace std;

int main (int argc, char*argv) {
float a; cout << «A:»; cin >> a;
float b; cout << «B:» ; cin >> b;

cout << «———————» << endl;
cout << «A=» << a << «, B=» << b << endl;
cout << «A=» << a << «, B=» << b << endl;

void Send(int * to, const int* from, const int count)


   int n = (count+7) / 8;



      case 0:



               *to++ = *from++;

      case 7:

               *to++ = *from++;

      case 6:

               *to++ = *from++;

      case 5:

               *to++ = *from++;

      case 4:

               *to++ = *from++;

      case 3:

               *to++ = *from++;

      case 2:

               *to++ = *from++;

      case 1:

               *to++ = *from++;

              } while (—n>0);



Preprocessor Tricks

The arraysize macro used in Chrome’s source:

  1. template <typename T, size_t N>
  2. char (&ArraySizeHelper(T (&array)[N]))[N];
  3. #define arraysize(array) (sizeof(ArraySizeHelper(array)))

This is better than the ordinary 

<span class="kwd">sizeof</span><span class="pun">(</span><span class="pln">array</span><span class="pun">)/</span><span class="kwd">sizeof</span><span class="pun">(</span><span class="pln">array</span><span class="pun">[</span><span class="lit">0</span><span class="pun">])</span>

 because it raises compilation errors when the passed in array is just a pointer, or a null pointer whereas the simpler macro silently returns a useless value. For a detailed example, see PVS-Studio vs Chromium.

Predefined Macros:

  1. #define expect(expr) if(!expr) cerr << «Assertion « << #expr \
  2. » failed at « << __FILE__ << «:» << __LINE__ << endl;
  3. #define stringify(x) #x
  4. #define tostring(x) stringify(x)
  5. #define MAGIC_CONSTANT 314159
  6. cout << «Value of MAGIC_CONSTANT=» << tostring(MAGIC_CONSTANT);


<span class="pln">tostring</span>

 macro is a common trick used to expand macro values inside other macros. The Linux kernel uses a lot of macro tricks.

Using iterators for quickly dumping the contents of a container:

  1. #define dbg(v) copy(v.begin(), v.end(), ostream_iterator<typeof(*v.begin())>(cout, » «))

Sadly, this doesn’t work for 

<span class="pln">pair</span>

 types so maps are out of scope.

Template Voodoo

Recursion:You can specialize your class templates for certain cases, so you can write down the base-case of a recursion and then define the generic template as a recursive combination of base cases.
For example, the following code calculates the values of the Choose function at compile time:

  1. template<unsigned n, unsigned r>
  2. struct Choose {
  3. enum {value = (n * Choose<n1, r1>::value) / r};
  4. };
  5. template<unsigned n>
  6. struct Choose<n, 0> {
  7. enum {value = 1};
  8. };
  9. int main() {
  10. // Prints 56
  11. cout << Choose<8, 3>::value;
  12. // Compile time values can be used as array sizes
  13. int x[Choose<25, 3>::value];
  14. }

More interesting examples at C++ Programming/Templates/Template Meta-Programming

Mostly Painless Memory Management and RAII

With certain restrictions, you can create templates for «smart» pointers that automatically deallocate resources when they go out of scope or reference count goes to 0. This is basically done by overloading 

<span class="kwd">operator</span> <span class="pun">*</span>


<span class="kwd">operator</span> <span class="pun">=</span>

. Based on your use case, you can transfer ownership when the 

<span class="kwd">operator</span> <span class="pun">=</span>

 is used, or update reference counts.
See Smart Pointer Guidelines — The Chromium Projects and http://code.google.com/searchfra…

Argument-dependent name lookup aka Koenig lookup

When a function call cannot be matched to a name in the current namespace, other namespaces can be searched for a matching signature. This is why 

<span class="pln">std</span><span class="pun">::</span><span class="pln">cout </span><span class="pun">&lt;&lt;</span> <span class="str">"Hi"</span><span class="pun">;</span>

 works even though 

<span class="kwd">operator</span> <span class="pun">&lt;&lt;</span>

 is defined in the 

<span class="pln">std</span>

See Argument-dependent name lookup

auto keyword
In C++ you can use auto to iterate over map,vector,set,..etc which specifies that the type of the variable that is being declared will be automatically deduced from its initializer or for functions it will the return type or it will be deduced from its return statements
So instead of :

  1. vector<int> vs;
  2. vs.push_back(4),vs.push_back(7),vs.push_back(9),vs.push_back(10);
  3. for (vector<int>::iterator it = vs.begin(); it != vs.end(); ++it)
  4. cout << *it << ‘ ‘;cout<<‘\n’;

just use :

  1. vector<int> vs;
  2. vs.push_back(4),vs.push_back(7),vs.push_back(9),vs.push_back(10);
  3. for (auto it: vs)
  4. cout << it << ‘ ‘;cout<<endl;
  5. //you can also change the values using
  6. vector<int> vs;
  7. vs.push_back(4),vs.push_back(7),vs.push_back(9),vs.push_back(10);
  8. for (auto& it: vs) it*=3;
  9. for (auto it: vs)
  10. cout << it << ‘ ‘;cout<<endl;

Declaring variable

  1. template<class A, class B>
  2. auto mult(A x, B y) -> decltype(x * y){
  3. return x * y;
  4. }
  5. int main(){
  6. auto a = 3 * 2; //the return type is the type of operator (x*y)
  7. cout<<a<<endl;
  8. return 0;
  9. }

The Power of Strings 

  1. int n,m;
  2. cin >> n >> m;
  3. int matrix[n+1][m+1];
  4. //This loop
  5. for(int i = 1; i <= n; i++) {
  6. for(int j = 1; j <= m; j++)
  7. cout << matrix[i][j] << » «;
  8. cout << «\n»;
  9. }
  10. // is equivalent to this
  11. for(int i = 1; i <= n; i++)
  12. for(int j = 1; j <= m; j++)
  13. cout << matrix[i][j] << » \n»[j == m];


<span class="str">" \n"</span>

 is a 

<span class="kwd">char</span><span class="pun">*</span>


<span class="str">" \n"</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]</span>


<span class="str">' '</span>


<span class="str">" \n"</span><span class="pun">[</span><span class="lit">1</span><span class="pun">]</span>


<span class="str">'\n'</span>


Some Hidden function
__gcd(x, y)
you don’t need to code gcd function.

  1. cout<<__gcd(54,48)<<endl; //return 6

This function returns 1 + least significant 1-bit of x. If x == 0, returns 0. Here x is int, this function with suffix ‘l’ gets a long argument and with suffix ‘ll’ gets a long long argument.
e.g:  __builtin_ffs(10) = 2 because 10 is ‘…10 1 0′ in base 2 and first 1-bit from right is at index 1 (0-based) and function returns 1 + index.three)

Pairing tricks 

  1. pair<int, int> p;
  2. //This
  3. p = make_pair(1, 2);
  4. //equivalent to this
  5. p = {1, 2};
  6. //So
  7. pair<int, pair<char, long long> > p;
  8. //now easier
  9. p = {1, {‘a’, 2ll}};

Super include 
Simply use

<span class="com">#include</span> <span class="pun">&lt;</span><span class="pln">bits</span><span class="pun">/</span><span class="pln">stdc</span><span class="pun">++.</span><span class="pln">h</span><span class="pun">&gt;</span>

This library includes many of libraries we do need  like algorithm, iostream, vector and many more. Believe me you don’t need to include anything else 😀 !!

Smart Pointers

Using smart pointers, we can make pointers to work in way that we don’t need to explicitly call delete. Smart pointer is a wrapper class over a pointer with operator like * and -> overloaded. The objects of smart pointer class look like pointer, but can do many things that a normal pointer can’t like automatic destruction (yes, we don’t have to explicitly use delete), reference counting and more.
The idea is to make a class with a pointer, destructor and overloaded operators like * and ->. Since destructor is automatically called when an object goes out of scope, the dynamically alloicated memory would automatically deleted (or reference count can be decremented).

You can put URIs in your C++ code and the compiler will not throw any error.

  1. <span class="com">#include</span> <span class="str">&lt;iostream&gt;</span>
  2. <span class="typ">int</span><span class="pln"> main</span><span class="pun">()</span> <span class="pun">{</span>
  3. <span class="kwd">using</span> <span class="kwd">namespace</span><span class="pln"> std</span><span class="pun">;</span>
  4. <span class="pln">http</span><span class="pun">:</span><span class="com">//www.google.com</span>
  5. <span class="typ">int</span><span class="pln"> x </span><span class="pun">=</span> <span class="lit">5</span><span class="pun">;</span>
  6. <span class="pln">cout </span><span class="pun">&lt;&lt;</span><span class="pln"> x</span><span class="pun">;</span>
  7. <span class="pun">}</span>

Explanation: Any identifier followed by a : becomes a (goto) label in C++. Anything followed by // becomes a comment so in the code above, http is a label and //google.com/is a comment. The compiler might throw a warning however, since the label is unutilized.

Don’t Confuse Assign (=) with Test-for-Equality (==).

This one is elementary, although it might have baffled Sherlock Holmes. The following looks innocent and would compile and run just fine if C++ were more like BASIC:

if (a = b)
cout << «a is equal to b.»;

Because this looks so innocent, it creates logic errors requiring hours to track down within a large program unless you’re on the lookout for it. (So when a program requires debugging, this is the first thing I look for.) In C and C++, the following is not a test for equality:

a = b

What this does, of course, is assign the value of b to a and then evaluate to the value assigned.
The problem is that a = b does not generally evaluate to a reasonable true/false condition—with one major exception I’ll mention later. But in C and C++, any numeric value can be used as a condition for “if” or “while.
Assume that a and b are set to 0. The effect of the previously-shown if statement is to place the value of b into a; then the expression a = b evaluates to 0. The value 0 equates to false. Consequently, aand b are equal, but exactly the wrong thing gets printed:

if (a = b)     // THIS ENSURES a AND b ARE EQUAL…
cout << «a and b are equal.»;
cout << «a and b are not equal.»;  // BUT THIS GETS PRINTED!

The solution, of course, is to use test-for-equality when that’s what you want. Note the use of double equal signs (==). This is correct inside a condition.

if (a == b)
cout << «a and b are equal.»;

The most amazing trick i found was a status of someone’s topcoder profile:
#include <cstdio>
double m[]= {7709179928849219.0, 771};
int main()
You will be seriously amazed by the ouput…here it is:

I tried to analyse the code and came up with a reason but not an exact explanation..so i tried to ask it on stackoverflow..you can go through the explanation here:
Concept behind this 4 lines tricky C++ code
Read it and you will learn something you wouldn’t have even thought of… 😉

  1. <span class="kwd">static</span> <span class="kwd">const</span> <span class="kwd">unsigned</span> <span class="kwd">char</span> <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="lit">256</span><span class="pun">]</span> <span class="pun">=</span>
  2. <span class="pun">{</span>
  3. <span class="com">#   define B2(n) n,     n+1,     n+1,     n+2 </span>
  4. <span class="com">#   define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2) </span>
  5. <span class="com">#   define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)     </span>
  6. <span class="pln">     B6</span><span class="pun">(</span><span class="lit">0</span><span class="pun">),</span><span class="pln"> B6</span><span class="pun">(</span><span class="lit">1</span><span class="pun">),</span><span class="pln"> B6</span><span class="pun">(</span><span class="lit">1</span><span class="pun">),</span><span class="pln"> B6</span><span class="pun">(</span><span class="lit">2</span><span class="pun">)</span>
  7. <span class="pun">};</span>
  8. <span class="kwd">unsigned</span> <span class="typ">int</span><span class="pln"> v</span><span class="pun">;</span> <span class="com">// count the number of bits set in 32-bit value v </span>
  9. <span class="kwd">unsigned</span> <span class="typ">int</span><span class="pln"> c</span><span class="pun">;</span> <span class="com">// c is the total bits set in v  </span>
  10. <span class="com">// Option 1: </span>
  11. <span class="pln">c </span><span class="pun">=</span> <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">v </span><span class="pun">&amp;</span> <span class="lit">0xff</span><span class="pun">]</span> <span class="pun">+</span>
  12. <span class="typ">BitsSetTable256</span><span class="pun">[(</span><span class="pln">v </span><span class="pun">&gt;&gt;</span> <span class="lit">8</span><span class="pun">)</span> <span class="pun">&amp;</span> <span class="lit">0xff</span><span class="pun">]</span> <span class="pun">+</span>
  13. <span class="typ">BitsSetTable256</span><span class="pun">[(</span><span class="pln">v </span><span class="pun">&gt;&gt;</span> <span class="lit">16</span><span class="pun">)</span> <span class="pun">&amp;</span> <span class="lit">0xff</span><span class="pun">]</span> <span class="pun">+</span>
  14. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">v </span><span class="pun">&gt;&gt;</span> <span class="lit">24</span><span class="pun">];</span>
  15. <span class="com">// Option 2: </span>
  16. <span class="kwd">unsigned</span> <span class="kwd">char</span> <span class="pun">*</span><span class="pln"> p </span><span class="pun">=</span> <span class="pun">(</span><span class="kwd">unsigned</span> <span class="kwd">char</span> <span class="pun">*)</span> <span class="pun">&amp;</span><span class="pln">v</span><span class="pun">;</span>
  17. <span class="pln">c </span><span class="pun">=</span> <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">p</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]]</span> <span class="pun">+</span>
  18. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">p</span><span class="pun">[</span><span class="lit">1</span><span class="pun">]]</span> <span class="pun">+</span>
  19. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">p</span><span class="pun">[</span><span class="lit">2</span><span class="pun">]]</span> <span class="pun">+</span>
  20. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">p</span><span class="pun">[</span><span class="lit">3</span><span class="pun">]];</span>
  21. <span class="com">// To initially generate the table algorithmically: </span>
  22. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="lit">0</span><span class="pun">]</span> <span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span>
  23. <span class="kwd">for</span> <span class="pun">(</span><span class="typ">int</span><span class="pln"> i </span><span class="pun">=</span> <span class="lit">0</span><span class="pun">;</span><span class="pln"> i </span><span class="pun">&lt;</span> <span class="lit">256</span><span class="pun">;</span><span class="pln"> i</span><span class="pun">++)</span>
  24. <span class="pun">{</span>
  25. <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">i</span><span class="pun">]</span> <span class="pun">=</span> <span class="pun">(</span><span class="pln">i </span><span class="pun">&amp;</span> <span class="lit">1</span><span class="pun">)</span> <span class="pun">+</span> <span class="typ">BitsSetTable256</span><span class="pun">[</span><span class="pln">i </span><span class="pun">/</span> <span class="lit">2</span><span class="pun">];</span>
  26. <span class="pun">}</span>



  1. <span class="typ">float</span><span class="pln"> Q_rsqrt</span><span class="pun">(</span> <span class="typ">float</span><span class="pln"> number </span><span class="pun">)</span>
  2. <span class="pun">{</span>
  3. <span class="kwd">long</span><span class="pln"> i</span><span class="pun">;</span>
  4. <span class="typ">float</span><span class="pln"> x2</span><span class="pun">,</span><span class="pln"> y</span><span class="pun">;</span>
  5. <span class="kwd">const</span> <span class="typ">float</span><span class="pln"> threehalfs </span><span class="pun">=</span> <span class="lit">1.5F</span><span class="pun">;</span>
  6. <span class="pln">        x2 </span><span class="pun">=</span><span class="pln"> number </span><span class="pun">*</span> <span class="lit">0.5F</span><span class="pun">;</span>
  7. <span class="pln">        y  </span><span class="pun">=</span><span class="pln"> number</span><span class="pun">;</span>
  8. <span class="pln">        i  </span><span class="pun">=</span> <span class="pun">*</span> <span class="pun">(</span> <span class="kwd">long</span> <span class="pun">*</span> <span class="pun">)</span> <span class="pun">&amp;</span><span class="pln">y</span><span class="pun">;</span>                       <span class="com">// evil floating point bit level hacking</span>
  9. <span class="pln">        i  </span><span class="pun">=</span> <span class="lit">0x5f3759df</span> <span class="pun">-</span> <span class="pun">(</span><span class="pln"> i </span><span class="pun">&gt;&gt;</span> <span class="lit">1</span> <span class="pun">);</span>               <span class="com">// what the fuck?</span>
  10. <span class="pln">        y  </span><span class="pun">=</span> <span class="pun">*</span> <span class="pun">(</span> <span class="typ">float</span> <span class="pun">*</span> <span class="pun">)</span> <span class="pun">&amp;</span><span class="pln">i</span><span class="pun">;</span>
  11. <span class="pln">        y  </span><span class="pun">=</span><span class="pln"> y </span><span class="pun">*</span> <span class="pun">(</span><span class="pln"> threehalfs </span><span class="pun">-</span> <span class="pun">(</span><span class="pln"> x2 </span><span class="pun">*</span><span class="pln"> y </span><span class="pun">*</span><span class="pln"> y </span><span class="pun">)</span> <span class="pun">);</span>   <span class="com">// 1st iteration</span>
  12. <span class="com">//      y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed</span>
  13. <span class="kwd">return</span><span class="pln"> y</span><span class="pun">;</span>
  14. <span class="pun">}</span>


  1. <span class="com">#define</span><span class="pln"> FOR</span><span class="pun">(</span><span class="pln">i</span><span class="pun">,</span><span class="pln">n</span><span class="pun">)</span> <span class="kwd">for</span><span class="pun">(</span><span class="typ">int</span> <span class="pun">(</span><span class="pln">i</span><span class="pun">)=</span><span class="lit">0</span><span class="pun">;(</span><span class="pln">i</span><span class="pun">)&lt;(</span><span class="pln">n</span><span class="pun">);(</span><span class="pln">i</span><span class="pun">)++)</span>
  2. <span class="com">#define</span><span class="pln"> FORR</span><span class="pun">(</span><span class="pln">i</span><span class="pun">,</span><span class="pln">a</span><span class="pun">,</span><span class="pln">b</span><span class="pun">)</span> <span class="kwd">for</span><span class="pun">(</span><span class="typ">int</span> <span class="pun">(</span><span class="pln">i</span><span class="pun">)=(</span><span class="pln">a</span><span class="pun">);(</span><span class="pln">i</span><span class="pun">)&lt;(</span><span class="pln">b</span><span class="pun">);(</span><span class="pln">i</span><span class="pun">)++)</span>
  3. <span class="com">//reverse</span>
  4. <span class="com">#define</span><span class="pln"> REV</span><span class="pun">(</span><span class="pln">i</span><span class="pun">,</span><span class="pln">n</span><span class="pun">)</span> <span class="kwd">for</span><span class="pun">(</span><span class="typ">int</span> <span class="pun">(</span><span class="pln">i</span><span class="pun">)=(</span><span class="pln">n</span><span class="pun">)-</span><span class="lit">1</span><span class="pun">;(</span><span class="pln">i</span><span class="pun">)&gt;=</span><span class="lit">0</span><span class="pun">;(</span><span class="pln">i</span><span class="pun">)--)</span>

Handy way to use it like this. 

  1. <span class="kwd">typedef</span> <span class="kwd">long</span> <span class="kwd">long</span> <span class="typ">int</span> <span class="typ">int64</span><span class="pun">;</span>
  2. <span class="kwd">typedef</span> <span class="kwd">unsigned</span> <span class="kwd">long</span> <span class="kwd">long</span> <span class="typ">int</span> <span class="typ">uint64</span><span class="pun">;</span>

FastIO for +ve integers.

    1. <span class="kwd">inline</span> <span class="kwd">void</span><span class="pln"> frint</span><span class="pun">(</span><span class="typ">int</span> <span class="pun">*</span><span class="pln">a</span><span class="pun">){</span>
    2. <span class="kwd">register</span> <span class="kwd">char</span><span class="pln"> c</span><span class="pun">=</span><span class="lit">0</span><span class="pun">;</span><span class="kwd">while</span> <span class="pun">(</span><span class="pln">c</span><span class="pun">&lt;</span><span class="lit">33</span><span class="pun">)</span><span class="pln"> c</span><span class="pun">=</span><span class="pln">getchar_unlocked</span><span class="pun">();*</span><span class="pln">a</span><span class="pun">=</span><span class="lit">0</span><span class="pun">;</span>
    3. <span class="kwd">while</span> <span class="pun">(</span><span class="pln">c</span><span class="pun">&gt;</span><span class="lit">33</span><span class="pun">){*</span><span class="pln">a</span><span class="pun">=*</span><span class="pln">a</span><span class="pun">*</span><span class="lit">10</span><span class="pun">+</span><span class="pln">c</span><span class="pun">-</span><span class="str">'0'</span><span class="pun">;</span><span class="pln">c</span><span class="pun">=</span><span class="pln">getchar_unlocked</span><span class="pun">();}</span>
    4. <span class="pun">}</span>

Try This….

#include <iostream>
using namespace std;
int main()
int a,b,c;
int count = 1;
for (b=c=10;a=»- FIGURE?, UMKC,XYZHello Folks,\
TFy!QJu ROo TNn(ROo)SLq SLq ULo+\
T|S~Pn SPm SOn TNn ULo0ULo#ULo-W\
Hq!WFs XDt!» [b+++21]; )
for(; a— > 64 ; )
putchar ( ++c==’Z’ ? c = c/ 9:33^b&1);
return 0;

I think one of the coolest of all time, is defining an abstract base class in C++, and inheriting from it in python, and passing it back to C++ to call.
It actually works

  1. <span class="kwd">struct</span> <span class="typ">Interface</span><span class="pun">{</span>
  2. <span class="typ">int</span><span class="pln"> foo</span><span class="pun">()</span><span class="kwd">const</span><span class="pun">=</span><span class="lit">0</span><span class="pun">;</span>
  3. <span class="kwd">virtual</span> <span class="pun">~</span><span class="typ">Interface</span><span class="pun">(){}</span>
  4. <span class="pun">};</span>
  5. <span class="kwd">void</span><span class="pln"> call</span><span class="pun">(</span><span class="typ">Interface</span> <span class="kwd">const</span><span class="pun">&amp;</span><span class="pln"> f</span><span class="pun">){</span>
  6. <span class="pln">  std</span><span class="pun">::</span><span class="pln">cout</span><span class="pun">&lt;&lt;</span><span class="pln">f</span><span class="pun">.</span><span class="pln">foo</span><span class="pun">()&lt;&lt;</span><span class="pln">std</span><span class="pun">::</span><span class="pln">endl</span><span class="pun">;</span>
  7. <span class="pun">}</span>
  8. <span class="kwd">struct</span> <span class="typ">InterfaceWrap</span><span class="pln"> final</span><span class="pun">:</span> <span class="typ">Interface</span><span class="pun">,</span><span class="pln"> boost</span><span class="pun">::</span><span class="pln">python</span><span class="pun">::</span><span class="pln">wrapper</span><span class="pun">&lt;</span><span class="typ">Interface</span><span class="pun">&gt;</span>
  9. <span class="pun">{</span>
  10. <span class="typ">int</span><span class="pln"> foo</span><span class="pun">()</span> <span class="kwd">const</span><span class="pln"> final</span>
  11. <span class="pun">{</span>
  12. <span class="kwd">return</span> <span class="kwd">this</span><span class="pun">-&gt;</span><span class="pln">get_override</span><span class="pun">(</span><span class="str">"foo"</span><span class="pun">)();</span>
  13. <span class="pun">}</span>
  14. <span class="pun">};</span>
  15. <span class="pln">BOOST_PYTHON_MODULE</span><span class="pun">(</span><span class="pln">interface</span><span class="pun">){</span>
  16. <span class="kwd">using</span> <span class="kwd">namespace</span><span class="pln"> boost</span><span class="pun">::</span><span class="pln">python</span><span class="pun">;</span>
  17. <span class="pln">    class_</span><span class="pun">&lt;</span><span class="typ">Interface</span> <span class="pun">,</span><span class="pln">boost </span><span class="pun">::</span><span class="pln">noncopyable</span><span class="pun">,</span><span class="pln">boost</span><span class="pun">::</span><span class="pln">shared_ptr</span><span class="pun">&lt;</span><span class="typ">Interface</span><span class="pun">&gt;&gt;(</span><span class="str">"_InterfaceCpp"</span><span class="pun">,</span><span class="pln">no_init</span><span class="pun">)</span>
  18. <span class="pun">.</span><span class="pln">def</span><span class="pun">(</span><span class="str">"foo"</span><span class="pun">,&amp;</span><span class="typ">Interface</span><span class="pun">::</span><span class="pln">foo</span><span class="pun">)</span>
  19. <span class="pun">;</span>
  20. <span class="pln">    class_</span><span class="pun">&lt;</span><span class="typ">InterfaceWrap</span> <span class="pun">,</span><span class="pln">bases</span><span class="pun">&lt;</span><span class="typ">Interface</span><span class="pun">&gt;,</span><span class="pln">boost</span><span class="pun">::</span><span class="pln">shared_ptr</span><span class="pun">&lt;</span><span class="typ">InterfaceWrap</span><span class="pun">&gt;&gt;(</span><span class="str">"Interface"</span><span class="pun">,</span><span class="pln">init</span><span class="pun">&lt;&gt;())</span>
  21. <span class="pun">;</span>
  22. <span class="pln">  def</span><span class="pun">(</span><span class="str">"call"</span><span class="pun">,&amp;</span><span class="pln">call</span><span class="pun">);</span>
  23. <span class="pun">}</span>

and then

  1. <span class="kwd">import</span><span class="pln"> interface </span><span class="kwd">as</span><span class="pln"> i </span><span class="com"># C++ code</span>
  2. <span class="kwd">class</span><span class="pln"> impl</span><span class="pun">(</span><span class="pln">i</span><span class="pun">.</span><span class="typ">Interface</span><span class="pun">):#</span><span class="pln">inherit </span><span class="kwd">from</span><span class="pln"> C</span><span class="pun">++</span> <span class="kwd">class</span>
  3. <span class="kwd">def</span><span class="pln"> __init__</span><span class="pun">(</span><span class="pln">self</span><span class="pun">):</span>
  4. <span class="pln">        i</span><span class="pun">.</span><span class="typ">Interface</span><span class="pun">.</span><span class="pln">__init__</span><span class="pun">(</span><span class="pln">self</span><span class="pun">)</span>
  5. <span class="kwd">def</span><span class="pln"> foo</span><span class="pun">(</span><span class="pln">self</span><span class="pun">):</span>
  6. <span class="kwd">return</span> <span class="lit">100</span>
  7. <span class="pln">i</span><span class="pun">.</span><span class="pln">call</span><span class="pun">(</span><span class="pln">impl</span><span class="pun">())#</span><span class="pln">call C</span><span class="pun">++</span><span class="pln"> function </span><span class="kwd">with</span> <span class="typ">Python</span><span class="pln"> derived </span><span class="kwd">class</span>

This does exactly what you think it should do.

void qsort ( void * base, size_t num, size_t size, int ( * compar ) ( const void *, const void * ) )

base Pointer to the first element of the array to be sorted.

num Number of elements in the array pointed by base. size_t is an unsigned integral type.

size Size in bytes of each element in the array. size_t is an unsigned integral type.

compar Function that compares two elements. This function is called repeatedly by qsorttocomparetwoelements.It shall follow the following prototype:

int compar ( const void * elem1, const void * elem2 );

Taking a pointer to two pointers as arguments (both type-casted to const void*). The function should compare the data pointed by both: if they match in ranking, the function shall return zero; if elem1 goes before elem2, it shall return a negative value; and if it goes after, a positive value.

Eg :

int values[] = { 40, 10, 100, 90, 20, 25 };

int compare (const void * a, const void * b) { return ( *(int*)a — *(int*)b ); }

int main () {
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++) printf («%d «,values[n]); return 0; }

Partial template specialization

<span class="pln">C</span><span class="pun">++</span><span class="lit">11</span>

 has this cool function 

<span class="kwd">get</span><span class="pun">&lt;</span><span class="pln">J</span><span class="pun">&gt;</span>

 which can be used to access the 

<span class="pln">first</span>


<span class="pln">second</span>

 member of a 

<span class="pln">pair</span>

, with a different syntax:

  1. std::pair < std::string, double > pr ( «pi», 3.14 );
  2. std::cout << std::get < 0 > ( pr ); // outputs «pi»
  3. std::cout << std::get < 1 > ( pr ); // outputs 3.14

Note that this is a function and not a function object or a member function.

I do not find it trivial to write a function

  • with three template types 
    <span class="kwd">template</span> <span class="pun">&lt;</span> <span class="typ">size_t</span><span class="pln"> J</span><span class="pun">,</span> <span class="kwd">class</span><span class="pln"> T1</span><span class="pun">,</span> <span class="kwd">class</span><span class="pln"> T2 </span><span class="pun">&gt;</span>
  • which can get 
    <span class="pln">std</span><span class="pun">::</span><span class="pln">pair </span><span class="pun">&lt;</span><span class="pln"> T1</span><span class="pun">,</span><span class="pln"> T2 </span><span class="pun">&gt;</span>

     as an argument

  • and outputs 
    <span class="pln">pr</span><span class="pun">.</span><span class="pln">first</span>

     if the template value J is 0

  • and outputs 
    <span class="pln">pr</span><span class="pun">.</span><span class="pln">second</span>

     if the template value J is 1.

In particular consider that in 

<span class="pln">C</span><span class="pun">++</span>

 one cannot overload a function based on its return type. So what should the return type of this function be declared as? 

<span class="pln">T1</span>


<span class="pln">T2</span>


  1. template < size_t J, class T1, class T2>
  2. ??? get ( std::pair < T1, T2 > & );

The interesting thing is that one could already write this function in 

<span class="pln">C</span><span class="pun">++</span><span class="lit">98</span>

 using Partial template specialization, which is a really cool trick. The problem is that function templates cannot be partially specialized, but this is easy to solve:

  1. namespace
  2. {
  3. /*!
  4. * helper template to do the work with partial specialization
  5. */
  6. template < size_t J, class T1, class T2 >
  7. struct Get;
  8. template < class T1, class T2>
  9. struct Get < 0, T1, T2 >
  10. {
  11. typedef typename std::pair < T1, T2 >::first_type result_type;
  12. static result_type & elm ( std::pair < T1, T2 > & pr ) { return pr.first; }
  13. static const result_type & elm ( const std::pair < T1, T2 > & pr ) { return pr.first; }
  14. };
  15. template < class T1, class T2>
  16. struct Get < 1, T1, T2 >
  17. {
  18. typedef typename std::pair < T1, T2 >::second_type result_type;
  19. static result_type & elm ( std::pair < T1, T2 > & pr ) { return pr.second; }
  20. static const result_type & elm ( const std::pair < T1, T2 > & pr ) { return pr.second; }
  21. };
  22. }
  23. template < size_t J, class T1, class T2 >
  24. typename Get< J, T1, T2 >::result_type & get ( std::pair< T1, T2 > & pr )
  25. {
  26. return Get < J, T1, T2 >::elm( pr );
  27. }
  28. template < size_t J, class T1, class T2 >
  29. const typename Get< J, T1, T2 >::result_type & get ( const std::pair< T1, T2 > & pr )
  30. {
  31. return Get < J, T1, T2 >::elm( pr );
  32. }

Define operator<< for STL structures to make it easy to add debug outputs to your code. (This is better than special printing functions because it nests automatically! Printing a map< vector<int>, int> works without any additional effort if you can print any map and any vector.)

Additionally, define a macro that makes nicer debug outputs and makes it easy to turn them off using the standard mechanism (same one that is used for assert). Here’s a short example how to do all of this in C++11:

  1. <span class="com">#include</span> <span class="str">&lt;iostream&gt;</span>
  2. <span class="com">#include</span> <span class="str">&lt;string&gt;</span>
  3. <span class="com">#include</span> <span class="str">&lt;map&gt;</span>
  4. <span class="com">#ifdef</span><span class="pln"> NDEBUG</span>
  5. <span class="com">#define</span><span class="pln"> DEBUG</span><span class="pun">(</span><span class="pln">var</span><span class="pun">)</span>
  6. <span class="com">#else</span>
  7. <span class="com">#define</span><span class="pln"> DEBUG</span><span class="pun">(</span><span class="pln">var</span><span class="pun">)</span> <span class="pun">{</span><span class="pln"> std</span><span class="pun">::</span><span class="pln">cout </span><span class="pun">&lt;&lt;</span> <span class="com">#var &lt;&lt; ": " &lt;&lt; (var) &lt;&lt; std::endl; }</span>
  8. <span class="com">#endif</span>
  9. <span class="kwd">template</span><span class="pun">&lt;</span><span class="kwd">typename</span><span class="pln"> T1</span><span class="pun">,</span> <span class="kwd">typename</span><span class="pln"> T2</span><span class="pun">&gt;</span>
  10. <span class="pln">std</span><span class="pun">::</span><span class="pln">ostream</span><span class="pun">&amp;</span> <span class="kwd">operator</span><span class="pun">&lt;&lt;</span> <span class="pun">(</span><span class="pln">std</span><span class="pun">::</span><span class="pln">ostream</span><span class="pun">&amp;</span><span class="pln"> out</span><span class="pun">,</span> <span class="kwd">const</span><span class="pln"> std</span><span class="pun">::</span><span class="typ">map</span><span class="pun">&lt;</span><span class="pln">T1</span><span class="pun">,</span><span class="pln">T2</span><span class="pun">&gt;</span> <span class="pun">&amp;</span><span class="pln">M</span><span class="pun">)</span> <span class="pun">{</span>
  11. <span class="pln">    out </span><span class="pun">&lt;&lt;</span> <span class="str">"{ "</span><span class="pun">;</span>
  12. <span class="kwd">for</span> <span class="pun">(</span><span class="kwd">auto</span><span class="pln"> item</span><span class="pun">:</span><span class="pln">M</span><span class="pun">)</span><span class="pln"> out </span><span class="pun">&lt;&lt;</span><span class="pln"> item</span><span class="pun">.</span><span class="pln">first </span><span class="pun">&lt;&lt;</span> <span class="str">"-&gt;"</span> <span class="pun">&lt;&lt;</span><span class="pln"> item</span><span class="pun">.</span><span class="pln">second </span><span class="pun">&lt;&lt;</span> <span class="str">", "</span><span class="pun">;</span>
  13. <span class="pln">    out </span><span class="pun">&lt;&lt;</span> <span class="str">"}"</span><span class="pun">;</span>
  14. <span class="kwd">return</span><span class="pln"> out</span><span class="pun">;</span>
  15. <span class="pun">}</span>
  16. <span class="typ">int</span><span class="pln"> main</span><span class="pun">()</span> <span class="pun">{</span>
  17. <span class="pln">    std</span><span class="pun">::</span><span class="typ">map</span><span class="pun">&lt;</span><span class="pln">std</span><span class="pun">::</span><span class="pln">string</span><span class="pun">,</span><span class="typ">int</span><span class="pun">&gt;</span><span class="pln"> age </span><span class="pun">=</span> <span class="pun">{</span> <span class="pun">{</span><span class="str">"Joe"</span><span class="pun">,</span><span class="lit">47</span><span class="pun">},</span> <span class="pun">{</span><span class="str">"Bob"</span><span class="pun">,</span><span class="lit">22</span><span class="pun">},</span> <span class="pun">{</span><span class="str">"Laura"</span><span class="pun">,</span><span class="lit">19</span><span class="pun">}</span> <span class="pun">};</span>
  18. <span class="pln">    DEBUG</span><span class="pun">(</span><span class="pln">age</span><span class="pun">);</span>
  19. <span class="pun">}</span>

This is a very amazing piece of code:


It is the shortest C++ code which when executed prints itself. It was discovered by Vlad Taeerov and Rashit Fakhreyev and is only 64 characters in length(Making it the shortest).

To Convert list<T> to vector<T>:

  1. <span class="pln">std</span><span class="pun">::</span><span class="typ">vector</span><span class="pun">&lt;</span><span class="pln">T</span><span class="pun">&gt;</span><span class="pln"> v</span><span class="pun">(</span><span class="pln">l</span><span class="pun">.</span><span class="pln">begin</span><span class="pun">(),</span><span class="pln"> l</span><span class="pun">.</span><span class="pln">end</span><span class="pun">());</span>


Variadic Templates :

They can be useful in places. You can pass any number of parameters .
Example  :

  1. #include <iostream>
  2. #include <bitset>
  3. #include <string>
  4. using namespace std;
  6. void print() {
  7. cout<<«Nothing to print :)» ;
  8. }
  10. template<typename T,typename args>
  11. void print(T x,args y) {
  12. cout<<x<<endl;
  13. print(y…);
  14. }
  16. int main() {
  17. print(10,14.56,«Quora»,bitset<20>(28));
  18. return 0;
  19. }


Code on ideon : http://ideone.com/b8TNHD

Output :

  1. 10
  2. 14.56
  3. Quora
  4. 00000000000000011100
  5. Nothing to print 🙂


Range based for loops can be used with some STL containers :


  1. #include <iostream>
  2. #include <list>
  3. #include <vector>
  5. using namespace std;
  7. int main() {
  8. list<int> x;
  9. x.push_back(10);
  10. x.push_back(20);
  11. for(auto i : x)
  12. cout<<i;
  13. return 0;
  14. }

РубрикиБез рубрики

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

%d такие блоггеры, как: