Skip to content

Instantly share code, notes, and snippets.

@conleec
Created June 6, 2019 01:19
Show Gist options
  • Select an option

  • Save conleec/6467eff72621ef6994013660a3f7da0e to your computer and use it in GitHub Desktop.

Select an option

Save conleec/6467eff72621ef6994013660a3f7da0e to your computer and use it in GitHub Desktop.
C++ Misc Notes
@conleec
Copy link
Author

conleec commented Jun 16, 2019

ALL elements of an array can be initialized at once like so

const int days_in_year {365};
double hi_temps [days_in_year] {0}; //init ALL to zero

There is NO BOUNDS CHECKING in C++ arrays!!!

  • Up to user to check bounds

If you name an array but don't indicate how many elements, C++ will automatically determine based on initilization

char vowels[] {'a', 'e', 'i', 'o', 'u'} // determines vowels has 5 elements

Multi-dimensional arrays are organized by Rows and Columns

int movie_reviews [4][5] {
			{0, 1, 2, 3, 4},
			{5, 6, 7, 8, 9},
			{10, 11, 12, 13, 14},
			{15, 16, 17, 18, 19}
	};

	for (int i = 0; i < 4; ++i) {
		for (int j = 0; j < 5; ++j) {
			cout << movie_reviews[i][j] << "\t";
		}
		cout << endl;
	}

VECTORS

To declare vector, you must:

#include <vector> // vector library
using namespace std;

vector <char> vowels;
vector <int> test_scores;

Vectors are OBJECTS and have methonds

You can do things like:

vector <double> hi_temps (365, 80.0) // will create 365 elements, ALL initialized to 80.0

vectors are always initialized by default

vectors can be accessed with [] sub selector (which offers NO bounds checking

vectors can also be accessed with the .at() method like so:

vector <int> test_scores {100, 90, 80, 70, 60};
cout << test_scores.at(1) // will display index 1, or 90 in this case

Static cast to convert types

uses syntax: static_cast(int variable here)

for instance:

int total {60}, count {3};
float average = static_cast<float>(total) / count;
cout << "The average is: " << average << endl;

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