Skip to content

Instantly share code, notes, and snippets.

@mgarg1
mgarg1 / stl_functions.cpp
Last active April 3, 2016 20:16
Important Cpp snipets
//using next permutation
while(next_permutation(vec.begin(), vec.end()) ){
// do some processing on vec
}
//using sort
std::sort (myvector.begin(), myvector.begin()+4)
std::sort (myvector.begin(), myvector.end())
//intialise vector with another array
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
@mgarg1
mgarg1 / Double_Dimension_Array_Class.cpp
Last active July 22, 2019 08:59
Double Dimension Array
// # define NDEBUG
# include <assert.h>
class array2D{
int rows,cols.**arr;
public:
// array2D():array2D(0,0,0){}
array2D(int r,int c,int val):rows(r),cols(c),arr(nullptr){
arr = new int *[rows];
@mgarg1
mgarg1 / qsort_2d_array.c
Last active April 3, 2016 20:15
Sort a 2-d array using ANSI qsort
#include <stdio.h>
int compare (const void *elem1, const void *elem2){
return *(int*)elem1 - *(int*)elem2;
}
#define ROW 5
#define COL 2
int main()
@mgarg1
mgarg1 / Array2D_AOOPS.cpp
Created October 8, 2014 04:53
Overloading subscript operator [ ] for 2-d arrays
#include <iostream>
#include <cstddef>
using namespace std;
template <typename T>
class Array2D {
public:
Array2D(size_t nr, size_t nc) : n_rows(nr), n_cols(nc), data(new T[n_rows*n_cols]) {}
~Array2D() { delete [] data; }
@mgarg1
mgarg1 / for_each functor
Last active April 3, 2016 20:14
use of functor for each loop
template<typename FUNCTION>
inline void loop(int n, FUNCTION f) {
for (int i = 0; i < n; ++i) {
f(i);
}
}
// ...
loop(5, [](int jj) { std::cout << "This is iteration #" << jj << std::endl; } );
@mgarg1
mgarg1 / debugging_utilities.c
Last active December 6, 2017 08:03
Some of the debugging utilities
#ifdef assert
#undef assert
#endif
#define assert(expr,i) \
if (!(expr)) { \
std::cerr << "Error at line " << __LINE__ << ": " \
<< "assert(" #expr ");" <<"value of i: "<<i<< std::endl; \
exit(EXIT_FAILURE); \
}
C++ concepts to learn:
SFINAE
pimpl
RTTI
C++ links to learn:
https://www.pluralsight.com/a/subscribe/step1?sku=IND-M-PLUS&isTrial=true&v=a
http://www.smu.edu/Guildhall/Admissions/GuildhallPreparation/ProgrammingPreparationCourse
http://www.codeguru.com/cpp/cpp/
#define COMMAND(NAME) { #NAME, NAME ## _command }
struct command commands[] =
{
COMMAND (quit),
COMMAND (help),
...
};
struct command
@mgarg1
mgarg1 / upen1.cpp
Last active October 2, 2016 22:57
working soln1
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
int main(){
int N;
cin >> N;