C++ Tidbits

From Minor Miracle Software
Jump to: navigation, search

C++ Tidbits


  • Day Of Year (DOY) (1-366)
date today = day_clock::local_day();
std::cout << "doy " << today.day_of_year() << std::endl;
  • Seconds
boost::chrono::duration<double> sec = boost::chrono::system_clock::now();
std::cout << "took " << sec.count() << " seconds\n"; 
  • Duration in Seconds
boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();
// do something
boost::chrono::duration<double> sec = boost::chrono::system_clock::now() - start;
std::cout << "took " << sec.count() << " seconds\n";


  • Console wait for key entry to end.
std::cout << "Press any key to end..." << std::endl;
return 0;
  • structs - The assignment operator each element in a struct to the other. tm = tm;
  • Cast without a warning message
int x;
double y = 10.1;
double z = 20.2;

x =  static_cast<int>(y + z);

  • Double and Float

Any divide or multiply creates rounding errors that can't be fixed. The solution is to use a library like Boost or STL.

  • Splitting a double into integer and fraction parts.
 double doubt = 125568.989;
 int tv_sec = (int) doubt;  // works (time_t(floor(doubt+0.5e-6)));
 int tv_usec = (int((doubt+0.5e-6L-floor(doubt+0.5e-6))*1000.0)); // 1000.0 is three decimal places
 printf("Modulus Double Test: double %f, integer %d, fraction %d \n", doubt, tv_sec, tv_usec );

Prints out

Modulus Double Test: double 125568.989000, integer 125568, fraction 989
  • Combine two integers into a double.
int Seconds = 1577744509;
int mills = 704;
printf("Seconds %d.\n", Seconds);
printf("mills %d.\n", mills);
double new_d = double(Seconds)+ double(mills) *1.0e-3;
printf("double is %f.\n", new_d);

Prints out
Seconds 1577744509.
mills 704.
double is 1577744509.704000.

  • Getting the class name

class AnyClass;

typeid( AnyClass ).name();


"class AnyClass"


  • Fetch the class name for an object. Get the object's class name. CString name_cs = typeid(data).name();

Global Objects

Microsoft Visual Studio C++ and Linux C++
Using extern a variable can be declared in one file and have a presence in other selected files.

int i = 42; // declaration and definition

extern int i;  // declaration only. same as i in FileA

extern int i;  // declaration only. same as i in FileA

int i = 43; // LNK2005! 'i' already has a definition.
extern int i = 43; // same error (extern is ignored on definitions)

Internal Links

Parent Article: Main Page