C++ Tidbits

From Minor Miracle Software
Jump to: navigation, search

C++ Tidbits

Boost

  • 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";

C++

  • Console wait for key entry to end.
std::cout << "Press any key to end..." << std::endl;
getchar();
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();

returns

"class AnyClass"

Class

  • 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.

//fileA.cpp
int i = 42; // declaration and definition

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

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

//fileD.cpp
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