Skip to content

Instantly share code, notes, and snippets.

@xdl
Last active January 2, 2016 19:29
Show Gist options
  • Save xdl/8350882 to your computer and use it in GitHub Desktop.
Save xdl/8350882 to your computer and use it in GitHub Desktop.

C++ Cheatsheet

Functions

  • Declared like so:

      int encode_character(char c, char multitap);
    
  • To pass a value by reference, prepend the & before the argument name:

      int encode_character(char c, char &passedbyreference);
    
  • Pointers/arrays, e.g. char multitap[512] can be passed to functions with the parameter: char* regardless.

  • String literals can be passed to functions as either type const char* or string, if the <string> library is included.

Files and streams

  • done with ifstream and ofstream in <fstream>:

      ifstream in_stream;
      ofstream out_stream;
    
      in_stream.open("mydata.txt");
      outstream.open("output.txt");
    
  • NOTE that if passing the file path as a string object, these need to be converted with c_str()

Do stuff with in_stream, such as:

  • Check for failure:

      if(in_stream.fail()) {
      	exit(1);
      }
    
  • Read single characters with .get, output them with .put. If you don't want it, can also put it back with ifstream.putback(ch)

  • Alternatively, can use the << and >> operators to pipe ints and floats into the input/output.

  • Can be arguments to functions, but need to be passed as reference:

      void delegateStreaming(ifstream &input_stream, ofstream &output_stream) {
      	//stuff here.
      }
    
  • .eof() flag is set to true if stream is pointing to eof, and a .get or >> causes the eof to be read. Therefore the proper way to start parsing an input stream is:

      in_stream.open("myfile.txt");
    
      char ch;
      in_stream.get(ch); //this will either read the first character, or if it is empty, raise the eof flag.
    
      while(!in_stream.eof()) {
      	//do something with the character ch here.
      	in_stream.get(ch); //get the next one
      }
      
      in_stream.close();
    

Arrays/Iterables/Vectors

  • Get the largest element, and its index, in an iterable, with max/min_elements (in <algorithm>) and distance (in <iterator>):

      //vecA = [1,2,3,5,2];
      vector<int>::iterator maxptr = max_elements(vecA.begin(), vecA.end());
      int max_val = *maxptr;
    
      int index = distance(vecA.begin(), maxptr);
    
  • appending to vector: vec.push_back(blah);

  • remove elements from vector with vec.erase(vec.begin() + i) where i is the ith element of the vector

  • remove last element with vec.pop_back()

  • when iterating through vectors from the end, make sure to use int rather than unsigned int:

      //bad:
      for (unsigned int = V.size() - 1; i >= 0; i--) {
      	//when i is decremented past 0, unsigned representation gives massive value so you won't break out of the loop, but rather more likely get a segfault instead.
    

    }

  • Initialise arrays to value:

      char mychararr[10] = {'a','b','c'} //unspecified values are all set to 0 (for an arrays of chars, this corresponds to '\0'
    
  • Initialise vectors to same value:

      vector<int> V(20, 0); //length 20, all have value 0
    
  • 2D arrays are initialised like char arr2d[width][height]

Strings and char* manipulations

  • <string> are also namespaced under std.

  • For strings, the = operator generally makes a copy of the right operand:

      char str1[5]; //initialise to something.
      string str2("initialised");
    
      string str3 = str1; //copies str1 content into str3
      string str3 = str2; //copies str2 content into str3
    
      //constructor passes by value as well:
      string str3(str1); //copies str1 content into str3
      string str3(str2); //copies str2 content into str3
    
  • To delete characters from a string (without making new copy), use string.erase(start, finish), where start and finish are indices.

  • Be careful about deleting the first character though - use string.erase(string.begin()) instead of string.erase(0) as they do different things.

  • In fact, better just to use str.erase(0,1) for deleting the first character.

  • String literals can be assigned to char* only at instantiation:

      char charptr[10] = "hi there!";
    
  • If you want to assign a string literal to them later, you must use strcpy (from <cstring>):

      strcpy(charptr, "hi again"); //string literal
      strcpy(charptr, properstring.c_str()); //string object
    
  • Get the number of characters in a string with str.size() (or str.length()).

  • Get the last element of string object with:

      if (!myStr.empty()) {
      	char lastChar = *myStr.rbegin();
      }
    
  • Get a section of a string (newly created) with substr:

      string str = "We think in generalities, but we live in details.";
    
      string str2 = str.substr (12,12);   // "generalities"
    
      int pos = str.find("live");         // position of "live" in str
    
      string str3 = str.substr (pos);     // get from "live" to the end
    
  • Ways of reversing string objects:

      //string approach
      string str = str1;
      string rts(str.rbegin(), str.rend());
    
      //char* approach
      int length= strlen(str1);
      for (int i = length-1; i >= 0; i--) {
      	str2[length-i-1] = str1[i];
      }
      str2[length] = '\0';
    

*strtok for splitting strings:

	int main ()
	{
		char str[] ="- This, a sample string.";
		char * pch;
		printf ("Splitting string \"%s\" into tokens:\n",str);
		pch = strtok (str," ,.-");
		while (pch != NULL)
		{
			printf ("%s\n",pch);
			pch = strtok (NULL, " ,.-");
		}
		return 0;
	}
  • Iterate through char*:

      for (int i = 0; plaintext[i] != '\0'; i++) {
      	//do something
      }
    
  • Get the length of a char* (not allocated memory, but from char[0] to '\0'):

      int strlen(charptr);
    
  • Other potentially useful <cstring> functions:

      char* strchr(const char*, char ch); //gets pointer to first occurrence of ch in char*
      char* strcat(char* destination, const char* source) //appends source to destination
      char * strstr([const] char* str, const char* str2); returns pointer to first occurrence of str2 in str.
    
  • For a const char*, individual characters can be referenced as charptr[0], and to use only part of the char* (e.g. omitting first character) can be done with pointer arithmetic: charptr + 1

Character manipulation

  • Ascii numbers:

      int n_A = 'A'; // 65
      int n_Z = 'Z'; // 90
      int n_a = 'a'; // 97
      int n_z = 'z'; // 122
      int n_0 = '0'; // 48
      int n_9 = '9'; // 57
    
  • converting an int (0-9) to ascii character:

      char c = '0' + my_int;
    
  • converting a char into an int:

      int a = c - '0';
    

Self explanatory from <cctype>:

  • int isalpha(char ch)
  • int islower(char ch)
  • char tolower(char ch)
  • int isdigit(char ch)
  • char toupper(char ch)
  • int isspace(char ch)

Maps

  • Checking equality (same keys, same values) of two maps is simply done by m1 == m2

  • Check if a key exists with:

      if (m1.find("mykey") == m1.end()) {
      	//not found
      }
    
  • Could use maps instead of switches, but might need to justify the cost of using them (lookup time for map is O(logn) and (n*) O(logn) time for insertion, vs O(n/2) for average switch case.

Makefile

Makefile template:

	all: mycppcode

	mycppcode: main.o mycppcode.o
		g++ -Wall -g main.o mycppcode.o -o mycppcode

	main.o: main.cpp mycppcode.h
		g++ -Wall -g -c main.cpp mycppcode.h

	mycppcode.o: mycppcode.cpp mycppcode.h
		g++ -Wall -g -c mycppcode.cpp mycppcode.h

	# For cleaning:

	compiled = mycppcode.h.gch *.o mycppcode

	clean:
		rm -f $(compiled)

Misc

  • For meaningful series of values, can do something like

      enum Chess { Black, White}; //shorthand for const int Black = 0, const in White = 1;
    
  • For meaningful values, can declare them as global constants or with preprocessor define:

      const int SIGNIGICANT_VALUE = 12;
      #define SIGNIFICANT VALUE  12
    
  • Header files should take the form:

      #ifndef HEADERSTUFF
      #define HEADERSTUFF
      	
      	//function, constant declarations go here
    
      #endif
    
  • Get the larger of two values (from <algorithm>):

      max(3,4) //4
    
  • Static casting: static_cast<type>(expression), e.g. char c = static_cast<char>(4)

  • Finding lengths of any arrays, e.g. ints: sizeof(int_arr)/sizeof(int). The only issue is when the array gets passed to a function - array type is automatically converted to pointer type, so this can't really be done (without templates).

  • In vim, use :set nocompatible for sensible undoing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment