C: Difference between revisions
Line 451: | Line 451: | ||
return 0; | return 0; | ||
} | } | ||
</pre> | |||
More examples from [http://www.cplusplus.com/forum/beginner/42244/ this post]. | |||
<pre> | |||
// OK case. | |||
main: int i=6; | |||
chgInt(&i); | |||
function: void chgInt(int *p); | |||
*p = 10 + *p; | |||
// Not OK case. | |||
main: char *name = "old"; | |||
chgStr(name); | |||
function: void chgStr(char *n); | |||
n = "new"; // This will make a new string, not changing the original one | |||
// Correction | |||
main: SAME | |||
function: void chgStr(char* &n); | |||
n = "new"; | |||
</pre> | </pre> | ||
Revision as of 14:18, 15 September 2013
Socket programming
- Beej's Guide to Network Programming
- UNIX Network Programming APIs 3rd; by Richard Stevens
- UNIX Network Programming by Jim Kurose
- http://www.prasannatech.net/2008/07/socket-programming-tutorial.html Socket programming in C, pERL, Python & Java.
- http://www.slideshare.net/hominhchuc/writing-client-server-programs-in-c-writing-clientserver-programs-in-c (see slides pp 19-23 & reference p31)
- http://www.yolinux.com/TUTORIALS/Sockets.html (c++ examples)
- http://www.cs.odu.edu/~mweigle/courses/cs455-f06/lectures/2-1-ClientServer.pdf
- TCP/IP Sockets in C: Practical Guide for Programmers by Donahoo and Calvert
- Effective TCP/IP Programming: 44 Tips to Improve Your Network by Jon Snader
- http://stackoverflow.com/questions/583940/is-there-a-beginners-book-for-c-socket-programming
- http://net.pku.edu.cn/~course/cs501/2011/code/BSD_Socket.t/sockets.pdf Presentation format
- Course material from Communication Networks
- Chapter 15 of Beginning Linux Programming 4th ed by Matthew and Stones.
- Chapter 18 of UNIX Systems Programming by Robbins and Robbins.
- http://www.binarytides.com/socket-programming-c-linux-tutorial/ Nice and short tutorial for beginner.
- Introduction to network functions in C http://shoe.bocks.com/net/
- http://www.cs.gsu.edu/~sguo/slides/3320/Sockets.ppt Short introduction and my local copy
- http://www.csd.uoc.gr/~hy556/material/tutorials/cs556-3rd-tutorial.pdf Long introduction and a local copy.
- http://web.cecs.pdx.edu/~jrb/tcpip/lectures/pdfs/sockets.pdf
Terms
There are two types of address domains.
- AF_UNIX: the unix domain for two processes which share a common file system, and
- AF_INET: the Internet domain for any two hosts on the Internet.
There are two types of sockets.
- a stream socket in which characters are read in a continuous stream as if from a file or pipe, and
- a datagram socket, in which messages are read in chunks.
The two symbolic constants are SOCK_STREAM and SOCK_DGRAM.
There are two types of ports:
- well known Ports | those that rarely change overtime. For instance, servers that provide mail, file transfer, remote login,
etc.
- dynamic ports | typically used only for the life of a process. For instance, pipes can be implemented using message passing
Examples of servers:
- mail server
- login server
- file server
- web server
- streaming server
TCP vs UDP
- TCP is used for services with a large data capacity, and a persistent connection
- UDP is more commonly used for quick lookups, and single use query-reply actions.
- Some common examples of TCP and UDP with their default ports:
- DNS lookup UDP 53
- FTP TCP 21
- HTTP TCP 80
- POP3 TCP 110
- Telnet TCP 23
General Idea
The steps involved in establishing a socket on the client side are as follows:
- Create a socket with the socket() system call
- Connect the socket to the address of the server using the connect() system call
- Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.
The steps involved in establishing a socket on the server side are as follows:
- Create a socket with the socket() system call
- Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
- Listen for connections with the listen() system call
- Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
- Receive and send data by using read() and write().
Internet Hearsay
- Tools for debugging sockets applications using netstat and tcpdump GNU/Linux tools.
View all TCP sockets currently active $ netstat --tcp View all UDP sockets $ netstat --udp View all TCP sockets in the listening state $ netstat --listening View the multicast group membership information $ netstat --groups Display the list of masqueraded connections $ netstat --masquerade View statistics for each protocol $ netstat --statistics Display all traffic on the eth0 interface for the local host $ tcpdump -l -i eth0 Show all traffic on the network coming from or going to host plato $ tcpdump host plato Show all HTTP traffic for host camus $ tcpdump host camus and (port http) View traffic coming from or going to TCP port 45000 on the local host $ tcpdump tcp port 45000
Make http request via telnet
Below, we only input two lines. One is telnet linus.nci.nih.gov 80 and the other is HEAD / HTTP/1.0\n\n. Remember the one carriage character and one line feed at the end of request line. We can change the HTTP method in the 2nd input to GET /HTTP/1.0\n\n to fetch the full page. See the book HTTP: The Definitive Guide and wikipedia.
$ telnet linus.nci.nih.gov 80 Trying 137.187.182.124... Connected to ncias-p942-v-1.nci.nih.gov. Escape character is '^]'. HEAD / HTTP/1.0 HTTP/1.1 200 OK Date: Thu, 21 Mar 2013 14:47:26 GMT Server: Apache Last-Modified: Tue, 12 Mar 2013 13:52:32 GMT ETag: "302a-4d7ba99db0800" Accept-Ranges: bytes Content-Length: 12330 Connection: close Content-Type: text/html Connection closed by foreign host. $
Some C/C++/Qt Examples
Example 1 - Linux/Unix
http://www.linuxhowtos.org/C_C++/socket.htm. The codes are saved under here.
$ gcc server.c -o server $ gcc client.c -o client $ ./server 51717 $ ./client 192.168.0.21 51717 Please enter the message: Who are you? I got your message
where 192.168.0.21 is the ip address on the server. The server side will show
Here is the message: Who are you?
If everything works correctly, the server will display your message on stdout, send an acknowledgement message to the client and terminate. The client will print the acknowledgement message from the server and then terminate.
- We can actually run the client on a different machine (eg server on my Ubuntu and client on my Windows) although we can also run both client and server on the same machine.
- Once we use the port (51717) one time, we can not use the same port to run it again??? The screen shows an error "ERROR on binding: Address already in use". The problem is we may need to wait until 4 minutes for avoiding this message. See the solution in here or SO_REUSEADDR option in setsockopt(). That is, we just need to change server.c to add the following
... int iOption = 1; // Turn on keep-alive, 0 = disables, 1 = enables ... // Immediately after the declaration of sockfd, we do if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *) &iOption, sizeof(int)) == -1) { error("setsockopt"); exit(1); }
- On Windows, we can use TCPView to see which process is listening on which port, socket status. On Linux, we can use netstat -a command (it gives a long output)
mli@PhenomIIx6:~/Downloads$ sudo netstat -a | grep 51717 tcp 0 0 *:51717 *:* LISTEN
- We can choose any port number between 2000 and 65535.
- If we use 51717 port for example, the server will open that port. But once the program is finished, the port will be closed immediately. Use linux command netstat -lp --inet to check which ports are opened.
Similar examples:
- http://www.thegeekstuff.com/2011/12/c-socket-programming/. This example is similar to Example 1. The server continuously runs and sends the date and time as soon as a client connects to it. To temporarily change the time, use
sudo date +%T -s "10:13:13"
. - http://www.binarytides.com/server-client-example-c-sockets-linux/
- http://www.amparo.net/ce155/socket-ex.html More complicated example
- Print client IP address
Example 2 (in C)
http://www.prasannatech.net/2008/07/socket-programming-tutorial.html
Server side (The code is here):
$ ./tcpserver TCPServer Waiting for client on port 5000 I got a connection from (127.0.0.1 , 36123) SEND (q or Q to quit) : yes RECIEVED DATA = Got it. SEND (q or Q to quit) : how are you RECIEVED DATA = I am fine. SEND (q or Q to quit) : q q ^C $
Client side (The code is here):
$ ./tcpclient Recieved data = yes SEND (q or Q to quit) : Got it. Recieved data = how are you SEND (q or Q to quit) : I am fine.
Example 3 - Mimic browser request
The code is based on the post. http://codebase.eu/tutorial/linux-socket-programming-c/. My local copy of [1].
This is another similar post. http://www.binarytides.com/receive-full-data-with-recv-socket-function-in-c/ which teaches how to receive full data with recv socket function in C.
Testing tcpclient.c
$ g++ tcpclient.cpp $ ./a.out Setting up the structs... Creating a socket... Connect()ing... send()ing message... Waiting to recieve data... 1000 bytes recieved : HTTP/1.1 200 OK Date: Wed, 20 Mar 2013 14:41:54 GMT Expires: -1 Cache-Control: private, max-age=0 Content-Type: text/html; charset=ISO-8859-1 Set-Cookie: PREF=ID=78ef359985426090:FF=0:TM=1363790513:LM=1363790514:S=UO5PtdM9ETqX6Mm_; expires=Fri, 20-Mar-2015 14:41:54 GMT; path=/; domain=.google.com Set-Cookie: NID=67=ENMHn5Br-_nZOPNeS04OI0z2Q7sUQEsfnP4xL0VGR66nnRyAv56lvXER7yrM2TESKJv2cwWinH6LOsW3ZuZdAL6-MJzmFNJzJ6ogNpOlvItoEPiAEycHvRrPLK11qDQx; expires=Thu, 19-Sep-2013 14:41:54 GMT; path=/; domain=.google.com; HttpOnly P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info." Server: gws X-XSS-Protection: 1; mode=block X-Frame-Options: SAMEORIGIN Transfer-Encoding: chunked 8000 <!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find ex Receiving complete. Closing socket... $
Testing tcpserver.c and tcpclient2.c
Server side:
$ ./tcpserver Setting up the structs... Creating a socket... Binding socket... Listen()ing for connections... Connection accepted. Using new socketfd : 4 Waiting to recieve data... 37 bytes recieved : GET / HTTP/1.1 host: www.google.com send()ing back a message... Stopping server... $
Client side (modify tcpclient.c to use IP 127.0.0.1 and port 5556):
$ ./tcpclient2 Setting up the structs... Creating a socket... Connect()ing... send()ing message... Waiting to recieve data... 10 bytes recieved : thank you.#▒ Receiving complete. Closing socket... $
Example 4 - Windows socket (almost implies C++)
Example 5 Get image using Qt
See Chapter 14. Foundation of Qt Development. The code is on https://github.com/arraytools/Qt/tree/master/FQD/Chapter14.
Example 6 Trip planner using Qt
See Chapter 15. Networking on C++ GUI Programming Qt 4. The code is on http://taichi.selfip.net:81/lang/c/qt-book/chap15/.
Basic(s)
Cheat sheet, Tutorial, Crash course
- http://www.pa.msu.edu/~duxbury/courses/phy480/Cpp_refcard.pdf or my local copy.
- How to programming C++ by Matt Mahoney. It gave more explanation like using 'const' pointer to pass large object to avoid overhead of copying.
- C++ pitfalls. It covers references, const keyword, Public, Protected and Private Labels, virtual Methods and mutable Class Members.
- STL reference by Yotam Medini.
- cppreference.com
- learncpp.com
- C++ for C programmers
- C++ crash course for C programmers
- C++ for Statisticians with a focus on interfacing from R and R packages.
Header/Include guard, Preprocessor
#ifndef ... #define ... #endif. See wikipedia and cplusplus.com.
Memory Management
On page 25 of the memory management lecture note, it mentions
- If using int x; the allocation occurs on a region of memory called the stack.
- If using new int; the allocation occurs on a region of memory called the heap.
new and delete operators
Use new/delete instead of malloc()/free() which depends on <cstdlib> in C++. For example, the following code was a modification from Listing 4.22 (p169) <delete.cpp> from the book 'C++ Primer Plus'.
The memory created by new operator is called heap or free store. Forgetting to use delete operator will cause a memory leak. This kind of storage is called dynamic storage which differs from automatic storage and static storage/stack.
#include <iostream> #include <cstring> // strlen() using namespace std; int main() { char * pn = new char(strlen("/home") + strlen("/Downloads") + 1); strcpy(pn, "/home"); cout << pn << endl; cout << strlen(pn) << endl; strcat(pn, "/Downloads"); cout << pn << endl; cout << strlen(pn) << endl; delete [] pn; return 0; }
- new allows to allocate a variable length arrays while allocating arrays on the stack stack size must be constant. See p52 of MIT Open Course.
- new and delete should be used together. See p62 to p67 of the above MIT note.
- Pay attention to the scope of variables. If a variable is declared within a parenthesis, it will evaporate once it exists the parenthesis. See p69 of the above MIT note for the problem and p75 for the solution.
bad_alloc error
http://stackoverflow.com/questions/6833143/how-to-check-memory-allocation-failures-with-new-operator
In C++ there are 2 primary ways in which new allocates memory and each requires different error checking.
The standard new operator will throw a std::bad_alloc exception on failure and this can be handled like a normal exception
try { char* c = new char[100]; } catch (std::bad_alloc&) { // Handle error }
Or alternative the nothrow version of new will simply return NULL on failure
char* c = new (std::nothrow) char[100]; if (!c) { // Handle error }
Virtual functions
may be actual functions or merely placeholders for real functions that derived classes must provide. If you define a virtual function without a body, that means the derived class must provide it (it has no choice, and the program will not compile otherwise). Classes with such functions are called abstract classes, because they aren’t complete classes and are more a guideline for creating actual classes. (For example, an abstract class might state “you must create the Display() method.”) In C++, you can create a virtual function without a body by appending =0 after its signature (also known as a pure virtual function). See OOP Demystified Chapter 4.3: Run-time polymorphism.
C++ videos
Type casting
by declaiming explicitly like (float)5 or using suffix like 5f.
C vs C++ with functions
In non-object programming, we use
function(x, parameter)
In C++ programming, we use
x->function(parameter) // if x is a pointer x.function(parameter) // if x is not a pointer
<cstdlib> vs <stdlib.h>
The first one is for C++ and the other is for C. See here.
this keyword
The this keyword is valid only inside a member function, where it denotes a pointer to the object on which the member function is operating. For example, inside Vec::operator=, the type of this is Vec*, because this is a pointer to the Vec object of which operator= is a member. For a binary operator, such as assignment, this is bound to the left-hand operand. Ordinarily, this is used when we need to refer to the object itself, as we do here both in the initial if test and in the return.
Pointers as a function argument
The following example is coming from http://www.nongnu.org/c-prog-book/online/x641.html. See also cplusplus.com tutorial about pointers.
#include <stdio.h> int swap_ints(int *first_number, int *second_number); int main() { int a = 4, b = 7; printf("pre-swap values are: a == %d, b == %d\n", a, b); swap_ints(&a, &b); printf("post-swap values are: a == %d, b == %d\n", a, b); return 0; } int swap_ints(int *first_number, int *second_number) { int temp; temp = *first_number; *first_number = *second_number; *second_number = temp; return 0; }
The following example is modified from C++ pitalls. Here we create a reference that looks and acts like a standard C++ variable except that it operates on the same data as the variable that it references.
int foo = 3; // foo == 3 int &bar = foo; // foo == 3 bar = 5; // foo == 5
and the same concept of references is used when passing variables.
#include <iostream> using namespace std; void foo( int &i ) { i++; } int main() { int bar = 5; // bar == 5 cout << bar << endl; foo( bar ); // bar == 6 cout << bar << endl; foo( bar ); // bar == 7 cout << bar << endl; return 0; }
More examples from this post.
// OK case. main: int i=6; chgInt(&i); function: void chgInt(int *p); *p = 10 + *p; // Not OK case. main: char *name = "old"; chgStr(name); function: void chgStr(char *n); n = "new"; // This will make a new string, not changing the original one // Correction main: SAME function: void chgStr(char* &n); n = "new";
String, string, string
http://stackoverflow.com/questions/11322200/unable-to-build-my-c-code-with-g-4-6-3
http://stackoverflow.com/questions/2258561/getting-the-length-of-an-array-using-strlen-in-g-compiler
- C++ uses <cstring> for char*, strlen, strcpy ...
- C uses <string.h> for char*
- C++ uses <string> for string class
try { ... } catch { ... } for exception handling
- http://msdn.microsoft.com/en-us/library/6dekhbbc(v=vs.80).aspx
- http://www.cplusplus.com/doc/tutorial/exceptions/
try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; }
Second example.
char *buf; try { buf = new char[512]; if( buf == 0 ) throw "Memory allocation failure!"; } catch( char * str ) { cout << "Exception raised: " << str << '\n'; }
Third example.
try { return grade(s); } catch (domain_error) { return grade(s.midterm, s.final, 0); }
map
The following example is from Chapter 7 of Accelerated C++. See also the example and a list of member types/functions from cplusplus.com. The interesting thing is the elements are ordered by their key at all times (see the example below).
#include <iostream> #include <map> #include <string> using std::cin; using std::cout; using std::endl; using std::map; using std::string; int main() { string s; map<string, int> counters; // store each word and an associated counter // read the input, keeping track of each word and how often we see it while (cin >> s) ++counters[s]; // write the words and associated counts for (map<string, int>::const_iterator it = counters.begin(); it != counters.end(); ++it) { cout << it->first << "\t" << it->second << endl; } return 0; }
template
http://www.cplusplus.com/doc/tutorial/templates/
// function template #include <iostream> using namespace std; template <class T> T GetMax (T a, T b) { T result; result = (a>b)? a : b; return (result); } int main () { int i=5, j=6, k; long l=10, m=5, n; k=GetMax<int>(i,j); n=GetMax<long>(l,m); cout << k << endl; cout << n << endl; return 0; }
Class constructor can take parameter via assignment
For example (see p6 & p76 of the [MIT lecture note)
class Integer { public: int val; Integer(int v) { val = v; cout << "constructor with arg " << v << endl; } }; int main() { Integer i(3); Integer j = 5; }
The output will be
constructor with arg 3 constructor with arg 5
copy constructor / operator=
- See Chapter 11.3 of Accelerate C++
- Cplusplus.com
String, iterator and printing
The iterator is one of string's member types and begin() & end() are two string's member functions with return type of iterators.
Iterator is sort of pointers. You can print the value by using star (*) to deference, use +/- to move it and use != to compare different iterators. Moreover, we can use subset operator [] to get elements (eg iter[-1]).
// string::begin/end #include <iostream> #include <string> int main () { std::string str ("Test string"); for ( std::string::iterator it=str.begin(); it!=str.end(); ++it) std::cout << *it; std::cout << '\n'; return 0; }
Convert std::string to c-string/char *
See stackoverflow A/stackoverflow B and www.cplusplus.com and codeguru.com.
Convert char* to string
std::string has a constructor that takes a char*.
char *path = "Eggs on toast."; std::string str = std::string(path);
Convert string to char*
http://stackoverflow.com/questions/12862739/convert-string-to-char
char * S = new char[R.length() + 1]; std::strcpy(S,R.c_str());
Convert an integer to character string
See www.cplusplus.com.
Convert a numerical number to char
Use
char mychar[256]=""; double number; sprintf_s(mychar, "%0.2f", number);
This will save a number for example -7.035425 to -7.03 as characters.
C++ IO Streams
- http://www.cprogramming.com/tutorial/c++-iostreams.html
- http://www.cplusplus.com/doc/tutorial/files/
The first example is to read the input filename using command line argument (Accelerated C++ Chapter 10.5).
int main(int argc, char **argv) { int fail_count = 0; // for each file in the input list for (int i = 1; i < argc; ++i) { ifstream in(argv[i]); // if it exists, write its contents, otherwise generate an error message if (in) { string s; while (getline(in, s)) cout << s << endl; } else { cerr << "cannot open file " << argv[i] << endl; ++fail_count; } } return fail_count; }
The 2nd example is to hard-code the input filename.
#include <fstream> #include <string> using std::endl; using std::getline; using std::ifstream; using std::ofstream; using std::string; int main() { ifstream infile("in"); ofstream outfile("out"); string s; while (getline(infile, s)) outfile << s << endl; return 0; }
Read a text file with one row only (using getline())
#include <iostream> #include <fstream> #include <string> using namespace std; ifstream fin; fin.open("combobox.txt"); // assume the file uses tab as delimiter if (fin.is_open() == false) { cout << "Can't open file. Bye." << endl; exit(EXIT_FAILURE); } string item; int count = 0; getline(fin, item, '\t'); while (fin) { ++count; cout << count << ": " << item << endl; getline(fin, item, '\t'); } cout << "Done\n"; fin.close();
Read a text file with multiple rows (using stringstream and getline())
With the following examples, we can count the number of columns and number of rows of a text file.
#include <iostream> #include <fstream> #include <string> #include <sstream> // stringstream using namespace std; ifstream fin; fin.open("combobox.txt"); if (fin.is_open() == false) { cout << "Can't open file. Bye." << endl; exit(EXIT_FAILURE); } string line, item; int ncol = 0, nrow = 0; stringstream iss; while(getline(fin, line)) { nrow++; iss << line; while (getline(iss, item, '\t')) { if (nrow == 1 ) ++ncol; cout << item << endl; } iss.clear(); } cout << "There are " << nrow << " rows and " << ncol " columns\n"; fin.close();
If we want to assign the column names to an array of string and elements to 2 2D string arrays, we need to determine the dimension and then declare the variables first.
col_names = new string[ncol]; for(int i=0;i<ncol;i++){ getline(iss, col_names[i], '\t'); } element = new string *[nrow]; stringstream iss; string str; for(int i=0;i<nrow;i++){ getline(fin, line); iss << line; element[i] = new string[ncol]; for(int j=0;j< ncol;j++){ if(getline(ts3, str, '\t') ) { element[i][j]=str; }else{ element[i][j]=string(""); } }
Count number of lines in a text file
int numLines = 0; ifstream in("combobox.txt"); std::string unused; while ( std::getline(in, unused) ) ++numLines; in.close();
Sorting only
- C++ string sorting Note: qsort() in C won't work for string type in C++.
#include <iostream> #include <string> #include <iterator> #include <algorithm> int main() { std::string obj[4] = {"fine", "ppoq", "tri", "get"}; std::sort(obj, obj + 4); std::copy(obj, obj + 4, std::ostream_iterator<std::string>(std::cout, "\n")); // And for vector // #include <vector> // std::vector<std::string> stringarray; // std::sort(stringarray.begin(), stringarray.end()); }
and
#include <stdlib.h> #include <string.h> int compare_cstr(const void* c1, const void* c2) { return strcmp(*(const char**)(c1), *(const char**)(c2)); } int main() { const char* obj[4] = {"fine", "ppoq", "tri", "get"}; qsort(obj, 4, sizeof(obj[0]), compare_cstr); std::copy(obj, obj + 4, std::ostream_iterator<const char*>(std::cout, "\n")); }
Note: The use of ostream_iterator<string>(cout, "\n") was explained & used in Accelerated C++ Chapter 8.3 (Input and output iterators) & 8.4. It was also explained in cplusplus.com.
Return permutation (R's order() function) using 3 approaches
Good example. This is using lambda from C++0x but it can be replaced with simple functor object.
#include <vector> #include <algorithm> #include <iostream> template<class Vals> void sortingPermutation(const Vals& values, std::vector<int>& v){ int size = values.size(); v.clear(); v.reserve(size); for(int i=0; i < size; ++i) v.push_back(i); std::sort(v.begin(), v.end(), [&values](int a, int b) -> bool { return values[a] < values[b]; }); } int main() { std::vector<double> values; values.push_back(24); values.push_back(55); values.push_back(22); values.push_back(1); std::vector<int> permutation; sortingPermutation(values, permutation); typedef std::vector<int>::const_iterator I; for (I p = permutation.begin(); p != permutation.end(); ++p) std::cout << *p << " "; std::cout << "\n"; }
This will return values 3, 2, 0, 1. In fact, the code is so general: if I add #include <string> and change double to std::string in the declaration of values, the code works for string data type.
Method 2. You can use std::sort to sort the list of pairs {(24, 0), (55, 2), (22, 0), (1, 1)}.
#include <vector> #include <algorithm> #include <utility> typedef std::pair<double, int> Pair; struct CmpPair { bool operator()(const Pair& a, const Pair& b) { return a.first < b.first; } }; void sortingPermutation( const std::vector<double>& values, std::vector<int>& permutation) { std::vector<Pair> pairs; for (int i = 0; i < (int)values.size(); i++) pairs.push_back(Pair(values[i], i)); std::sort(pairs.begin(), pairs.end(), CmpPair()); typedef std::vector<Pair>::const_iterator I; for (I p = pairs.begin(); p != pairs.end(); ++p) permutation.push_back(p->second); } #include <iostream> int main() { std::vector<double> values; values.push_back(24); values.push_back(55); values.push_back(22); values.push_back(1); std::vector<int> permutation; sortingPermutation(values, permutation); typedef std::vector<int>::const_iterator I; for (I p = permutation.begin(); p != permutation.end(); ++p) std::cout << *p << " "; std::cout << "\n"; }
This will give the same result as above. In fact, the code is so general: if I add #include <string> and change double to std::string in the declaration of values, the code works for string data type. See also c version http://stackoverflow.com/questions/2804493/finding-unique-elements-in-an-string-array-in-c.
Method 3. Create a vector of ints 0..N and then sort that array with a comparison function that compares the corresponding elements of the vector you're trying to find the sorted permutation of. Something like:
#include <iostream> #include <algorithm> #include <vector> template<class T> class sorter { const std::vector<T> &values; public: sorter(const std::vector<T> &v) : values(v) {} bool operator()(int a, int b) { return values[a] < values[b]; } }; template<class T> std::vector<int> order(const std::vector<T> &values) { std::vector<int> rv(values.size()); int idx = 0; for (std::vector<int>::iterator i = rv.begin(); i != rv.end(); i++) *i = idx++; std::sort(rv.begin(), rv.end(), sorter<T>(values)); return rv; } int main() { std::vector<double> values; values.push_back(24); values.push_back(55); values.push_back(22); values.push_back(1); std::vector<int> permutation; permutation = order(values); typedef std::vector<int>::const_iterator I; for (I p = permutation.begin(); p != permutation.end(); ++p) std::cout << *p << " "; std::cout << "\n"; }
This also gives the same result. In fact, the code is so general: if I add #include <string> and change double to std::string in the declaration of values, the code works for string data type.
Scope
Method 1: Created object cannot be used in other places.
Class aClass { aClass(); void foo(); }; aClass::aClass() { bClass *obj = new bClass; } void aClass::foo() { obj->myfunction(); // Won't work!! }
Method 2: Created object can be used within the class.
Class aClass { aClass(); void foo(); }; aClass::aClass() { obj = new bClass; } void aClass::foo() { obj->myfunction(); }
(C++11) Lambda functions
A lambda function is essentially an anonymous function (a function without a name) that’s defined inline.
- http://msdn.microsoft.com/en-us/library/dd293608(v=vs.100).aspx
- http://en.cppreference.com/w/cpp/language/lambda
- http://candrews.net/blog/2011/07/understanding-c-0x-lambda-functions/
- sorting and index
STL vector vs C++ new
Basic STL vector
- http://www.cprogramming.com/tutorial/stl/vector.html
- http://www.cplusplus.com/reference/vector/vector/
WINVER
http://stackoverflow.com/questions/1439752/what-is-winver WINVER determines the minimum platform SDK required to build your application, which in turn will determine at compile time which routines are found by the headers.
You can use this to verify, at compile time, that your application will work on Windows 2000 (0x0500), for example, or on Windows XP (0x0501).
This was used in win32 disk imager program.
Colon
- Single colon ":" was used in inheritance. For instance,
class fourwheeler {} class car : public fourwheeler {}
- Double colons was used to define/refer a class's function/method. Sometimes it can be used to resolve namespace problem. See here.
void MyClass::setText() {}
Protected vs private members
Private members are only accessible within the class defining them.
Protected members are accessible in the class that defines them and in classes that inherit from that class.
Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.
Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ Lite for a better understanding of the issue. This question about protected variables might also help.
'friend' class and function
- http://www.cplusplus.com/doc/tutorial/inheritance/
- http://www.cprogramming.com/tutorial/friends.html
alignment of pointers
https://stat.ethz.ch/pipermail/r-devel/2013-August/067314.html
Debugging
Tools
cmake
On Windows, it will be installed on C:\Program Files (x86)\Cmake 2.8 folder. By default, it is not added to system PATH. The 'Cmake' program will ask for source, binary folders and the Compiler option. After clicking 'configure' and 'generate' buttons, it will create VS solution file and we can double click the solution file to open the project in Visual Studio. In Visual Studio, we can just build the solution (Ctrl + Shift + B). When we want to debug the code, we should 1. right click on project and select property. Change the working directory to the source code (note that .exe file will be generated there). 2. Set the project as the starting project.
Some C++ Projects
Approximate nearest neighbor search
The R wrap is here
NGS++
A programming library in C++11 specialized in manipulating both next-generation sequencing (NGS) datasets and genomic information files. See the paper.
LIBSVM
Tophat
It also requires the packages
- Boost
- SamTools and its source code
Parana2
It also depends on a few other tools.
- Bio++ - a set of C++ libraries for Bioinformatics, including sequence analysis, phylogenetics, molecular evolution and population genetics.
- Boost
- GMP - The GNU Multiple Precision Arithmetic Library
- MPFR - C library for multiple-precision floating-point computations with correct rounding.
- pugixml - light-weight C++ XML processing library.
Short read alignment with populations of genomes
https://github.com/viq854/bwbble
Janus-comprehensive tool investigating the two faces of transcription
It depends on bamtools.
RNA-Pareto
Interactive Analysis of Pareto-optimal RNA Sequence-Structure Alignments
Windows programming
Resource
- http://www.stanford.edu/class/cs193w/
- Petzold Programming Windows 1998 with source code for download
- Kruglinski Programming Microsoft Visual C++, 1998
- Xoax which contains tutorials for C++, OpenGL, Win32 C++ and more.
- ProgrammingKnowledge about Visual C++ Windows Forms Application Tutorial in Youtube.
- Simple GUI calculator using VS C++/CLR
Difference between Win32 project and CLR (common language runtime) project
See here.
A Win32 project is used if you want to end up with a DLL or a Win32 application usually using the bare WinAPI. A CLR project is used to create C++/CLI project, i.e. to use C++/CLI to target the .NET platform.
The main difference between projects is what Visual Studio comes up with in terms of pre-created files. A windowed Win32 application for example (what you get when you choose Win32 project, but not a DLL) is created with a file for resources (menus, acceleators, icons etc.) and some default code to create and register a window class and to instantiate this window.
Quoted from http://en.wikipedia.org/wiki/Common_Language_Runtime
The Common Language Runtime (CLR) is the virtual machine component of Microsoft's .NET framework and is responsible for managing the execution of .NET programs. In a process known as Just-in-time compilation, the compiled code is converted into machine instructions that, in turn, are executed by the computer's CPU. The CLR provides additional services including memory management, type safety and exception handling. All programs written for the .NET framework, regardless of programming language, are executed by the CLR. It provides exception handling, garbage collection and thread management. CLR is common to all versions of the .NET framework.
The CLR is Microsoft's implementation of the Common Language Infrastructure (CLI) standard.
Difference between Win32, MFC and .NET
Using the CLR will provide you with the most expressive set of libraries (the entire .NET framework), at the cost of restricting your executable to requiring the .NET framework to be installed at runtime, as well as limiting you to the Windows platform (however, all 4 listed technologies are windows only, so the platform limitation is probably the least troublesome).
However, CLR requires you to use the C++/CLI extensions to the C++ language, so you'll, in essense, need to learn some extra language features in order to use this. Doing so gives you many "extras," such as access to the .net libraries, full garbage collection, etc.
Using Win32 directly provides the smallest executables, with the fewest dependencies, but is more work to write. You have the least amount of helper libraries, so you're writing more of the code.
Win32 is the raw, bare-metal way of doing it. It's tedious, difficult to use, and has alot of small details you need to remember otherwise things will fail in relatively mysterious ways.
MFC builds upon Win32 to provide you an object oriented way of building your application. It's not a replacement for Win32, but rather an enhancement - it does alot of the hard work for you.
System.Windows.Forms (which is what I assume you meant by CLR) is completely different, but has large similarities to MFC from its basic structure. It's by far the easiest to use, but requires the .NET framework, which may or may not be a hindrance in your case.
Why not MFC
http://win32-framework.sourceforge.net/explanation.htm The website also provides an alternative software called Win32++ to replace MFC. It also provides useful links for C++ compilers, tools, tutorial and references.
Qt
- C++ GUI Programming with Qt 4
- Qt Graphics http://qt-project.org/doc/qt-5.0/qtdoc/topics-graphics.html
- 2D Painting Example QPainter and QGLWidget can be used together to display accelerated 2D graphics on supported hardware. OpenGL examples are here.
wxwidgets
OpenGL Programming on Windows
We need to include
#include <gl/gl.h> #include <gl/glu.h>
And go to project's link properties and enter <opengl32.lib> & <glu32.lib>. Check the directory C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include and C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib
header files are: gl\gl.h and glu.h libraries are: openGL32.lib and GLU32.lib
x64 libs can be found in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\lib\x64 you can put freeglut lib and header files to those locations to use freeglut with visual studio 2010 when you copy freeglut DLLs to C:\Windows\System32 don’t copy 64 bit DLL to syswow64 this gives a freaky error 0xc000007b when running code. Don’t know what it mean, but if you have freeglut only in system32 you going to be fine.
Resource
- [Book] OpenGL Programming Guide: The Official Guide to Learning OpenGL. Online book ver 1.1
- http://nehe.gamedev.net/
- http://homepage.cs.uiowa.edu/~cwyman/classes/common/howto/winGLUT.html. The instruction there assumes the Windows XP. On my Windows 7 and VS2010 machine, I see <glu32.lib> in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib.
- http://www.cprogramming.com/tutorial/opengl_first_opengl_program.html
- http://www.devshoe.net/2012/08/opengl-programming-in-windows-7-64-bit.html
- http://www3.ntu.edu.sg/home/ehchua/programming/opengl/HowTo_OpenGL_C.html (Notice the comment at the end)
- http://www.opengl-tutorial.org/beginners-tutorials/tutorial-1-opening-a-window/
- OpenGL on Windows
- http://www.nullterminator.net/opengl32.html (hmv, without using glut). See also a discussion on here why it is platform specific to initialize OpenGL.
- Check OpenGL version: glview
- Setting up freeGLUT on Visual Studio 2010
- Google: windows opengl programming tutorial visual studio
Example 1
http://openglbook.com/setting-up-opengl-glew-and-freeglut-in-visual-c/
- Download freeglut (freeglut-MSVC-2.8.0-1.mp.zip) & glew (glew-1.9.0-win32.zip)
- Copy files include and lib to appropriate location
- Copy freeglut.dll to the Project's Release or Debug folder
I don't need Step 5 (Compiler) and Step 6 (Linker).
I keep a copy of the instruction in Evernote.
Example 2
Teapot and Glut shapes (WireTeapot, SolidTeapot, SolidCube & SolidSphere) from http://openglsamples.sourceforge.net/
Example 3 (no Glut, Windows OS only)
http://www.nullterminator.net/opengl32.html
Examples from opengl.org
http://www.opengl.org/sdk/docs/tutorials/
Example of American Flag
http://www.youtube.com/watch?v=9xjBlde4Cew