tips & tricks

You think you are good at C/C++ programming language? Maybe you are, but I’m trying to learn ever day something new.

Look at my collection of interesting features/questions/whatever. If you know something interesting about C/C++ please post comment.

Array as index

What do you think this code will do? Will there be compiler error?

int array[] = {1, 2, 3};
std::cout << "value : " << 1[array] << std::endl;

No, it will work the same as writing array[1].
Output:

value : 2
Statically initialized pointer

I seen it at my job. To initialize pointer statically, you just have to create single element array. Why you could do it this way? I don’t really know.

int pointer[] = {5};
cout << "pointer : " << pointer << endl;    
cout << "value   : " << *pointer << endl;

Output:

pointer : 0x7fff5fbff980
value   : 5
Single line code for printing std::vector

Useful code to print vector using only single line of source code.

#include <vector>
#include <iterator>
#include <iostream>

int main(int argc, char** argv)
{
    std::vector v(5, 2); 
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    return 0;
}

Output:

2 2 2 2 2
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: