From f6aba50ba36927f22c7f4f7ae46a8b3dbf35921e Mon Sep 17 00:00:00 2001 From: richelbilderbeek Date: Tue, 2 Jan 2018 18:43:17 +0100 Subject: [PATCH] Improve layout and text and code --- content/CppCmathH.md | 59 +--------- content/CppCoalescentTreeModel.md | 166 +--------------------------- content/CppCodeSmell.md | 163 ++++++++------------------- content/CppCodeSnippets.md | 33 +----- content/CppCodeTemplate.md | 62 ++--------- content/CppCodecvtH.md | 35 +----- content/CppCodingStandard.md | 44 +------- content/CppColorToRgb.md | 46 +++----- content/CppColorToRgb.txt | 11 -- content/CppStdAccumulate.md | 69 +++--------- content/CppStdAccumulateExample1.md | 129 +++------------------ content/CppStdAccumulateExample2.md | 148 +++++++------------------ 12 files changed, 154 insertions(+), 811 deletions(-) delete mode 100755 content/CppColorToRgb.txt diff --git a/content/CppCmathH.md b/content/CppCmathH.md index 41056aee..171ba9f0 100644 --- a/content/CppCmathH.md +++ b/content/CppCmathH.md @@ -1,56 +1,7 @@ +# ([C++](Cpp.md)) [cmath.h](CppCmathH.md) -  - -  - -  - -  - -  - -([C++](Cpp.md)) [cmath.h](CppCmathH.md) -========================================= - -  - -[cmath.h](CppCmathH.md) is an [STL](CppStl.md) [header -file](CppHeaderFile.md) for mathematical [functions](CppFunction.md). - -  - - --------------------- - ` #include ` - --------------------- - -  - -  - -  - -  - -  - -List of functions in [cmath.h](CppCmathH.md) (incomplete) ----------------------------------------------------------- - -  - - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` std::abs std::acos std::asin std::atan std::atan2 std::ceil std::cos std::cosh std::exp std::fabs std::floor std::fmod std::labs std::ldexp std::ldiv std::log std::log10 std::modf std::pow std::sin std::sinh std::sqrt std::tan std::tanh` - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -  +[cmath.h](CppCmathH.md) is an [STL](CppStl.md) [header file](CppHeaderFile.md) for mathematical [functions](CppFunction.md). +```c++ +#include +``` diff --git a/content/CppCoalescentTreeModel.md b/content/CppCoalescentTreeModel.md index 16a5a563..ca8e39c3 100644 --- a/content/CppCoalescentTreeModel.md +++ b/content/CppCoalescentTreeModel.md @@ -1,166 +1,2 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [CoalescentTreeModel](CppCoalescentTreeModel.md) -================================================================== - -  - -Technical facts ---------------- - -  - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/CppCoalescentTreeModel.pri ---------------------------------------------------- - -  - - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - ` INCLUDEPATH += \     ../../Classes/CppCoalescentTreeModel SOURCES += \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelsimulation.cpp \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelparameters.cpp \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelhelper.cpp HEADERS  += \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelsimulation.h \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelparameters.h \     ../../Classes/CppCoalescentTreeModel/coalescenttreemodelhelper.h OTHER_FILES += \     ../../Classes/CppCoalescentTreeModel/Licence.txt` - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelhelper.h ----------------------------------------------------- - -  - - ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #ifndef COALESCENTTREEMODELHELPER_H #define COALESCENTTREEMODELHELPER_H #include "rate.h" #include namespace ribi { namespace ctm { struct Parameters; struct Helper {   using Rate = ribi::units::Rate;   enum class Part { phylogeny, branch_lengths };   Helper();   ///Calculate the likelihood of the candidate parameters in generating the dataset   double CalcLogLikelihood(     const std::string& newick,     const Rate& birth_rate,     const Rate& death_rate   ) const;   ///Uses DDD package   double CalcLogLikelihoodDdd(     const std::string& newick,     const Rate& birth_rate,     const Rate& death_rate,     const Part part   ) const;   ///Uses laser package   double CalcLogLikelihoodLaser(     const std::string& newick,     const Rate& birth_rate,     const Rate& death_rate   ) const;   ///Uses DDD package   void CalcMaxLikelihood(     const std::string& newick,     Rate& birth_rate,     Rate& death_rate,     const Part part = Part::phylogeny   ) const;   std::string CreateSimulatedPhylogeny(     const Parameters& parameters   ) const;   private:   #ifndef NDEBUG   static void Test() noexcept;   #endif }; } //~namespace ctm } //~namespace ribi #endif // COALESCENTTREEMODELHELPER_H` - ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelhelper.cpp ------------------------------------------------------- - -  - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #include "coalescenttreemodelhelper.h" #include #include #include #include #include #include "RInside.h" #include "fileio.h" #include "testtimer.h" #include "coalescenttreemodelparameters.h" #include "phylogeny_r.h" #include "trace.h" #include "ribi_rinside.h" ribi::ctm::Helper::Helper() {   #ifndef NDEBUG   Test();   #endif } double ribi::ctm::Helper::CalcLogLikelihood(   const std::string& newick,   const Rate& birth_rate,   const Rate& death_rate ) const {   return CalcLogLikelihoodLaser(     newick,     birth_rate,     death_rate   ); } double ribi::ctm::Helper::CalcLogLikelihoodDdd(   const std::string& newick,   const Rate& birth_rate,   const Rate& death_rate,   const Part part ) const {   assert(!newick.empty());   auto& r = ribi::Rinside().Get();   r.parseEval("library(ape)");   r.parseEval("library(DDD)");   r["newick"] = newick;   r.parseEval("phylogeny <- read.tree(text = newick)");   r.parseEval("branch_lengths <- phylogeny$edge.length");   r["lambda"] = birth_rate.value();   r["mu"] = death_rate.value();   // model of time-dependence:   // - 0: no time dependence   // - 1: speciation and/or extinction rate is exponentially declining with time   // - 2: stepwise decline in speciation rate as in diversity-dependence without extinction   // - 3: decline in speciation rate following deterministic logistic equation for ddmodel = 1   r["model_of_time_dependence"] = 0;   // conditioning:   // - 0: conditioning on stem or crown age   // - 1: conditioning on stem or crown age and non-extinction of the phylogeny   // - 2: conditioning on stem or crown age and on the total number of extant taxa (including missing species)   // - 3: conditioning on the total number of extant taxa (including missing species)   r["conditioning"] = 1;   // Likelihood of what:   // - 0: branching times   // - 1: the phylogeny   switch (part)   {     case Part::branch_lengths: r["likelihood_of_what"] = 0; break;     case Part::phylogeny     : r["likelihood_of_what"] = 1; break;   }   // Show parameters and likelihood on screen:   // - 0: no   // - 1: yes   r["show_parameters_and_likelihood_on_screen"] = 0;   // first data point is:   // - 1: stem age   // - 2: crown age   r["first_data_point_is"] = 2;   r.parseEval(     "log_likelihood_ddd <- bd_loglik("     "  pars1 = c(lambda,mu),"     "  pars2 = c("     "    model_of_time_dependence,"     "    conditioning,"     "    likelihood_of_what,"     "    show_parameters_and_likelihood_on_screen,"     "    first_data_point_is"     "  ),"     "  brts=branch_lengths,"     "  missnumspec = 0"     ")"   );   Rcpp::DoubleVector v = r["log_likelihood_ddd"];   assert(v.size() == 1);   return v[0]; } double ribi::ctm::Helper::CalcLogLikelihoodLaser(   const std::string& newick,   const Rate& birth_rate,   const Rate& death_rate ) const {   assert(!newick.empty());   auto& r = ribi::Rinside().Get();   r.parseEval("library(ape)");   r.parseEval("library(laser)");   r["newick"] = newick;   r.parseEval("phylogeny <- read.tree(text = newick)");   r.parseEval("branch_lengths <- phylogeny$edge.length");   r["lambda"] = birth_rate.value();   r["mu"] = death_rate.value();   Rcpp::DoubleVector v     = r.parseEval("calcLHbd(x = branch_lengths, r = lambda - mu, a = mu / lambda)"   );   assert(v.size() == 1);   return v[0]; } void ribi::ctm::Helper::CalcMaxLikelihood(   const std::string& newick,   Rate& birth_rate,   Rate& death_rate,   const Part part ) const {   assert(!newick.empty());   auto& r = ribi::Rinside().Get();   r.parseEval("library(ape)");   r.parseEval("library(DDD)");   r["newick"] = newick;   r.parseEval("phylogeny <- read.tree(text = newick)");   r.parseEval("branch_lengths <- phylogeny$edge.length");   switch (part)   {     case Part::branch_lengths: r["part"] = 0; break;     case Part::phylogeny     : r["part"] = 1; break;   }   r.parseEval(     "max_likelihood <- bd_ML("     "  brts = branch_lengths,"     "  cond = 1," // # cond == 1 : conditioning on stem or crown age and non-extinction of the phylogeny     "  btorph = part"     ")"   );   r.parseEval("lambda0 <- max_likelihood$lambda0");   r.parseEval("mu0 <- max_likelihood$mu0");   r.parseEval("conv <- max_likelihood$conv");   const Rcpp::DoubleVector lambda0 = r["lambda0"];   const Rcpp::DoubleVector mu0 = r["mu0"];   const Rcpp::IntegerVector conv = r["conv"];   assert(lambda0.size() == 1);   assert(mu0.size() == 1);   assert(conv.size() == 1);   const bool has_converged = conv[0] == 0;   if (!has_converged)   {     std::stringstream s;     s << __func__ << ": has not converged" ;     throw std::runtime_error(s.str());   }   birth_rate = lambda0[0] / boost::units::si::second;   death_rate = mu0[0] / boost::units::si::second; } std::string ribi::ctm::Helper::CreateSimulatedPhylogeny(   const Parameters& parameters ) const {   ribi::fileio::FileIo f;   auto& r = ribi::Rinside().Get();   r.parseEvalQ("library(ape)");   r.parseEvalQ("library(geiger)");   const double birth_rate{parameters.GetBirthRate().value()};   const double death_rate{parameters.GetDeathRate().value()};   const int n_taxa{parameters.GetNumberOfTaxa()};   const int rng_seed{parameters.GetRngSeed()};   const double t_end{parameters.GetTime().value()};   assert(t_end == 0 && "Not yet implemented running to a certain time");   r["birth_rate"] = birth_rate;   r["death_rate"] = death_rate;   r["n_taxa"] = n_taxa;   r["rng_seed"] = rng_seed;   r["t_end"] = t_end;   // /home/richel/R/i686-pc-linux-gnu-library/3.1/Rcpp/include/Rcpp/vector/Vector.h   assert(Rcpp::DoubleVector(r["birth_rate"])[0] == birth_rate);   assert(Rcpp::DoubleVector(r["death_rate"])[0] == death_rate);   assert(Rcpp::IntegerVector(r["n_taxa"])[0] == n_taxa);   assert(Rcpp::IntegerVector(r["rng_seed"])[0] == rng_seed);   assert(Rcpp::DoubleVector(r["t_end"])[0] == t_end);   //Vital! If forgotten, the branch lengths will become N/A or 0   std::setlocale(LC_ALL,"en_US.UTF-8");   r.parseEvalQ("tree_full <- sim.bdtree(b=birth_rate,d=death_rate,stop=\"taxa\",n=n_taxa,extinct=FALSE,seed=rng_seed)");   const Rcpp::String s = r.parseEval("write.tree(tree_full)");   return std::string(s); } #ifndef NDEBUG void ribi::ctm::Helper::Test() noexcept {   {     static bool is_tested{false};     if (is_tested) return;     is_tested = true;   }   {     ribi::fileio::FileIo();     auto& r = ribi::Rinside().Get();     r.parseEval("library(ape)");     r.parseEval("library(DDD)");     r.parseEval("library(geiger)");     r.parseEval("library(laser)");   }   const TestTimer test_timer(__func__,__FILE__,1.0);   Helper h;   ribi::fileio::FileIo f;   //CreateSimulatedPhylogeny must create a newick   {     const Parameters parameters(       0.1 / boost::units::si::second,       0.0 / boost::units::si::second,       10,       42     );     assert(!h.CreateSimulatedPhylogeny(parameters).empty());   }   //CalcLogLikelihood   {     const std::string newick{"((F:2,G:2):1,H:3);"};     const Rate& birth_rate{0.20 / boost::units::si::second};     const Rate& death_rate{0.01 / boost::units::si::second};     const double log_likelihood{       h.CalcLogLikelihood(         newick,         birth_rate,         death_rate       )     };     assert(log_likelihood <= 0.0);   }   //CalcLogLikelihoodDdd and CalcLogLikelihoodLaser should give same results   {     const std::string newick{"((F:2,G:2):1,H:3);"};     const Rate& birth_rate{0.20 / boost::units::si::second};     const Rate& death_rate{0.01 / boost::units::si::second};     const double log_likelihood_ddd{       h.CalcLogLikelihoodDdd(         newick,         birth_rate,         death_rate,         Part::branch_lengths       )     };     const double log_likelihood_laser{       h.CalcLogLikelihoodLaser(         newick,         birth_rate,         death_rate       )     };     std::cout       << "log_likelihood_laser: " << log_likelihood_laser << '\n'       << "log_likelihood_ddd: " << log_likelihood_ddd << '\n'     ;     assert(abs(log_likelihood_laser - log_likelihood_ddd) < 0.0001);   }   //CalcMaxLikelihood   {     const std::string newick{"((F:2,G:2):1,H:3);"};     Rate birth_rate{0.0 / boost::units::si::second};     Rate death_rate{0.0 / boost::units::si::second};     h.CalcMaxLikelihood(       newick,       birth_rate,       death_rate,       Part::phylogeny     );     assert(birth_rate > 0.0 / boost::units::si::second);     assert(death_rate > 0.0 / boost::units::si::second);   } } #endif` - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelparameters.h --------------------------------------------------------- - -  - - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #ifndef COALESCENTTREEMODELPARAMETERS_H #define COALESCENTTREEMODELPARAMETERS_H #include "rate.h" #include "ribi_time.h" namespace ribi { namespace ctm { ///Performs a Birth-Death process struct Parameters {   using BirthRate = ribi::units::Rate;   using DeathRate = ribi::units::Rate;   using Time = ribi::units::Time;   Parameters(     const BirthRate birth_rate,     const DeathRate death_rate,     const Time time,     const int rng_seed = 42   );   Parameters(     const BirthRate birth_rate,     const DeathRate death_rate,     const int n_taxa,     const int rng_seed = 42   );   auto GetBirthRate() const noexcept { return m_birth_rate; }   auto GetDeathRate() const noexcept { return m_death_rate; }   auto GetNumberOfTaxa() const noexcept { return m_n_taxa; }   auto GetRngSeed() const noexcept { return m_rng_seed; }   auto GetTime() const noexcept { return m_time; }   private:   const BirthRate m_birth_rate;   const DeathRate m_death_rate;   const int m_rng_seed;   const Time m_time;   const int m_n_taxa; }; } //~namespace ctm } //~namespace ribi #endif // COALESCENTTREEMODELPARAMETERS_H` - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelparameters.cpp ----------------------------------------------------------- - -  - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #include "coalescenttreemodelparameters.h" #include #include ribi::ctm::Parameters::Parameters(     const BirthRate birth_rate,     const DeathRate death_rate,     const Time time,     const int rng_seed ) :     m_birth_rate{birth_rate},     m_death_rate{death_rate},     m_rng_seed{rng_seed},     m_time{time},     m_n_taxa{0} {   if (m_birth_rate < 0.0 / boost::units::si::second)   {     std::stringstream s;     s << __func__       << ": birth_rate must be positive, "       << "value given is " << m_birth_rate     ;     throw std::logic_error(s.str());   }   if (m_death_rate < 0.0 / boost::units::si::second)   {     std::stringstream s;     s << __func__       << ": death_rate must be positive, "       << "value given is " << m_death_rate     ;     throw std::logic_error(s.str());   }   if (m_time < 0.0 * boost::units::si::second)   {     std::stringstream s;     s << __func__       << ": time must be positive, "       << "value given is " << m_time     ;     throw std::logic_error(s.str());   } } ribi::ctm::Parameters::Parameters(     const BirthRate birth_rate,     const DeathRate death_rate,     const int n_taxa,     const int rng_seed ) :     m_birth_rate{birth_rate},     m_death_rate{death_rate},     m_rng_seed{rng_seed},     m_time{0.0 * boost::units::si::second},     m_n_taxa{n_taxa} {   if (m_birth_rate < 0.0 / boost::units::si::second)   {     std::stringstream s;     s << __func__       << ": birth_rate must be positive, "       << "value given is " << m_birth_rate     ;     throw std::logic_error(s.str());   }   if (m_death_rate < 0.0 / boost::units::si::second)   {     std::stringstream s;     s << __func__       << ": death_rate must be positive, "       << "value given is " << m_death_rate     ;     throw std::logic_error(s.str());   }   if (m_n_taxa < 2)   {     std::stringstream s;     s << __func__       << ": n_taxa must be 2 at least, "       << "value given is " << m_n_taxa     ;     throw std::logic_error(s.str());   } }` - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelsimulation.h --------------------------------------------------------- - -  - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #ifndef COALESCENTTREEMODELPROCESS_H #define COALESCENTTREEMODELPROCESS_H #include "coalescenttreemodelparameters.h" #include namespace ribi { namespace ctm { ///Performs a Brownian motion struct Simulation {   using BirthRate = ribi::units::Rate;   using DeathRate = ribi::units::Rate;   using Time = ribi::units::Time;   Simulation(     const Parameters& parameters   );   ///Calculate the next x. This class will supply the random numbers,   ///thus these member functions are not const   void CalcNext(     const double x   );   ///Calculate the next x+dt, supplying the random numbers yourself   void CalcNext(     const double x,     const double random_exponential   );   int CountExtant() const noexcept;   #ifndef NDEBUG   static void Test() noexcept;   #endif   private:   std::exponential_distribution m_exponential_distribution;   const Parameters m_parameters;   std::mt19937 m_rng;   Time m_time;   std::uniform_real_distribution m_uniform_distribution; }; } //~namespace ctm } //~namespace ribi #endif // COALESCENTTREEMODELPROCESS_H` - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -./CppCoalescentTreeModel/coalescenttreemodelsimulation.cpp ----------------------------------------------------------- - -  - - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #include "coalescenttreemodelsimulation.h" #include #include #include #include #include #include "coalescenttreemodelhelper.h" #include #include "testtimer.h" ribi::ctm::Simulation::Simulation(   const Parameters& parameters )   : m_exponential_distribution(parameters.GetBirthRate().value() + parameters.GetDeathRate().value()),     m_parameters{parameters},     m_rng(parameters.GetRngSeed()),     m_time{0.0 * boost::units::si::second},     m_uniform_distribution(0.0,1.0) {   #ifndef NDEBUG   Test();   #endif } void ribi::ctm::Simulation::CalcNext(const double x) {   const double r{     CountExtant()     * (m_parameters.GetBirthRate().value() + m_parameters.GetDeathRate().value())   };   if (r != m_exponential_distribution.lambda())   {     m_exponential_distribution = std::exponential_distribution(r);   }   const double random_exponential{m_exponential_distribution(m_rng)};   return CalcNext(x,random_exponential); } void ribi::ctm::Simulation::CalcNext(   const double /* x */,   const double random_exponential ) {   const auto dt = random_exponential * boost::units::si::second;   m_time += dt;   //Do something with a phylogeny here   //Stub } int ribi::ctm::Simulation::CountExtant() const noexcept {   return 0; //Stub } #ifndef NDEBUG void ribi::ctm::Simulation::Test() noexcept {   {     static bool is_tested{false};     if (is_tested) return;     is_tested = true;   }   {     Helper();   }   const TestTimer test_timer(__func__,__FILE__,1.0); } #endif` - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -  +# ([C++](Cpp.md)) [CoalescentTreeModel](CppCoalescentTreeModel.md) diff --git a/content/CppCodeSmell.md b/content/CppCodeSmell.md index 9d9ea297..be3d06b3 100644 --- a/content/CppCodeSmell.md +++ b/content/CppCodeSmell.md @@ -1,225 +1,154 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [code smell](CppCodeSmell.md) -=============================================== - -  +# ([C++](Cpp.md)) [code smell](CppCodeSmell.md) A [code smell](CppCodeSmell.md) is 'any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are usually not bugs—they are not technically incorrect and don't currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of -bugs or failures in the future' \[1\]. - -  +bugs or failures in the future' [1]. -  +## Examples -  - -  - -  - -Examples --------- - -  - -- Comments \[2\]: There's a fine line between comments that illuminate +- Comments [2]: There's a fine line between comments that illuminate and comments that obscure. Are the comments necessary? Do they explain "why" and not "what"? Can you refactor the code so the comments aren't required? And remember, you're writing comments for people, not machines -- Duplicated code \[1,2\]: identical or very similar code exists in +- Duplicated code [1,2]: identical or very similar code exists in more than one location. Duplicated code is the bane of software development. Stamp out duplication whenever possible. You should always be on the lookout for more subtle cases of near-duplication, too. Don't Repeat Yourself! -- Long method \[1,2\]: a method, function, or procedure that has grown +- Long method [1,2]: a method, function, or procedure that has grown too large. All other things being equal, a shorter method is easier to read, easier to understand, and easier to troubleshoot. Refactor long methods into smaller methods if you can -- Large class \[1,2\]: a class that has grown too large. See +- Large class [1,2]: a class that has grown too large. See God object. Large classes, like long methods, are difficult to read, understand, and troubleshoot. Does the class contain too many responsibilities? Can the large class be restructured or broken into smaller classes? -- Too many parameters \[1,2\]: a long list of parameters in a +- Too many parameters [1,2]: a long list of parameters in a procedure or function make readability and code quality worse. The more parameters a method has, the more complex it is. Limit the number of parameters you need in a given method, or use an object to combine the parameters -- Lazy class / Freeloader \[1,2\]: a class that does too little. +- Lazy class / Freeloader [1,2]: a class that does too little. Classes should pull their weight. Every additional class increases the complexity of a project. If you have a class that isn't doing enough to pay for itself, can it be collapsed or combined into another class? -- Inappropriate intimacy \[1,2\]: a class that has dependencies on +- Inappropriate intimacy [1,2]: a class that has dependencies on implementation details of another class. Watch out for classes that spend too much time together, or classes that interface in inappropriate ways. Classes should know as little as possible about each other -- Feature envy \[1,2\]: a class that uses methods of another +- Feature envy [1,2]: a class that uses methods of another class excessively. Methods that make extensive use of another class may belong in another class. Consider moving this method to the class it is so envious of. Closely related to Middle Man -- Middle Man \[2\]: If a class is delegating all its work, why does it +- Middle Man [2]: If a class is delegating all its work, why does it exist? Cut out the middleman. Beware classes that are merely wrappers over other classes or existing functionality in the framework. Closely related to Feature Envy -- Refused bequest \[1,2\]: a class that overrides a method of a base +- Refused bequest [1,2]: a class that overrides a method of a base class in such a way that the contract of the base class is not honored by the derived class. See Liskov substitution principle. If you inherit from a class, but never use any of the inherited functionality, should you really be using inheritance? -- Contrived complexity \[1\]: forced usage of overly complicated +- Contrived complexity [1]: forced usage of overly complicated design patterns where simpler design would suffice -- Excessively long identifiers \[1\]: in particular, the use of naming +- Excessively long identifiers [1]: in particular, the use of naming conventions to provide disambiguation that should be implicit in the software architecture -- Excessively short identifiers \[1\]: the name of a variable should +- Excessively short identifiers [1]: the name of a variable should reflect its function unless the function is obvious -- Excessive use of literals \[1\]: these should be coded as named +- Excessive use of literals [1]: these should be coded as named constants, to improve readability and to avoid programming errors. Additionally, literals can and should be externalized into resource files/scripts where possible, to facilitate localization of software if it is intended to be deployed in different regions -- Ubercallback \[1\]: a callback that is trying to do everything -- Complex conditionals \[1\]: branches that check lots of unrelated +- Ubercallback [1]: a callback that is trying to do everything +- Complex conditionals [1]: branches that check lots of unrelated conditions and edge cases that don't seem to capture the meaning of a block of code -- Conditional Complexity \[2\]: Watch out for large conditional logic +- Conditional Complexity [2]: Watch out for large conditional logic blocks, particularly blocks that tend to grow larger or change significantly over time. Consider alternative object-oriented approaches such as decorator, strategy, or state -- Combinitorial Explosion \[2\]: You have lots of code that does +- Combinitorial Explosion [2]: You have lots of code that does almost the same thing.. but with tiny variations in data or behavior. This can be difficult to refactor-- perhaps using generics or an interpreter? -- Type Embedded in Name \[2\]: Avoid placing types in method names; +- Type Embedded in Name [2]: Avoid placing types in method names; it's not only redundant, but it forces you to change the name if the type changes -- Uncommunicative Name \[2\]: Does the name of the method succinctly +- Uncommunicative Name [2]: Does the name of the method succinctly describe what that method does? Could you read the method's name to another developer and have them explain to you what it does? If not, rename it or rewrite it -- Inconsistent Names \[2\]: Pick a set of standard terminology and +- Inconsistent Names [2]: Pick a set of standard terminology and stick to it throughout your methods. For example, if you have Open(), you should probably have Close() -- Dead Code \[2\]: Ruthlessly delete code that isn't being used. +- Dead Code [2]: Ruthlessly delete code that isn't being used. That's why we have source control systems! -- Speculative Generality \[2\]: Write code to solve today's problems, +- Speculative Generality [2]: Write code to solve today's problems, and worry about tomorrow's problems when they actually materialize. Everyone loses in the "what if.." school of design. You (Probably) Aren't Gonna Need It -- Oddball Solution \[2\]: There should only be one way of solving the +- Oddball Solution [2]: There should only be one way of solving the same problem in your code. If you find an oddball solution, it could be a case of poorly duplicated code-- or it could be an argument for the adapter model, if you really need multiple solutions to the same problem -- Temporary Field \[2\]: Watch out for objects that contain a lot of +- Temporary Field [2]: Watch out for objects that contain a lot of optional or unnecessary fields. If you're passing an object as a parameter to a method, make sure that you're using all of it and not cherry-picking single fields -- Alternative Classes with Different Interfaces \[2\]: If two classes +- Alternative Classes with Different Interfaces [2]: If two classes are similar on the inside, but different on the outside, perhaps they can be modified to share a common interface -- Primitive Obsession \[2\]: Don't use a gaggle of primitive data type +- Primitive Obsession [2]: Don't use a gaggle of primitive data type variables as a poor man's substitute for a class. If your data type is sufficiently complex, write a class to represent it -- Data Class \[2\]: Avoid classes that passively store data. Classes +- Data Class [2]: Avoid classes that passively store data. Classes should contain data and methods to operate on that data, too -- Data Clumps \[2\]: If you always see the same data hanging around +- Data Clumps [2]: If you always see the same data hanging around together, maybe it belongs together. Consider rolling the related data up into a larger class -- Indecent Exposure \[2\]: Beware of classes that unnecessarily expose +- Indecent Exposure [2]: Beware of classes that unnecessarily expose their internals. Aggressively refactor classes to minimize their public surface. You should have a compelling reason for every item you make public. If you don't, hide it -- Message Chains \[2\]: Watch out for long sequences of method calls +- Message Chains [2]: Watch out for long sequences of method calls or temporary variables to get routine data. Intermediaries are dependencies in disguise -- Divergent Change \[2\]: If, over time, you make changes to a class +- Divergent Change [2]: If, over time, you make changes to a class that touch completely different parts of the class, it may contain too much unrelated functionality. Consider isolating the parts that changed in another class -- Shotgun Surgery \[2\]: If a change in one class requires cascading +- Shotgun Surgery [2]: If a change in one class requires cascading changes in several related classes, consider refactoring so that the changes are limited to a single class -- Parallel Inheritance Hierarchies \[2\]: Every time you make a +- Parallel Inheritance Hierarchies [2]: Every time you make a subclass of one class, you must also make a subclass of another. Consider folding the hierarchy into a single class -- Incomplete Library Class \[2\]: We need a method that's missing from +- Incomplete Library Class [2]: We need a method that's missing from the library, but we're unwilling or unable to change the library to include the method. The method ends up tacked on to some other class. If you can't modify the library, consider isolating the method -- Solution Sprawl \[2\]: If it takes five classes to do anything +- Solution Sprawl [2]: If it takes five classes to do anything useful, you might have solution sprawl. Consider simplifying and consolidating your design -  - -  - -  - -  - -  - -External links --------------- - -  - -- [Wikipedia page about code - smell](https://en.wikipedia.org/wiki/Code_smell.md) -- [Codinghorror page about code - smell](http://www.codinghorror.com/blog/2006/05/code-smells.html) -- [A code smell - taxonomy](www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.md) - -  - -  - -  - -  - -  - -[References](CppReferences.md) -------------------------------- - -  - -1. [Wikipedia page about code - smell](https://en.wikipedia.org/wiki/Code_smell.md) -2. [Codinghorror page about code - smell](http://www.codinghorror.com/blog/2006/05/code-smells.html) - -  - -  - -  - -  +## External links -  + * [Wikipedia page about code smell](https://en.wikipedia.org/wiki/Code_smell.md) + * [Codinghorror page about code smell](http://www.codinghorror.com/blog/2006/05/code-smells.html) + * [A code smell taxonomy](www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.md) -  +## [References](CppReferences.md) + * [1] [Wikipedia page about code smell](https://en.wikipedia.org/wiki/Code_smell.md) + * [2] [Codinghorror page about code smell](http://www.codinghorror.com/blog/2006/05/code-smells.html) diff --git a/content/CppCodeSnippets.md b/content/CppCodeSnippets.md index 876f845b..b2ab68c2 100644 --- a/content/CppCodeSnippets.md +++ b/content/CppCodeSnippets.md @@ -1,33 +1,15 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [Code snippets](CppCodeSnippets.md) -===================================================== - -  +# ([C++](Cpp.md)) [Code snippets](CppCodeSnippets.md) My own favorite [C++](Cpp.md) [code snippets](CppCodeSnippets.md), for everyone to use freely. Note that some snippets fall under multiple categories. Some snippets are trivial for most people, but I put them here for completeness and for newbies (including my own students). -  - I cite my sources whenever someone else published a version of the snippet before me, although I have always modified the original. All snippets should compile cleanly after a copy-paste. Feel free to contact me when one snippet does not ([view my E-mail address](Email.png)) -  - 1. [Artificial Intelligence](CppArtificialIntelligence.md) 2. [ASCII art](CppAsciiArt.md) 3. [Audio](CppAudio.md) @@ -72,16 +54,3 @@ me when one snippet does not ([view my E-mail address](Email.png)) 42. [vector, std::vector](CppVector.md) 43. [Windows](CppWindows.md) 44. [XML](CppXml.md) - -  - -  - -  - -  - -  - -  - diff --git a/content/CppCodeTemplate.md b/content/CppCodeTemplate.md index 048a8437..77abaa35 100644 --- a/content/CppCodeTemplate.md +++ b/content/CppCodeTemplate.md @@ -1,65 +1,17 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [code template](CppCodeTemplate.md) -===================================================== - -  +# ([C++](Cpp.md)) [code template](CppCodeTemplate.md) [Code templates](CppCodeTemplate.md) are predefined pieces of code that can be inserted by a keyboard shortcut. Not all [IDE](CppIde.md)s support [code templates](CppCodeTemplate.md). -  - -  - -  - -  - -  - -Example -------- +## Example -  +In the C++ Builder 6.0 IDE, one can define a [code template](CppCodeTemplate.md) as follows: -In the C++ Builder 6.0 IDE, one can define a [code -template](CppCodeTemplate.md) as follows: - -  - - ---------------------------------- - ` for (int i=0; i!=|; ++i) { }` - ---------------------------------- - -  +``` +for (int i=0; i!=|; ++i) { } +``` The bar ('|') denotes the cursor position after insertion. -  - -This code can be inserted by using CTRL-J and the [code -template](CppCodeTemplate.md)'s shortcut, for example 'i'. - -  - -  - -  - -  - -  - -  - +This code can be inserted by using CTRL-J and the [code template](CppCodeTemplate.md)'s shortcut, for example 'i'. diff --git a/content/CppCodecvtH.md b/content/CppCodecvtH.md index 15cc00cc..6b94e589 100644 --- a/content/CppCodecvtH.md +++ b/content/CppCodecvtH.md @@ -1,34 +1,3 @@ +# ([C++](Cpp.md)) ![C++11](PicCpp11.png) [codecvt.h](CppCodecvtH.md) -  - -  - -  - -  - -  - -([C++](Cpp.md)) ![C++11](PicCpp11.png) [codecvt.h](CppCodecvtH.md) -==================================================================== - -  - -[codecvt.h](CppCodecvtH.md) is a standard [header -file](CppHeaderFile.md) (since the [C++11](Cpp11.md) -[standard](CppStandard.md)). - -  - -  - -  - -  - -  - -  - -  - +[codecvt.h](CppCodecvtH.md) is a standard [header file](CppHeaderFile.md) (since the [C++11](Cpp11.md) [standard](CppStandard.md)). diff --git a/content/CppCodingStandard.md b/content/CppCodingStandard.md index ab552a88..26ab5164 100644 --- a/content/CppCodingStandard.md +++ b/content/CppCodingStandard.md @@ -1,51 +1,19 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [Coding standard](CppCodingStandard.md) -========================================================= - -  +# ([C++](Cpp.md)) [Coding standard](CppCodingStandard.md) A [coding standard](CppCodingStandard.md) is 'a set of rules or guidelines used when writing the source code for a computer program. It is often claimed that following a particular programming style will help programmers to read and understand source code conforming to the style, -and help to avoid introducing errors' \[1\]. +and help to avoid introducing errors' [1]. -  - -The table of contents of \[2\] is already the summary of an excellent +The table of contents of [2] is already the summary of an excellent [coding standard](CppCodingStandard.md), and it can be found at [the book's homepage](http://www.gotw.ca/publications/c++cs.md). -  - -  - -  - -  - -  - -[References](CppReferences.md) -------------------------------- - -  +## [References](CppReferences.md) -1. [Wikipedia page about coding - standard](http://en.wikipedia.org/wiki/Coding_standard) -2. [Herb Sutter](CppHerbSutter.md), [Andrei - Alexandrescu](CppAndreiAlexandrescu.md). C++ coding standards: 101 - rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. +1. [Wikipedia page about coding standard](http://en.wikipedia.org/wiki/Coding_standard) +2. [Herb Sutter](CppHerbSutter.md), [Andrei Alexandrescu](CppAndreiAlexandrescu.md). C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6.   diff --git a/content/CppColorToRgb.md b/content/CppColorToRgb.md index 55350d6e..263eda7a 100644 --- a/content/CppColorToRgb.md +++ b/content/CppColorToRgb.md @@ -1,38 +1,18 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [ColorToRgb](CppColorToRgb.md) -================================================ - -  +# ([C++](Cpp.md)) [ColorToRgb](CppColorToRgb.md) [ColorToRgb](CppColorToRgb.md) converts a TColor value to its RGB values. To convert RGB values to a TColor, use [the RgbToColor function](CppRgbToColor.md). -  - - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - ` //From http://www.richelbilderbeek.nl void ColorToRgb(   const TColor color,   unsigned char& red,   unsigned char& green,   unsigned char& blue  ) {   red   = GetRValue(color);   green = GetGValue(color);   blue  = GetBValue(color); }` - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - -  - -  - -  - -  - -  - -  - +```c++ +void ColorToRgb( + const TColor color, + unsigned char& red, + unsigned char& green, + unsigned char& blue ) +{ + red = GetRValue(color); + green = GetGValue(color); + blue = GetBValue(color); +} +``` diff --git a/content/CppColorToRgb.txt b/content/CppColorToRgb.txt deleted file mode 100755 index d5b42d59..00000000 --- a/content/CppColorToRgb.txt +++ /dev/null @@ -1,11 +0,0 @@ -//From http://www.richelbilderbeek.nl -void ColorToRgb( - const TColor color, - unsigned char& red, - unsigned char& green, - unsigned char& blue ) -{ - red = GetRValue(color); - green = GetGValue(color); - blue = GetBValue(color); -} diff --git a/content/CppStdAccumulate.md b/content/CppStdAccumulate.md index 798d921e..c3b85852 100644 --- a/content/CppStdAccumulate.md +++ b/content/CppStdAccumulate.md @@ -1,59 +1,24 @@ +# ([C++](Cpp.md)) [std::accumulate](CppAccumulate.md) -  +[std::accumulate](CppAccumulate.md) is an [STL](CppStl.md) [algorithm](CppAlgorithm.md) +to accumulate a range. [std::accumulate](CppAccumulate.md) is defined in [numeric.h](CppNumericH.md). -  -  + * [std::accumulate example 1: summing a std::vector of integers](CppStdAccumulateExample1.md) + * [std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression](CppStdAccumulateExample2.md) + * [accumulate_if](CppAccumulate_if.md): `accumulate` with a [predicate](CppPredicate.md). -  +## A [definition](CppDefinition.md) of [std::accumulate](CppAccumulate.md) -  +```c++ +template +T accumulate (InputIterator first, InputIterator last, T init) +{ + while (first != last) init = init + *first++; + return init; +} +``` -([C++](Cpp.md)) [std::accumulate](CppAccumulate.md) -===================================================== - -  - -[Algorithm](CppAlgorithm.md) to accumulate a range. -[std::accumulate](CppAccumulate.md) is defined in -[numeric.h](CppNumericH.md). Use [accumulate\_if](CppAccumulate_if.md) -if you need to supply a [predicate](CppPredicate.md). - -  - -- [std::accumulate example 1: summing a std::vector of - integers](CppAccumulateExample1.md) -- [std::accumulate example 2: summing a std::vector of a custom class - using a C++11 lambda expression](CppAccumulateExample2.md) - -  - -  - -  - -  - -  - -A [definition](CppDefinition.md) of [std::accumulate](CppAccumulate.md) -------------------------------------------------------------------------- - -  - - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - ` template T accumulate (InputIterator first, InputIterator last, T init) {   while (first != last) init = init + *first++;   return init; }` - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - -  - -  - -  - -  - -  - -  +## External links + * [cppreference's `std::accumulate` page](http://en.cppreference.com/w/cpp/algorithm/accumulate) \ No newline at end of file diff --git a/content/CppStdAccumulateExample1.md b/content/CppStdAccumulateExample1.md index 1b507fab..deb71c68 100644 --- a/content/CppStdAccumulateExample1.md +++ b/content/CppStdAccumulateExample1.md @@ -1,116 +1,23 @@ +# ([C++](Cpp.md)) [std::accumulate example 1: summing a std::vector of integers](CppAccumulateExample1.md) -  +[std::accumulate example 1: summing a std::vector of integers](CppAccumulateExample1.md) is a +[std::accumulate](CppStdAccumulate.md) example to sum a [std::vector](CppVector.md) of [integers](CppInt.md). -  +```c++ +#include +#include +#include -  +int main() +{ + //Create a std::vector + std::vector v; + for (int i=0; i!=10; ++i) { v.push_back(i); } -  - -  - -([C++](Cpp.md)) [std::accumulate example 1: summing a std::vector of integers](CppAccumulateExample1.md) -========================================================================================================== - -  - -[std::accumulate example 1: summing a std::vector of -integers](CppAccumulateExample1.md) is a -[std::accumulate](CppAccumulate.md) example to sum a -[std::vector](CppVector.md) of [integers](CppInt.md). - -  - -- Download the Qt Creator project 'CppAccumulateExample1' (zip) - -  - -  - -  - -  - -  - -Technical facts ---------------- - -  - -[Operating system(s) or programming environment(s)](CppOs.md) - -- ![Lubuntu](PicLubuntu.png) [Lubuntu](CppLubuntu.md) 13.04 (raring) - -[IDE(s)](CppIde.md): - -- ![Qt Creator](PicQtCreator.png) [Qt Creator](CppQtCreator.md) 2.7.0 - -[Project type](CppQtProjectType.md): - -- ![console](PicConsole.png) [Console - application](CppConsoleApplication.md) - -[C++ standard](CppStandard.md): - -- ![C++98](PicCpp98.png) [C++98](Cpp98.md) - -[Compiler(s)](CppCompiler.md): - -- [G++](CppGpp.md) 4.7.3 - -[Libraries](CppLibrary.md) used: - -- ![STL](PicStl.png) [STL](CppStl.md): GNU ISO C++ Library, version - 4.7.3 - -  - -  - -  - -  - -  - -[Qt project file](CppQtProjectFile.md): CppAccumulateExample1.pro ------------------------------------------------------------------- - -  - - ------------------------------------------------------------------------------------------- - ` TEMPLATE = app CONFIG += console CONFIG -= app_bundle CONFIG -= qt SOURCES += main.cpp` - ------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -main.cpp --------- - -  - - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - ` #include #include #include int main() {   //Create a std::vector   std::vector v;   for (int i=0; i!=10; ++i) { v.push_back(i); }   //Sum the std::vector   const int sum = std::accumulate(v.begin(), v.end(), 0 ); // '0' is the initial value   //Assume std::accumulate works correctly   assert(sum == 45); }` - ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - -  - -  - -  - -  - -  - -  + //Sum the std::vector + const int sum{std::accumulate(std::begin(v), std::end(v), 0)}; // '0' is the initial value + //Assume std::accumulate works correctly + assert(sum == 45); +} +``` diff --git a/content/CppStdAccumulateExample2.md b/content/CppStdAccumulateExample2.md index 9f541d84..dd7e4139 100644 --- a/content/CppStdAccumulateExample2.md +++ b/content/CppStdAccumulateExample2.md @@ -1,18 +1,4 @@ - -  - -  - -  - -  - -  - -([C++](Cpp.md)) [std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression](CppAccumulateExample2.md) -================================================================================================================================================ - -  +# ([C++](Cpp.md)) [std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression](CppAccumulateExample2.md) [std::accumulate example 2: summing a std::vector of a custom class using a C++11 lambda expression](CppAccumulateExample2.md) is a @@ -20,98 +6,40 @@ using a C++11 lambda expression](CppAccumulateExample2.md) is a [std::vector](CppVector.md) of a custom [class](CppClass.md) using a [C++11](Cpp11.md) [lambda expression](CppLambdaExpression.md). -  - -- Download the Qt Creator project 'CppAccumulateExample2' (zip) - -  - -  - -  - -  - -  - -Technical facts ---------------- - -  - -[Operating system(s) or programming environment(s)](CppOs.md) - -- ![Lubuntu](PicLubuntu.png) [Lubuntu](CppLubuntu.md) 13.04 (raring) - -[IDE(s)](CppIde.md): - -- ![Qt Creator](PicQtCreator.png) [Qt Creator](CppQtCreator.md) 2.7.0 - -[Project type](CppQtProjectType.md): - -- ![console](PicConsole.png) [Console - application](CppConsoleApplication.md) - -[C++ standard](CppStandard.md): - -- ![C++11](PicCpp11.png) [C++11](Cpp11.md) - -[Compiler(s)](CppCompiler.md): - -- [G++](CppGpp.md) 4.7.3 - -[Libraries](CppLibrary.md) used: - -- ![STL](PicStl.png) [STL](CppStl.md): GNU ISO C++ Library, version - 4.7.3 - -  - -  - -  - -  - -  - -[Qt project file](CppQtProjectFile.md): CppAccumulateExample2.pro ------------------------------------------------------------------- - -  - - ------------------------------------------------------------------------------------------------------------------------ - ` QMAKE_CXXFLAGS += -std=c++11 TEMPLATE = app CONFIG += console CONFIG -= app_bundle CONFIG -= qt SOURCES += main.cpp` - ------------------------------------------------------------------------------------------------------------------------ - -  - -  - -  - -  - -  - -main.cpp --------- - -  - - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - ` #include #include #include struct MyClass {   MyClass(const int x = 0) : m_x(x) {}   int Get() const { return m_x; }   private:   int m_x; }; int main() {   //Create a std::vector   std::vector v;   for (int i=0; i!=10; ++i) { v.push_back(MyClass(i)); }   //Sum the std::vector using a C++11 lambda expression   const int sum     = std::accumulate(       v.begin(),       v.end(),       0, // '0' is the initial value       [](const int sum, const MyClass& my_class)       {         return sum + my_class.Get();       }     );   //Assume std::accumulate works correctly   assert(sum == 45); }` - --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- - -  - -  - -  - -  - -  - -  - +```c++ +#include +#include +#include + +class my_class +{ +public: + my_class(const int x = 0) : m_x{x} {} + int get_x() const noexcept { return m_x; } +private: + int m_x; +}; + +int main() +{ + //Create a std::vector + std::vector v; + for (int i=0; i!=10; ++i) { v.push_back(my_class(i)); } + + //Sum the std::vector using lambda expression + const int sum{ + std::accumulate( + std::begin(v), + std::end(v), + 0, // '0' is the initial value + [](const int sum, const my_class& m) + { + return sum + m.get_x(); + } + ) + }; + + //Assume std::accumulate works correctly + assert(sum == 45); +} +```