#include <iterator>
#include <algorithm> // for std::partition
#include <functional> // for std::less

// helper function for median of three
template<typename T>
 T median(T t1, T t2, T t3)
{
  if (t1 < t2)
  {
    if (t2 < t3)
      return t2;
    else if (t1 < t3)
      return t3;
    else
      return t1;
  }
  else
  {
    if (t1 < t3)
      return t1;
    else if (t2 < t3)
      return t3;
    else
      return t2;
  }
}

// helper object to get <= from <
template<typename Order> struct non_strict_op:
  public std::binary_function<typename Order::second_argument_type,
                              typename Order::first_argument_type,
                              bool>
{
  non_strict_op(Order o): order(o) {}
  bool operator()(typename Order::second_argument_type arg1,
                  typename Order::first_argument_type arg2) const
  {
    return !order(arg2, arg1);
  }
private:
  Order order;
};

template<typename Order> non_strict_op<Order> non_strict(Order o)
{
  return non_strict_op<Order>(o);
}

template<typename RandomAccessIterator,
         typename Order>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)
{
  if (first != last && first+1 != last)
  {
    typedef typename std::iterator_traits<RandomAccessIterator>::value_type value_type;
    RandomAccessIterator mid = first + (last - first)/2;
    value_type pivot = median(*first, *mid, *(last-1));
    RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot));
    RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot));
    quicksort(first, split1, order);
    quicksort(split2, last, order);
  }
}

template<typename RandomAccessIterator>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last)
{
  quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}

#include <iterator>
#include <algorithm> // for std::partition
#include <functional> // for std::less

template<typename RandomAccessIterator,
         typename Order>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)
{
  if (last - first > 1)
  {
    RandomAccessIterator split = std::partition(first+1, last, std::bind2nd(order, *first));
    std::iter_swap(first, split-1);
    quicksort(first, split-1, order);
    quicksort(split, last, order);
  }
}

template<typename RandomAccessIterator>
 void quicksort(RandomAccessIterator first, RandomAccessIterator last)
{
  quicksort(first, last, std::less<typename std::iterator_traits<RandomAccessIterator>::value_type>());
}

implement the quicksort algorithm. The algorithm sorts an array or list by choosing a pivot element and dividing the rest of the elements into two partitions: one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include two versions of quicksort: one that uses a median-of-three pivot and works in place to avoid memory allocation, and a simpler version that uses the first element as the pivot.


// Display the current date in the formats of "2007-11-10"
// and "Sunday, November 10, 2007".

#include <vector>
#include <string>
#include <iostream>
#include <ctime>

/** Return the current date in a string, formatted as either ISO-8601
 *  or "Weekday-name, Month-name Day, Year".
 *
 *  The date is initialized when the object is created and will return
 *  the same date for the lifetime of the object.  The date returned
 *  is the date in the local timezone.
 */
class Date
{
    struct tm ltime;

public:
    /// Default constructor.
    Date()
    {
        time_t t = time(0);
        localtime_r(&t, &ltime);
    }

    /** Return the date based on a format string.  The format string is
     *  fed directly into strftime().  See the strftime() documentation
     *  for information on the proper construction of format strings.
     *
     *  @param[in] fmt is a valid strftime() format string.
     *
     *  @return a string containing the formatted date, or a blank string
     *      if the format string was invalid or resulted in a string that
     *      exceeded the internal buffer length.
     */
    std::string getDate(const char* fmt)
    {
        char out[200];
        size_t result = strftime(out, sizeof out, fmt, &ltime);
        return std::string(out, out + result);
    }

    /** Return the date in ISO-8601 date format.
     *
     *  @return a string containing the date in ISO-8601 date format.
     */
    std::string getISODate() {return getDate("%F");}

    /** Return the date formatted as "Weekday-name, Month-name Day, Year".
     *
     *  @return a string containing the date in the specified format.
     */
    std::string getTextDate() {return getDate("%A, %B %d, %Y");}
};

int main()
{
    Date d;
    std::cout << d.getISODate() << std::endl;
    std::cout << d.getTextDate() << std::endl;
    return 0;
}

display the current date in two formats: "2007-11-23" and "Friday, November 23, 2007".


Non-recursive version[edit]
#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
typedef std::set<int> set_type;
typedef std::set<set_type> powerset_type;

powerset_type powerset(set_type const& set)
{
  typedef set_type::const_iterator set_iter;
  typedef std::vector<set_iter> vec;
  typedef vec::iterator vec_iter;

  struct local
  {
    static int dereference(set_iter v) { return *v; }
  };

  powerset_type result;

  vec elements;
  do
  {
    set_type tmp;
    std::transform(elements.begin(), elements.end(),
                   std::inserter(tmp, tmp.end()),
                   local::dereference);
    result.insert(tmp);
    if (!elements.empty() && ++elements.back() == set.end())
    {
      elements.pop_back();
    }
    else
    {
      set_iter iter;
      if (elements.empty())
      {
        iter = set.begin();
      }
      else
      {
        iter = elements.back();
        ++iter;
      }
      for (; iter != set.end(); ++iter)
      {
        elements.push_back(iter);
      }
    }
  } while (!elements.empty());

  return result;
}

int main()
{
  int values[4] = { 2, 3, 5, 7 };
  set_type test_set(values, values+4);

  powerset_type test_powerset = powerset(test_set);

  for (powerset_type::iterator iter = test_powerset.begin();
       iter != test_powerset.end();
       ++iter)
  {
    std::cout << "{ ";
    char const* prefix = "";
    for (set_type::iterator iter2 = iter->begin();
         iter2 != iter->end();
         ++iter2)
    {
      std::cout << prefix << *iter2;
      prefix = ", ";
    }
    std::cout << " }\n";
  }
}

The code takes a set S as input and generates its power set. The power set includes all subsets of S, including the empty set and the set itself. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set.


C++ 98[edit]
#include <iostream>
#include <string>

std::string to_roman(int value)
{
  struct romandata_t { int value; char const* numeral; };
  static romandata_t const romandata[] =
     { 1000, "M",
        900, "CM",
        500, "D",
        400, "CD",
        100, "C",
         90, "XC",
         50, "L",
         40, "XL",
         10, "X",
          9, "IX",
          5, "V",
          4, "IV",
          1, "I",
          0, NULL }; // end marker

  std::string result;
  for (romandata_t const* current = romandata; current->value > 0; ++current)
  {
    while (value >= current->value)
    {
      result += current->numeral;
      value  -= current->value;
    }
  }
  return result;
}

int main()
{
  for (int i = 1; i <= 4000; ++i)
  {
    std::cout << to_roman(i) << std::endl;
  }
}

C++ 11[edit]
#include <iostream>
#include <string>

std::string to_roman(int x) {
     if (x <= 0)
         return "Negative or zero!";
     auto roman_digit = [](char one, char five, char ten, int x) {
        if (x <= 3)
            return std::string().assign(x, one);
        if (x <= 5)
            return std::string().assign(5 - x, one) + five;
        if (x <= 8)
            return five + std::string().assign(x - 5, one);
        return std::string().assign(10 - x, one) + ten;
    };
    if (x >= 1000)
        return x - 1000 > 0 ? "M" + to_roman(x - 1000) : "M";
    if (x >= 100) {
        auto s = roman_digit('C', 'D', 'M', x / 100);
        return x % 100 > 0 ? s + to_roman(x % 100) : s;
    }
    if (x >= 10) {
        auto s = roman_digit('X', 'L', 'C', x / 10);
        return x % 10 > 0 ? s + to_roman(x % 10) : s;
    }
    return roman_digit('I', 'V', 'X', x);
}

int main() {
    for (int i = 0; i < 2018; i++)
        std::cout << i << " --> " << to_roman(i) << std::endl;
}

create a function that converts a positive integer into its equivalent Roman numeral representation.


Works with: C++11

#include <array>
#include <vector>

// These headers are only needed for the demonstration
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

// This is a template function that works for any array-like object
template <typename Array>
void demonstrate(Array& array)
{
  // Array element access
  array[2] = "Three";  // Fast, but unsafe - if the index is out of bounds you
                       // get undefined behaviour
  array.at(1) = "Two"; // *Slightly* less fast, but safe - if the index is out
                       // of bounds, an exception is thrown

  // Arrays can be used with standard algorithms
  std::reverse(begin(array), end(array));
  std::for_each(begin(array), end(array),
    [](typename Array::value_type const& element) // in C++14, you can just use auto
    {
      std::cout << element << ' ';
    });

  std::cout << '\n';
}

int main()
{
  // Compile-time sized fixed-size array
  auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
  // If you do not supply enough elements, the remainder are default-initialized

  // Dynamic array
  auto dynamic_array = std::vector<std::string>{ "One", "Four" };
  dynamic_array.push_back("Eight"); // Dynamically grows to accept new element

  // All types of arrays can be used more or less interchangeably
  demonstrate(fixed_size_array);
  demonstrate(dynamic_array);
}

demonstrate the basic syntax of arrays in C++. It includes creating both fixed-length and dynamic arrays, assigning values to them, and retrieving an element. The code also showcases the use of std::array and std::vector, discussing their size allocation, memory placement, and additional functionalities. The code also refers to obsolete tasks related to array creation, value assignment, and element retrieval.


Works with: g++ version 3.4.2
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string line;
    ifstream input ( "input.txt" );
    ofstream output ("output.txt");

    if (output.is_open()) {
        if (input.is_open()){
            while (getline (input,line)) {
                output << line << endl;
            }
            input.close(); // Not necessary - will be closed when variable goes out of scope.
        }
        else {
            cout << "input.txt cannot be opened!\n";
        }
        output.close(); // Not necessary - will be closed when variable goes out of scope.
    }
    else {
        cout << "output.txt cannot be written to!\n";
    }
    return 0;
}

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
  std::ifstream input("input.txt");
  if (!input.is_open())
  {
    std::cerr << "could not open input.txt for reading.\n";
    return EXIT_FAILURE;
  }

  std::ofstream output("output.txt");
  if (!output.is_open())
  {
    std::cerr << "could not open output.txt for writing.\n";
    return EXIT_FAILURE;
  }

  output << input.rdbuf();
  if (!output)
  {
    std::cerr << "error copying the data.\n";
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

# include <algorithm>
# include <fstream>

int main() {
  std::ifstream ifile("input.txt");
  std::ofstream ofile("output.txt");
  std::copy(std::istreambuf_iterator<char>(ifile),
            std::istreambuf_iterator<char>(),
            std::ostreambuf_iterator<char>(ofile));
}

#include <fstream>

int main()
{
  std::ifstream input("input.txt");
  std::ofstream output("output.txt");
  output << input.rdbuf();
}

demonstrate how to read the contents of "input.txt" file into a variable and then write this variable's contents into a new file called "output.txt". The codes also show the usage of istream and ostream iterators. The use of oneliners that skip the intermediate variable is also explored, although it's of secondary interest.


Works with: g++ version  3.4.4 (cygming special)
Library: STL

#include <algorithm>
#include <string>
#include <cctype>

/// \brief in-place convert string to upper case
/// \return ref to transformed string
void str_toupper(std::string &str) {
  std::transform(str.begin(),
                 str.end(),
                 str.begin(),
                 (int(*)(int)) std::toupper);
}

/// \brief in-place convert string to lower case
/// \return ref to transformed string
void str_tolower(std::string &str) {
  std::transform(str.begin(),
                 str.end(),
                 str.begin(),
                 (int(*)(int)) std::tolower);
}

#include <iostream>
#include <string>

using namespace std;
int main() {
  string foo("_upperCas3Me!!");
  str_toupper(foo);
  cout << foo << endl;
  str_tolower(foo);
  cout << foo << endl;
  return 0;
}

demonstrate how to convert the string "alphaBETA" to upper-case and lower-case using the default encoding of a string literal or plain ASCII. The codes also showcase additional case conversion functions such as swapping case, capitalizing the first letter, etc. The transformation is done in-place, but alternate methods may return a new copy or use a stream manipulator.


/*
	Author: Kevin Bacon
	Date: 04/03/2014
	Task: Closest-pair problem
*/

#include <iostream>
#include <vector>
#include <utility>
#include <cmath>
#include <random>
#include <chrono>
#include <algorithm>
#include <iterator>

typedef std::pair<double, double> point_t;
typedef std::pair<point_t, point_t> points_t;

double distance_between(const point_t& a, const point_t& b) {
	return std::sqrt(std::pow(b.first - a.first, 2)
		+ std::pow(b.second - a.second, 2));
}

std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) {
	if (points.size() < 2) {
		return { -1, { { 0, 0 }, { 0, 0 } } };
	}
	auto minDistance = std::abs(distance_between(points.at(0), points.at(1)));
	points_t minPoints = { points.at(0), points.at(1) };
	for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {
		for (auto j = i + 1; j < std::end(points); ++j) {
			auto newDistance = std::abs(distance_between(*i, *j));
			if (newDistance < minDistance) {
				minDistance = newDistance;
				minPoints.first = *i;
				minPoints.second = *j;
			}
		}
	}
	return { minDistance, minPoints };
}

std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP,
	const std::vector<point_t>& yP) {
	if (xP.size() <= 3) {
		return find_closest_brute(xP);
	}
	auto N = xP.size();
	auto xL = std::vector<point_t>();
	auto xR = std::vector<point_t>();
	std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL));
	std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR));
	auto xM = xP.at((N-1) / 2).first;
	auto yL = std::vector<point_t>();
	auto yR = std::vector<point_t>();
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {
		return p.first <= xM;
	});
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {
		return p.first > xM;
	});
	auto p1 = find_closest_optimized(xL, yL);
	auto p2 = find_closest_optimized(xR, yR);
	auto minPair = (p1.first <= p2.first) ? p1 : p2;
	auto yS = std::vector<point_t>();
	std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {
		return std::abs(xM - p.first) < minPair.first;
	});
	auto result = minPair;
	for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {
		for (auto k = i + 1; k != std::end(yS) &&
		 ((k->second - i->second) < minPair.first); ++k) {
			auto newDistance = std::abs(distance_between(*k, *i));
			if (newDistance < result.first) {
				result = { newDistance, { *k, *i } };
			}
		}
	}
	return result;
}

void print_point(const point_t& point) {
	std::cout << "(" << point.first
		<< ", " << point.second
		<< ")";
}

int main(int argc, char * argv[]) {
	std::default_random_engine re(std::chrono::system_clock::to_time_t(
		std::chrono::system_clock::now()));
	std::uniform_real_distribution<double> urd(-500.0, 500.0);
	std::vector<point_t> points(100);
	std::generate(std::begin(points), std::end(points), [&urd, &re]() {
                return point_t { 1000 + urd(re), 1000 + urd(re) };
        });
	auto answer = find_closest_brute(points);
	std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
		return a.first < b.first;
	});
	auto xP = points;
	std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {
		return a.second < b.second;
	});
	auto yP = points;
	std::cout << "Min distance (brute): " << answer.first << " ";
	print_point(answer.second.first);
	std::cout << ", ";
	print_point(answer.second.second);
	answer = find_closest_optimized(xP, yP);
	std::cout << "\nMin distance (optimized): " << answer.first << " ";
	print_point(answer.second.first);
	std::cout << ", ";
	print_point(answer.second.second);
	return 0;
}

provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.


built-in array[edit]

int a[5]; // array of 5 ints (since int is POD, the members are not initialized)
a[0] = 1; // indexes start at 0

int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // arrays can be initialized on creation

#include <string>
std::string strings[4]; // std::string is no POD, therefore all array members are default-initialized
                        // (for std::string this means initialized with empty strings)

vector[edit]

#include <vector>

std::vector<int> v;       // empty vector
v.push_back(5);           // insert a 5 at the end
v.insert(v.begin(), 7);   // insert a 7 at the beginning

deque[edit]

#include <deque>

std::deque<int> d;        // empty deque
d.push_back(5);           // insert a 5 at the end
d.push_front(7);          // insert a 7 at the beginning
d.insert(v.begin()+1, 6); // insert a 6 in the middle

list[edit]

#include <list>

std::list<int> l;         // empty list
l.push_back(5);           // insert a 5 at the end
l.push_front(7);          // insert a 7 at the beginning
std::list::iterator i = l.begin();
++l;
l.insert(i, 6);           // insert a 6 in the middle

set[edit]

#include <set>

std::set<int> s;          // empty set
s.insert(5);              // insert a 5
s.insert(7);              // insert a 7 (automatically placed after the 5)
s.insert(5);              // try to insert another 5 (will not change the set)

multiset[edit]

#include <multiset>

std::multiset<int> m;     // empty multiset
m.insert(5);              // insert a 5
m.insert(7);              // insert a 7 (automatically placed after the 5)
m.insert(5);              // insert a second 5 (now m contains two 5s, followed by one 7)

demonstrate the creation and usage of various collections in C++. It includes the creation of a collection and adding values to it. The collections used include built-in arrays, vectors, deques, lists, sets, and multisets. The code also demonstrates the different optimizations and behaviors of these collections, such as resizable arrays, efficient access to elements, and sorted elements. It also covers the use of user-defined types in collections and the requirement for types to be copyable and assignable.


#include <iostream>

int main()
{
  int i;
  for (i = 1; i<=10 ; i++){
    std::cout << i;
    if (i < 10)
     std::cout << ", ";
  }
  return 0;
}

The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.


C++11[edit]
#include <map>
#include <set>

template<typename Goal>
class topological_sorter {
protected:
    struct relations {
        std::size_t dependencies;
        std::set<Goal> dependents;
    };
    std::map<Goal, relations> map;
public:
    void add_goal(Goal const &goal) {
        map[goal];
    }
    void add_dependency(Goal const &goal, Goal const &dependency) {
        if (dependency == goal)
            return;
        auto &dependents = map[dependency].dependents;
        if (dependents.find(goal) == dependents.end()) {
            dependents.insert(goal);
            ++map[goal].dependencies;
        }
    }
    template<typename Container>
    void add_dependencies(Goal const &goal, Container const &dependencies) {
        for (auto const &dependency : dependencies)
            add_dependency(goal, dependency);
    }
    template<typename ResultContainer, typename CyclicContainer>
    void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {
        sorted.clear();
        unsortable.clear();
        for (auto const &lookup : map) {
            auto const &goal = lookup.first;
            auto const &relations = lookup.second;
            if (relations.dependencies == 0)
                sorted.push_back(goal);
        }
        for (std::size_t index = 0; index < sorted.size(); ++index)
            for (auto const &goal : map[sorted[index]].dependents)
                if (--map[goal].dependencies == 0)
                    sorted.push_back(goal);
        for (auto const &lookup : map) {
            auto const &goal = lookup.first;
            auto const &relations = lookup.second;
            if (relations.dependencies != 0)
                unsortable.push_back(goal);
        }
    }
    template<typename ResultContainer, typename CyclicContainer>
    void sort(ResultContainer &sorted, CyclicContainer &unsortable) {
        topological_sorter<Goal> temporary = *this;
        temporary.destructive_sort(sorted, unsortable);
    }
    void clear() {
        map.clear();
    }
};

/*
 Example usage with text strings
 */

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void display_heading(string const &message) {
    cout << endl << "~ " << message << " ~" << endl;
}
void display_results(string const &input) {
    topological_sorter<string> sorter;
    vector<string> sorted, unsortable;
    stringstream lines(input);
    string line;
    while (getline(lines, line)) {
        stringstream buffer(line);
        string goal, dependency;
        buffer >> goal;
        sorter.add_goal(goal);
        while (buffer >> dependency)
            sorter.add_dependency(goal, dependency);
    }
    sorter.destructive_sort(sorted, unsortable);
    if (sorted.size() == 0)
        display_heading("Error: no independent variables found!");
    else {
        display_heading("Result");
        for (auto const &goal : sorted)
            cout << goal << endl;
    }
    if (unsortable.size() != 0) {
        display_heading("Error: cyclic dependencies detected!");
        for (auto const &goal : unsortable)
            cout << goal << endl;
    }
}
int main(int argc, char **argv) {
    if (argc == 1) {
        string example = "des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n"
                "dw01             ieee dw01 dware gtech\n"
                "dw02             ieee dw02 dware\n"
                "dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\n"
                "dw04             dw04 ieee dw01 dware gtech\n"
                "dw05             dw05 ieee dware\n"
                "dw06             dw06 ieee dware\n"
                "dw07             ieee dware\n"
                "dware            ieee dware\n"
                "gtech            ieee gtech\n"
                "ramlib           std ieee\n"
                "std_cell_lib     ieee std_cell_lib\n"
                "synopsys\n"
                "cycle_11     cycle_12\n"
                "cycle_12     cycle_11\n"
                "cycle_21     dw01 cycle_22 dw02 dw03\n"
                "cycle_22     cycle_21 dw01 dw04";
        display_heading("Example: each line starts with a goal followed by it's dependencies");
        cout << example << endl;
        display_results(example);
        display_heading("Enter lines of data (press enter when finished)");
        string line, data;
        while (getline(cin, line) && !line.empty())
            data += line + '\n';
        if (!data.empty())
            display_results(data);
    } else
        while (*(++argv)) {
            ifstream file(*argv);
            typedef istreambuf_iterator<char> iterator;
            display_results(string(iterator(file), iterator()));
        }
}

C++17[edit]
#include <unordered_map>
#include <unordered_set>
#include <vector>

template <typename ValueType>
class topological_sorter
{
public:
    using value_type = ValueType;

protected:
    struct relations
    {
        std::size_t dependencies { 0 };
        std::unordered_set<value_type> dependents {};
    };

    std::unordered_map<value_type, relations> _map {};

public:
    void add(const value_type &object)
    {
        _map.try_emplace(object, relations {});
    }

    void add(const value_type &object, const value_type &dependency)
    {
        if (dependency == object) return;

        auto &dependents = _map[dependency].dependents;

        if (dependents.find(object) == std::end(dependents))
        {
            dependents.insert(object);

            ++_map[object].dependencies;
        }
    }

    template <typename Container>
    void add(const value_type &object, const Container &dependencies)
    {
        for (auto const &dependency : dependencies) add(object, dependency);
    }

    void add(const value_type &object, const std::initializer_list<value_type> &dependencies)
    {
        add<std::initializer_list<value_type>>(object, dependencies);
    }

    template<typename... Args>
    void add(const value_type &object, const Args&... dependencies)
    {
        (add(object, dependencies), ...);
    }

    auto sort()
    {
        std::vector<value_type> sorted, cycled;
        auto map { _map };

        for (const auto &[object, relations] : map) if (!relations.dependencies) sorted.emplace_back(object);

        for (decltype(std::size(sorted)) idx = 0; idx < std::size(sorted); ++idx)
            for (auto const& object : map[sorted[idx]].dependents)
                if (!--map[object].dependencies) sorted.emplace_back(object);

        for (const auto &[object, relations] : map) if (relations.dependencies) cycled.emplace_back(std::move(object));

        return std::pair(std::move(sorted), std::move(cycled));
    }

    void clear()
    {
        _map.clear();
    }
};

/*
	Example usage with shared_ptr to class
*/
#include <iostream>
#include <memory>

int main()
{
    using namespace std::string_literals;

    struct task
    {
        std::string message;

        task(const std::string &v) : message { v } {}
        ~task() { std::cout << message[0] << " - destroyed" << std::endl; }
    };

    using task_ptr = std::shared_ptr<task>;

    std::vector<task_ptr> tasks
    {
        // defining simple tasks
        std::make_shared<task>("A - depends on B and C"s),    //0
        std::make_shared<task>("B - depends on none"s),       //1
        std::make_shared<task>("C - depends on D and E"s),    //2
        std::make_shared<task>("D - depends on none"s),       //3
        std::make_shared<task>("E - depends on F, G and H"s), //4
        std::make_shared<task>("F - depends on I"s),          //5
        std::make_shared<task>("G - depends on none"s),       //6
        std::make_shared<task>("H - depends on none"s),       //7
        std::make_shared<task>("I - depends on none"s),       //8
    };

    topological_sorter<task_ptr> resolver;

    // now setting relations between them as described above
    resolver.add(tasks[0], { tasks[1], tasks[2] });
    //resolver.add(tasks[1]); // no need for this since the task was already mentioned as a dependency
    resolver.add(tasks[2], { tasks[3], tasks[4] });
    //resolver.add(tasks[3]); // no need for this since the task was already mentioned as a dependency
    resolver.add(tasks[4], tasks[5], tasks[6], tasks[7]); // using templated add with fold expression
    resolver.add(tasks[5], tasks[8]);
    //resolver.add(tasks[6]); // no need for this since the task was already mentioned as a dependency
    //resolver.add(tasks[7]); // no need for this since the task was already mentioned as a dependency

    //resolver.add(tasks[3], tasks[0]); // uncomment this line to test cycled dependency

    const auto &[sorted, cycled] = resolver.sort();

    if (std::empty(cycled))
    {
        for (auto const& d: sorted)
            std::cout << d->message << std::endl;
    }
    else
    {
        std::cout << "Cycled dependencies detected: ";

        for (auto const& d: cycled)
            std::cout << d->message[0] << " ";

        std::cout << std::endl;
    }

    //tasks.clear(); // uncomment this line to destroy all tasks in sorted order.

    std::cout << "exiting..." << std::endl;

    return 0;
}

The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.


#include <string>
using namespace std;

string s1="abcd";
string s2="abab";
string s3="ab";
//Beginning
s1.compare(0,s3.size(),s3)==0;
//End
s1.compare(s1.size()-s3.size(),s3.size(),s3)==0;
//Anywhere
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2

The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.


//C++14/17
#include <algorithm>//std::for_each
#include <iostream> //std::cout
#include <numeric>  //std::iota
#include <vector>   //std::vector, save solutions
#include <list>     //std::list, for fast erase

using std::begin, std::end, std::for_each;

//Generates all the valid solutions for the problem in the specified range [from, to)
std::list<std::vector<int>> combinations(int from, int to)
{
    if (from > to)
        return {};                          //Return nothing if limits are invalid

    auto pool = std::vector<int>(to - from);//Here we'll save our values
    std::iota(begin(pool), end(pool), from);//Populates pool

    auto solutions = std::list<std::vector<int>>{};   //List for the solutions

    //Brute-force calculation of valid values...
    for (auto a : pool)
        for (auto b : pool)
            for (auto c : pool)
                for (auto d : pool)
                    for (auto e : pool)
                        for (auto f : pool)
                            for (auto g : pool)
                                if ( a      == c + d
                                  && b + c  == e + f
                                  && d + e  ==     g )
                                    solutions.push_back({a, b, c, d, e, f, g});
    return solutions;
}

//Filter the list generated from "combinations" and return only lists with no repetitions
std::list<std::vector<int>> filter_unique(int from, int to)
{
    //Helper lambda to check repetitions:
    //If the count is > 1 for an element, there must be a repetition inside the range
    auto has_non_unique_values = [](const auto & range, auto target)
    {
        return std::count( begin(range), end(range), target) > 1;
    };

    //Generates all the solutions...
    auto results = combinations(from, to);

    //For each solution, find duplicates inside
    for (auto subrange = cbegin(results); subrange != cend(results); ++subrange)
    {
        bool repetition = false;

        //If some element is repeated, repetition becomes true
        for (auto x : *subrange)
            repetition |= has_non_unique_values(*subrange, x);

        if (repetition)    //If repetition is true, remove the current subrange from the list
        {
            results.erase(subrange);        //Deletes subrange from solutions
            --subrange;                     //Rewind to the last subrange analysed
        }
    }

    return results; //Finally return remaining results
}

template <class Container> //Template for the sake of simplicity
inline void print_range(const Container & c)
{
    for (const auto & subrange : c)
    {
        std::cout << "[";
        for (auto elem : subrange)
            std::cout << elem << ' ';
        std::cout << "\b]\n";
    }
}

int main()
{
    std::cout << "Unique-numbers combinations in range 1-7:\n";
    auto solution1 = filter_unique(1, 8);
    print_range(solution1);
    std::cout << "\nUnique-numbers combinations in range 3-9:\n";
    auto solution2 = filter_unique(3,10);
    print_range(solution2);
    std::cout << "\nNumber of combinations in range 0-9: "
              << combinations(0, 10).size() << "." << std::endl;

    return 0;
}

Unique-numbers combinations in range 1-7:
[3 7 2 1 5 4 6]
[4 5 3 1 6 2 7]
[4 7 1 3 2 6 5]
[5 6 2 3 1 7 4]
[6 4 1 5 2 3 7]
[6 4 5 1 2 7 3]
[7 2 6 1 3 5 4]
[7 3 2 5 1 4 6]

Unique-numbers combinations in range 3-9:
[7 8 3 4 5 6 9]
[8 7 3 5 4 6 9]
[9 6 4 5 3 7 8]
[9 6 5 4 3 8 7]

Number of combinations in range 0-9: 2860.

The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It replaces letters a to g with unique decimal digits ranging from a specified low to high value. It provides solutions for ranges 1-7 and 3-9 where each letter is unique. Additionally, it calculates the number of solutions for the range 0-9 where letters can be non-unique.


#include <windows.h>
#include <string>
#include <math.h>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20,
          MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20;
const float PI = 3.1415926536f;

//--------------------------------------------------------------------------------------------------
class vector2
{
public:
    vector2() { x = y = 0; }
    vector2( int a, int b ) { x = a; y = b; }
    void set( int a, int b ) { x = a; y = b; }
    void rotate( float angle_r )
    {
	float _x = static_cast<float>( x ),
	      _y = static_cast<float>( y ),
	       s = sinf( angle_r ),
	       c = cosf( angle_r ),
	       a = _x * c - _y * s,
	       b = _x * s + _y * c;

	x = static_cast<int>( a );
	y = static_cast<int>( b );
    }
    int x, y;
};
//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteObject( brush );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO    bi;
	ZeroMemory( &bi, sizeof( bi ) );
	bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes      = 1;
	bi.bmiHeader.biWidth       =  w;
	bi.bmiHeader.biHeight      = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;
	return true;
    }

    void clear( BYTE clr = 0 )
    {
	memset( pBits, clr, width * height * sizeof( DWORD ) );
    }

    void setBrushColor( DWORD bClr )
    {
	if( brush ) DeleteObject( brush );
	brush = CreateSolidBrush( bClr );
	SelectObject( hdc, brush );
    }

    void setPenColor( DWORD c )
    {
	clr = c;
	createPen();
    }

    void setPenWidth( int w )
    {
	wid = w;
	createPen();
    }

    void saveBitmap( string path )
    {
	BITMAPFILEHEADER fileheader;
	BITMAPINFO       infoheader;
	BITMAP           bitmap;
	DWORD            wb;

	GetObject( bmp, sizeof( bitmap ), &bitmap );
	DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];

        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }

private:
    void createPen()
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, wid, clr );
	SelectObject( hdc, pen );
    }

    HBITMAP bmp;
    HDC     hdc;
    HPEN    pen;
    HBRUSH  brush;
    void    *pBits;
    int     width, height, wid;
    DWORD   clr;
};
//--------------------------------------------------------------------------------------------------
class clock
{
public:
    clock()
    {
	_bmp.create( BMP_SIZE, BMP_SIZE );
	_bmp.clear( 100 );
	_bmp.setPenWidth( 2 );
	_ang = DegToRadian( 6 );
    }

    void setNow()
    {
	GetLocalTime( &_sysTime );
	draw();
    }

    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }

    void setHWND( HWND hwnd ) { _hwnd = hwnd; }

private:
    void drawTicks( HDC dc )
    {
	vector2 line;
	_bmp.setPenWidth( 1 );
	for( int x = 0; x < 60; x++ )
	{
	    line.set( 0, 50 );
	    line.rotate( static_cast<float>( x + 30 ) * _ang );
	    MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL );
	    LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) );
	}

	_bmp.setPenWidth( 3 );
	for( int x = 0; x < 60; x += 5 )
	{
	    line.set( 0, 50 );
	    line.rotate( static_cast<float>( x + 30 ) * _ang );
	    MoveToEx( dc, CENTER - static_cast<int>( 2.5f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.5f * static_cast<float>( line.y ) ), NULL );
	    LineTo( dc, CENTER - static_cast<int>( 2.81f * static_cast<float>( line.x ) ), CENTER - static_cast<int>( 2.81f * static_cast<float>( line.y ) ) );
	}
    }

    void drawHands( HDC dc )
    {
	float hp = DegToRadian( ( 30.0f * static_cast<float>( _sysTime.wMinute ) ) / 60.0f );
	int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5;

	_bmp.setPenWidth( 3 );
	_bmp.setPenColor( RGB( 0, 0, 255 ) );
	drawHand( dc, HOUR_LEN, ( _ang * static_cast<float>( 30 + h ) ) + hp );

	_bmp.setPenColor( RGB( 0, 128, 0 ) );
	drawHand( dc, MIN_LEN, _ang * static_cast<float>( 30 + _sysTime.wMinute ) );

	_bmp.setPenWidth( 2 );
	_bmp.setPenColor( RGB( 255, 0, 0 ) );
	drawHand( dc, SEC_LEN, _ang * static_cast<float>( 30 + _sysTime.wSecond ) );
    }

    void drawHand( HDC dc, int len, float ang )
    {
	vector2 line;
	line.set( 0, len );
	line.rotate( ang );
	MoveToEx( dc, CENTER, CENTER, NULL );
	LineTo( dc, line.x + CENTER, line.y + CENTER );
    }

    void draw()
    {
	HDC dc = _bmp.getDC();

	_bmp.setBrushColor( RGB( 250, 250, 250 ) );
	Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE );
	_bmp.setBrushColor( RGB( 230, 230, 230 ) );
	Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 );

	drawTicks( dc );
	drawHands( dc );

	_bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 );
	Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 );

	_wdc = GetDC( _hwnd );
	BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
	ReleaseDC( _hwnd, _wdc );
    }

    myBitmap   _bmp;
    HWND       _hwnd;
    HDC        _wdc;
    SYSTEMTIME _sysTime;
    float      _ang;
};
//--------------------------------------------------------------------------------------------------
class wnd
{
public:
    wnd() { _inst = this; }
    int wnd::Run( HINSTANCE hInst )
    {
	_hInst = hInst;
	_hwnd = InitAll();
	SetTimer( _hwnd, MY_TIMER, 1000, NULL );
	_clock.setHWND( _hwnd );

	ShowWindow( _hwnd, SW_SHOW );
	UpdateWindow( _hwnd );

	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );
	while( msg.message != WM_QUIT )
	{
	    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
	    {
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	    }
	}
	return UnregisterClass( "_MY_CLOCK_", _hInst );
    }
private:
    void wnd::doPaint( HDC dc ) { _clock.setNow(); }
    void wnd::doTimer()         { _clock.setNow(); }
    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
    {
	switch( msg )
	{
	    case WM_DESTROY: PostQuitMessage( 0 ); break;
	    case WM_PAINT:
	    {
		PAINTSTRUCT ps;
		HDC dc = BeginPaint( hWnd, &ps );
		_inst->doPaint( dc );
		EndPaint( hWnd, &ps );
		return 0;
	    }
	    case WM_TIMER: _inst->doTimer(); break;
	    default:
		return DefWindowProc( hWnd, msg, wParam, lParam );
	}
	return 0;
    }

    HWND InitAll()
    {
	WNDCLASSEX wcex;
	ZeroMemory( &wcex, sizeof( wcex ) );
	wcex.cbSize           = sizeof( WNDCLASSEX );
	wcex.style           = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc   = ( WNDPROC )WndProc;
	wcex.hInstance     = _hInst;
	wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
	wcex.lpszClassName = "_MY_CLOCK_";

	RegisterClassEx( &wcex );

	RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
	AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
	int w = rc.right - rc.left, h = rc.bottom - rc.top;
	return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
    }

    static wnd* _inst;
    HINSTANCE  _hInst;
    HWND       _hwnd;
    clock      _clock;
};
wnd* wnd::_inst = 0;
//--------------------------------------------------------------------------------------------------
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
    wnd myWnd;
    return myWnd.Run( hInstance );
}
//--------------------------------------------------------------------------------------------------

The code creates a simple, non-resource-intensive clock that displays the passage of seconds. It uses system or language-specific timers or events instead of constant polling. The clock display updates every second and cycles after a set period. The code is written in a clear and concise manner.


#include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>

using namespace std;

auto CountTriplets(unsigned long long maxPerimeter)
{
    unsigned long long totalCount = 0;
    unsigned long long primitveCount = 0;
    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
    for(unsigned long long m = 2; m < max_M; ++m)
    {
        for(unsigned long long n = 1 + m % 2; n < m; n+=2)
        {
            if(gcd(m,n) != 1)
            {
                continue;
            }

            // The formulas below will generate primitive triples if:
            //   0 < n < m
            //   m and n are relatively prime (gcd == 1)
            //   m + n is odd

            auto a = m * m - n * n;
            auto b = 2 * m * n;
            auto c = m * m + n * n;
            auto perimeter = a + b + c;
            if(perimeter <= maxPerimeter)
            {
                primitveCount++;
                totalCount+= maxPerimeter / perimeter;
            }
        }
    }

    return tuple(totalCount, primitveCount);
}

int main()
{
    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
        1000'000, 10'000'000, 100'000'000, 1000'000'000,
        10'000'000'000};  // This last one takes almost a minute
    for(auto maxPerimeter : inputs)
    {
        auto [total, primitive] = CountTriplets(maxPerimeter);
        cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
    }
}

The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.


Library: Qt
Uses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses library" (as page type) with input value "library/Qt/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

#include <QApplication>
#include <QMainWindow>

int main(int argc, char *argv[])
{
 QApplication app(argc, argv);
 QMainWindow window;
 window.show();
 return app.exec();
}

Library: GTK

#include <iostream>
#include <gtkmm.h>

int
main( int argc, char* argv[] )
{
 try
 {
  Gtk::Main m( argc, argv ) ;
  Gtk::Window win ;
  m.run( win ) ;
 }

 catch( std::exception const & exc )
 {
  std::cout << exc.what() << std::endl ;
  exit( -1 ) ;
 }

 exit( 0 ) ;
}

create a GUI window that can respond to close requests. It is compiled using qmake and g++ commands.


#include <fstream>
#include <iostream>

int main()
{
	std::ifstream input("filename.txt", std::ios_base::binary);
	if (!input)
	{
		std::cerr << "error: can't open file\n";
		return -1;
	}

	size_t count[256];
	std::fill_n(count, 256, 0);

	for (char c; input.get(c); ++count[uint8_t(c)]) // process input file
		; // empty loop body

	for (size_t i = 0; i < 256; ++i)
	{
		if (count[i] && isgraph(i)) // non-zero counts of printable characters
		{
			std::cout << char(i) << " = " << count[i] << '\n';
		}
	}
}

Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.


struct link
{
  link* next;
  int data;
};

struct link
{
  link* next;
  int data;
  link(int a_data, link* a_next = 0): next(a_next), data(a_data) {}
};

 link* small_primes = new link(2, new link(3, new link(5, new link(7))));

template<typename T> struct link
{
  link* next;
  T data;
  link(T a_data, link* a_next = 0): next(a_next), data(a_data) {}
};

define a data structure for a singly-linked list element. This element contains a data member for holding a numeric value and a mutable link to the next element. The code also includes a constructor to simplify the initialization of links on the heap, allowing for direct initialization at allocation. The code is generic, supporting any data type, not just integral types.


#include <windows.h>
#include <string>
#include <math.h>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const float PI = 3.1415926536f;

//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO	bi;
	void		*pBits;
	ZeroMemory( &bi, sizeof( bi ) );
	bi.bmiHeader.biSize	   = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount	   = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes	   = 1;
	bi.bmiHeader.biWidth	   =  w;
	bi.bmiHeader.biHeight	   = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;

	return true;
    }

    void setPenColor( DWORD clr )
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, 1, clr );
	SelectObject( hdc, pen );
    }

    void saveBitmap( string path )
    {
	BITMAPFILEHEADER	fileheader;
	BITMAPINFO			infoheader;
	BITMAP				bitmap;
	DWORD*				dwpBits;
	DWORD				wb;
	HANDLE				file;

	GetObject( bmp, sizeof( bitmap ), &bitmap );

	dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC()     { return hdc; }
    int getWidth()  { return width; }
    int getHeight() { return height; }

private:
    HBITMAP bmp;
    HDC	    hdc;
    HPEN    pen;
    int     width, height;
};
//--------------------------------------------------------------------------------------------------
class vector2
{
public:
    vector2() { x = y = 0; }
    vector2( int a, int b ) { x = a; y = b; }
    void set( int a, int b ) { x = a; y = b; }
    void rotate( float angle_r )
    {
	float _x = static_cast<float>( x ),
	      _y = static_cast<float>( y ),
	       s = sinf( angle_r ),
	       c = cosf( angle_r ),
	       a = _x * c - _y * s,
	       b = _x * s + _y * c;

	x = static_cast<int>( a );
	y = static_cast<int>( b );
    }

    int x, y;
};
//--------------------------------------------------------------------------------------------------
class fractalTree
{
public:
    fractalTree()		      { _ang = DegToRadian( 24.0f ); }
    float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); }

    void create( myBitmap* bmp )
    {
	_bmp = bmp;
	float line_len = 130.0f;

	vector2 sp( _bmp->getWidth() / 2, _bmp->getHeight() - 1 );
	MoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );
	sp.y -= static_cast<int>( line_len );
	LineTo( _bmp->getDC(), sp.x, sp.y);

	drawRL( &sp, line_len, 0, true );
	drawRL( &sp, line_len, 0, false );
    }

private:
    void drawRL( vector2* sp, float line_len, float a, bool rg )
    {
	line_len *= .75f;
	if( line_len < 2.0f ) return;

	MoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );
	vector2 r( 0, static_cast<int>( line_len ) );

        if( rg ) a -= _ang;
        else a += _ang;

	r.rotate( a );
	r.x += sp->x; r.y = sp->y - r.y;

	LineTo( _bmp->getDC(), r.x, r.y );

	drawRL( &r, line_len, a, true );
	drawRL( &r, line_len, a, false );
    }

    myBitmap* _bmp;
    float     _ang;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );

    myBitmap bmp;
    bmp.create( 640, 512 );
    bmp.setPenColor( RGB( 255, 255, 0 ) );

    fractalTree tree;
    tree.create( &bmp );

    BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );

    bmp.saveBitmap( "f://rc//fracTree.bmp" );

    system( "pause" );

    return 0;
}
//--------------------------------------------------------------------------------------------------

Generates and draws a fractal tree by drawing the trunk, splitting it at an angle to create branches, and repeating this process until a desired level of branching is achieved.


#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>

std::vector<int> GenerateFactors(int n) {
    std::vector<int> factors = { 1, n };
    for (int i = 2; i * i <= n; ++i) {
        if (n % i == 0) {
            factors.push_back(i);
            if (i * i != n)
                factors.push_back(n / i);
        }
    }

    std::sort(factors.begin(), factors.end());
    return factors;
}

int main() {
    const int SampleNumbers[] = { 3135, 45, 60, 81 };

    for (size_t i = 0; i < sizeof(SampleNumbers) / sizeof(int); ++i) {
        std::vector<int> factors = GenerateFactors(SampleNumbers[i]);
        std::cout << "Factors of ";
        std::cout.width(4);
        std::cout << SampleNumbers[i] << " are: ";
        std::copy(factors.begin(), factors.end(), std::ostream_iterator<int>(std::cout, " "));
        std::cout << std::endl;
    }

    return EXIT_SUCCESS;
}

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


The code reads a text file where fields within a line are separated by a dollar symbol. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. The code does not require adding separating characters between or around columns. It handles trailing dollar characters and ignores consecutive spaces at the end of lines. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


#include<graphics.h>
#include<iostream>

int main()
{
    int k;
    initwindow(1500,810,"Rosetta Cuboid");

    do{
       std::cout<<"Enter ratio of sides ( 0 or -ve to exit) : ";
       std::cin>>k;

       if(k>0){
                bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1);
       }
       }while(k>0);

    return 0;
}

draw a 2x3x4 cuboid, with three visible faces, using either graphical representation or ASCII art, and can be either static or rotational. The code requires BGI for Windows from Colorado State University.


#include <iostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <cstdlib>
#include <string>

// the rot13 function
std::string rot13(std::string s)
{
  static std::string const
    lcalph = "abcdefghijklmnopqrstuvwxyz",
    ucalph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  std::string result;
  std::string::size_type pos;

  result.reserve(s.length());

  for (std::string::iterator it = s.begin(); it != s.end(); ++it)
  {
    if ( (pos = lcalph.find(*it)) != std::string::npos )
      result.push_back(lcalph[(pos+13) % 26]);
    else if ( (pos = ucalph.find(*it)) != std::string::npos )
      result.push_back(ucalph[(pos+13) % 26]);
    else
      result.push_back(*it);
  }

  return result;
}

// function to output the rot13 of a file on std::cout
// returns false if an error occurred processing the file, true otherwise
// on entry, the argument is must be open for reading
int rot13_stream(std::istream& is)
{
  std::string line;
  while (std::getline(is, line))
  {
    if (!(std::cout << rot13(line) << "\n"))
      return false;
  }
  return is.eof();
}

// the main program
int main(int argc, char* argv[])
{
  if (argc == 1) // no arguments given
    return rot13_stream(std::cin)? EXIT_SUCCESS : EXIT_FAILURE;

  std::ifstream file;
  for (int i = 1; i < argc; ++i)
  {
    file.open(argv[i], std::ios::in);
    if (!file)
    {
      std::cerr << argv[0] << ": could not open for reading: " << argv[i] << "\n";
      return EXIT_FAILURE;
    }
    if (!rot13_stream(file))
    {
      if (file.eof())
        // no error occurred for file, so the error must have been in output
        std::cerr << argv[0] << ": error writing to stdout\n";
      else
        std::cerr << argv[0] << ": error reading from " << argv[i] << "\n";
      return EXIT_FAILURE;
    }
    file.clear();
    file.close();
    if (!file)
      std::cerr << argv[0] << ": warning: closing failed for " << argv[i] << "\n";
  }
  return EXIT_SUCCESS;
}

Library: Boost
#include <iostream>
#include <string>
#include <boost/iostreams/concepts.hpp>    // output_filter
#include <boost/iostreams/operations.hpp>  // put
#include <boost/iostreams/filtering_stream.hpp>
#include <fstream>
namespace io = boost::iostreams;

class rot_output_filter : public io::output_filter
{
public:
    explicit rot_output_filter(int r=13):rotby(r),negrot(alphlen-r){};

    template<typename Sink>
    bool put(Sink& dest, int c){
        char uc = toupper(c);

        if(('A' <= uc) && (uc <= ('Z'-rotby)))
            c = c + rotby;
        else if ((('Z'-rotby) <= uc) && (uc <= 'Z'))
            c = c - negrot;
        return boost::iostreams::put(dest, c);
    };
private:
        static const int alphlen = 26;
        const int rotby;
        const int negrot;
};

int main(int argc, char *argv[])
{
    io::filtering_ostream out;
    out.push(rot_output_filter(13));
    out.push(std::cout);

    if (argc == 1) out << std::cin.rdbuf();
    else for(int i = 1; i < argc; ++i){
        std::ifstream in(argv[i]);
        out << in.rdbuf();
    }
}

C++11[edit]
#include <string>
#include <iostream>
#include <fstream>

char rot13(const char c){
	if (c >= 'a' && c <= 'z')
		return (c - 'a' + 13) % 26 + 'a';
	else if (c >= 'A' && c <= 'Z')
		return (c - 'A' + 13) % 26 + 'A';
	return c;
}

std::string &rot13(std::string &s){
	for (auto &c : s) //range based for is the only used C++11 feature
		c = rot13(c);
	return s;
}

void rot13(std::istream &in, std::ostream &out){
	std::string s;
	while (std::getline(in, s))
		out << rot13(s) << '\n';
}

int main(int argc, char *argv[]){
	if (argc == 1)
		rot13(std::cin, std::cout);
	for (int arg = 1; arg < argc; ++arg){
		std::ifstream f(argv[arg]);
		if (!f)
			return EXIT_FAILURE;
		rot13(f, std::cout);
	}
}

The code implements a rot-13 function that replaces each letter of the ASCII alphabet with the letter 13 places ahead, wrapping from z to a as necessary. It maintains case and leaves non-alphabetic characters unaltered. The function can be optionally wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line, or acts as a filter on its standard input. The code also includes an alternative approach that allows rotation by any number.


g++ -std=c++11 sort.cpp

#include <algorithm>
#include <iostream>
#include <string>

struct entry {
  std::string name;
  std::string value;
};

int main() {
  entry array[] = { { "grass", "green" }, { "snow", "white" },
                    { "sky", "blue" }, { "cherry", "red" } };

  std::cout << "Before sorting:\n";
  for (const auto &e : array) {
    std::cout << "{" << e.name << ", " << e.value << "}\n";
  }

  std::sort(std::begin(array), std::end(array),
            [](const entry & a, const entry & b) {
    return a.name < b.name;
  });

  std::cout << "After sorting:\n";
  for (const auto &e : array) {
    std::cout << "{" << e.name << ", " << e.value << "}\n";
  }
}

Before sorting:
{grass, green}
{snow, white}
{sky, blue}
{cherry, red}
After sorting:
{cherry, red}
{grass, green}
{sky, blue}
{snow, white}

sort an array of name-value pair structures by the key name using a custom comparator in C++11.


for(int i = 0; i < 5; ++i) {
  for(int j = 0; j < i; ++j)
    std::cout.put('*');

  std::cout.put('\n');
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


#include <map>

Creation[edit]

std::map<A, B> exampleMap

std::map<int, double> exampleMap

Insertion[edit]

Operator[][edit]

exampleMap[7] = 3.14

int myKey = 7;
double myValue = 3.14;
exampleMap[myKey] = myValue;

insert()[edit]

exampleMap.insert(std::pair<int, double>(7,3.14));

exampleMap.insert(std::make_pair(7,3.14));

Lookup[edit]

operator[][edit]

myValue = exampleMap[myKey]

find()[edit]

double myValue = 0.0;
std::map<int, double>::iterator myIterator = exampleMap.find(myKey);
if(exampleMap.end() != myIterator)
{
  // Return the value for that key.
  myValue = myIterator->second;
}

Example[edit]

#include <map>
#include <iostreams>

int main()
{
  // Create the map.
  std::map<int, double> exampleMap;

  // Choose our key
  int myKey = 7;

  // Choose our value
  double myValue = 3.14;

  // Assign a value to the map with the specified key.
  exampleMap[myKey] = myValue;

  // Retrieve the value
  double myRetrievedValue = exampleMap[myKey];

  // Display our retrieved value.
  std::cout << myRetrievedValue << std::endl;

  // main() must return 0 on success.
  return 0;
}

The code creates an associative array or map using the C++ standard std::map. It defines a map with a key of type A and a value of type B. It also shows how to define a map with a key type of int and a value of double. The code demonstrates two ways to insert values into the map using an example key of 7 and a value of 3.14. It also explains how to retrieve values from the map using the correct key or using the find() function. If a value doesn't exist, it inserts a default-constructed object of the value's type using the specified key and returns that default value. The code also prints the value to STDOUT.


The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the Linear Congruential Generator formula to generate a sequence of random numbers, starting from a seed value. The generated sequence matches the original generator when starting from the same seed. The code also includes the specific formulas used by BSD and Microsoft, and the range of possible output values for each.


template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
  new_node->next = list_node->next;
  list_node->next = new_node;
};

link<int>* a = new link<int>('A', new link<int>('B'));
link<int>* c = new link<int>('C');

 insert_after(a, c);

while (a)
{
  link<int>* tmp = a;
  a = a->next;
  delete tmp;
}

define a method to insert an element into a singly-linked list after a given element. The method is then used to insert element C into a list comprised of elements A and B, specifically after element A. The list is then destroyed after the operation.


template<int N>
struct Half
{
        enum { Result = N >> 1 };
};

template<int N>
struct Double
{
        enum { Result = N << 1 };
};

template<int N>
struct IsEven
{
        static const bool Result = (N & 1) == 0;
};

template<int Multiplier, int Multiplicand>
struct EthiopianMultiplication
{
        template<bool Cond, int Plier, int RunningTotal>
        struct AddIfNot
        {
                enum { Result = Plier + RunningTotal };
        };
        template<int Plier, int RunningTotal>
        struct AddIfNot <true, Plier, RunningTotal>
        {
                enum { Result = RunningTotal };
        };

        template<int Plier, int Plicand, int RunningTotal>
        struct Loop
        {
                enum { Result = Loop<Half<Plier>::Result, Double<Plicand>::Result,
                       AddIfNot<IsEven<Plier>::Result, Plicand, RunningTotal >::Result >::Result };
        };
        template<int Plicand, int RunningTotal>
        struct Loop <0, Plicand, RunningTotal>
        {
                enum { Result = RunningTotal };
        };

        enum { Result = Loop<Multiplier, Multiplicand, 0>::Result };
};

#include <iostream>

int main(int, char **)
{
        std::cout << EthiopianMultiplication<17, 54>::Result << std::endl;
        return 0;
}

The code defines three functions to halve an integer, double an integer, and check if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two integers using only addition, doubling, and halving operations. The multiplication process involves repeatedly halving the first number and doubling the second number, discarding rows where the halved number is even, and summing the remaining values in the doubled column to get the multiplication result. The code is implemented as a C++ meta-program, running at compile time with the result saved into the compiled code.


Works with: C++11
Works with: GCC version 4.8

#include <iostream>
#include <ratio>
#include <array>
#include <algorithm>
#include <random>

typedef short int Digit;  // Typedef for the digits data type.

constexpr Digit nDigits{4};      // Amount of digits that are taken into the game.
constexpr Digit maximumDigit{9}; // Maximum digit that may be taken into the game.
constexpr short int gameGoal{24};    // Desired result.

typedef std::array<Digit, nDigits> digitSet; // Typedef for the set of digits in the game.
digitSet d;

void printTrivialOperation(std::string operation) { // Prints a commutative operation taking all the digits.
	bool printOperation(false);
	for(const Digit& number : d) {
		if(printOperation)
			std::cout << operation;
		else
			printOperation = true;
		std::cout << number;
	}
	std::cout << std::endl;
}

void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") {
	std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;
}

int main() {
	std::mt19937_64 randomGenerator;
	std::uniform_int_distribution<Digit> digitDistro{1, maximumDigit};
	// Let us set up a number of trials:
	for(int trial{10}; trial; --trial) {
		for(Digit& digit : d) {
			digit = digitDistro(randomGenerator);
			std::cout << digit << " ";
		}
		std::cout << std::endl;
		std::sort(d.begin(), d.end());
		// We start with the most trivial, commutative operations:
		if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)
			printTrivialOperation(" + ");
		if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies<Digit>{}) == gameGoal)
			printTrivialOperation(" * ");
		// Now let's start working on every permutation of the digits.
		do {
			// Operations with 2 symbols + and one symbol -:
			if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); // If gameGoal is ever changed to a smaller value, consider adding more operations in this category.
			// Operations with 2 symbols + and one symbol *:
			if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + ");
			if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + ");
			if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )");
			// Operations with one symbol + and 2 symbols *:
			if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + ");
			if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )");
			if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )");
			// Operations with one symbol - and 2 symbols *:
			if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - ");
			if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )");
			if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )");
			// Operations with one symbol +, one symbol *, and one symbol -:
			if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - ");
			if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - ");
			if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + ");
			if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )");
			if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )");
			// Operations with one symbol *, one symbol /, one symbol +:
			if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + ");
			if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / ");
			if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / ");
			if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )");
			// Operations with one symbol *, one symbol /, one symbol -:
			if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - ");
			if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / ");
			if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / ");
			if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )");
			// Operations with 2 symbols *, one symbol /:
			if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / ");
			if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )");
			// Operations with 2 symbols /, one symbol -:
			if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )");
			// Operations with 2 symbols /, one symbol *:
			if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", "");
		} while(std::next_permutation(d.begin(), d.end())); // All operations are repeated for all possible permutations of the numbers.
	}
	return 0;
}

The code accepts four digits either from user input or random generation and computes arithmetic expressions based on the rules of the 24 game. It also provides examples of the generated solutions. The code can be extended to work with more numbers, different goals, or digit ranges.


#include <boost/iterator/counting_iterator.hpp>
#include <algorithm>

int factorial(int n)
{
  // last is one-past-end
  return std::accumulate(boost::counting_iterator<int>(1), boost::counting_iterator<int>(n+1), 1, std::multiplies<int>());
}

Iterative[edit]

//iteration with while
long long int factorial(long long int n)
{
   long long int r = 1;
   while(1<n)
       r *= n--;
   return r;
}

Template[edit]
template <int N>
struct Factorial
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Compare all Solutions (except the meta)[edit]
#include <algorithm>
#include <chrono>
#include <iostream>
#include <numeric>
#include <vector>
#include <boost/iterator/counting_iterator.hpp>

using ulli = unsigned long long int;

// bad style do-while and wrong for Factorial1(0LL) -> 0 !!!
ulli Factorial1(ulli m_nValue) {
    ulli result = m_nValue;
    ulli result_next;
    ulli pc = m_nValue;
    do {
        result_next = result * (pc - 1);
        result = result_next;
        pc--;
    } while (pc > 2);
    return result;
}

// iteration with while
ulli Factorial2(ulli n) {
    ulli r = 1;
    while (1 < n)
        r *= n--;
    return r;
}

// recursive
ulli Factorial3(ulli n) {
    return n < 2 ? 1 : n * Factorial3(n - 1);
}

// tail recursive
inline ulli _fac_aux(ulli n, ulli acc) {
    return n < 1 ? acc : _fac_aux(n - 1, acc * n);
}
ulli Factorial4(ulli n) {
    return _fac_aux(n, 1);
}

// accumulate with functor
ulli Factorial5(ulli n) {
    // last is one-past-end
    return std::accumulate(boost::counting_iterator<ulli>(1ULL),
                           boost::counting_iterator<ulli>(n + 1ULL), 1ULL,
                           std::multiplies<ulli>());
}

// accumulate with lambda
ulli Factorial6(ulli n) {
    // last is one-past-end
    return std::accumulate(boost::counting_iterator<ulli>(1ULL),
                           boost::counting_iterator<ulli>(n + 1ULL), 1ULL,
                           [](ulli a, ulli b) { return a * b; });
}

int main() {
    ulli v = 20; // max value with unsigned long long int
    ulli result;
    std::cout << std::fixed;
    using duration = std::chrono::duration<double, std::micro>;

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial1(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "do-while(1)               result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial2(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "while(2)                  result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial3(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "recursive(3)              result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial3(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "tail recursive(4)         result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial5(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "std::accumulate(5)        result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }

    {
        auto t1 = std::chrono::high_resolution_clock::now();
        result = Factorial6(v);
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "std::accumulate lambda(6) result " << result << " took " << duration(t2 - t1).count() << " µs\n";
    }
}

do-while(1)               result 2432902008176640000 took 0.110000 µs
while(2)                  result 2432902008176640000 took 0.078000 µs
recursive(3)              result 2432902008176640000 took 0.057000 µs
tail recursive(4)         result 2432902008176640000 took 0.056000 µs
std::accumulate(5)        result 2432902008176640000 took 0.056000 µs
std::accumulate lambda(6) result 2432902008176640000 took 0.079000 µs

The code defines a function that calculates the factorial of a positive integer number. The factorial is calculated either iteratively or recursively. The function may optionally handle negative input errors. The code can also be adapted for C++ using STL and boost, with an iterative version using a while loop.


#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>

bool contains_duplicates(std::string s)
{
  std::sort(s.begin(), s.end());
  return std::adjacent_find(s.begin(), s.end()) != s.end();
}

void game()
{
  typedef std::string::size_type index;

  std::string symbols = "0123456789";
  unsigned int const selection_length = 4;

  std::random_shuffle(symbols.begin(), symbols.end());
  std::string selection = symbols.substr(0, selection_length);
  std::string guess;
  while (std::cout << "Your guess? ", std::getline(std::cin, guess))
  {
    if (guess.length() != selection_length
        || guess.find_first_not_of(symbols) != std::string::npos
        || contains_duplicates(guess))
    {
      std::cout << guess << " is not a valid guess!";
      continue;
    }

    unsigned int bulls = 0;
    unsigned int cows = 0;
    for (index i = 0; i != selection_length; ++i)
    {
      index pos = selection.find(guess[i]);
      if (pos == i)
        ++bulls;
      else if (pos != std::string::npos)
        ++cows;
    }
    std::cout << bulls << " bulls, " << cows << " cows.\n";
    if (bulls == selection_length)
    {
      std::cout << "Congratulations! You have won!\n";
      return;
    }
  }
  std::cerr << "Oops! Something went wrong with input, or you've entered end-of-file!\nExiting ...\n";
  std::exit(EXIT_FAILURE);
}

int main()
{
  std::cout << "Welcome to bulls and cows!\nDo you want to play? ";
  std::string answer;
  while (true)
  {
    while (true)
    {
      if (!std::getline(std::cin, answer))
      {
        std::cout << "I can't get an answer. Exiting.\n";
        return EXIT_FAILURE;
      }
      if (answer == "yes" || answer == "Yes" || answer == "y" || answer == "Y")
        break;
      if (answer == "no" || answer == "No" || answer == "n" || answer == "N")
      {
        std::cout << "Ok. Goodbye.\n";
        return EXIT_SUCCESS;
      }
      std::cout << "Please answer yes or no: ";
    }
    game();
    std::cout << "Another game? ";
  }
}

generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.


Works with: C++11

#include <random>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
  random_device seed;
  mt19937 engine(seed());
  normal_distribution<double> dist(1.0, 0.5);
  auto rnd = bind(dist, engine);

  vector<double> v(1000);
  generate(v.begin(), v.end(), rnd);
  return 0;
}

Works with: C++03
#include <cstdlib>   // for rand
#include <cmath>     // for atan, sqrt, log, cos
#include <algorithm> // for generate_n

double const pi = 4*std::atan(1.0);

// simple functor for normal distribution
class normal_distribution
{
public:
  normal_distribution(double m, double s): mu(m), sigma(s) {}
  double operator() const // returns a single normally distributed number
  {
    double r1 = (std::rand() + 1.0)/(RAND_MAX + 1.0); // gives equal distribution in (0, 1]
    double r2 = (std::rand() + 1.0)/(RAND_MAX + 1.0);
    return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2);
  }
private:
  const double mu, sigma;
};

int main()
{
  double array[1000];
  std::generate_n(array, 1000, normal_distribution(1.0, 0.5));
  return 0;
}

Library: Boost

#include <vector>
#include "boost/random.hpp"
#include "boost/generator_iterator.hpp"
#include <boost/random/normal_distribution.hpp>
#include <algorithm>

typedef boost::mt19937 RNGType; ///< mersenne twister generator

int main() {
    RNGType rng;
    boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution
                           with mean of 1.0 and standard deviation of 0.5 */

    boost::variate_generator< RNGType, boost::normal_distribution<> >
                    get_rand(rng, rdist);

    std::vector<double> v(1000);
    generate(v.begin(),v.end(),get_rand);
    return 0;
}

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5 using the Mersenne Twister generator. The code also includes the option to change the generator type.


#include <iostream>
#include <numeric>

int main()
{
    int a[] = { 1, 3, -5 };
    int b[] = { 4, -2, -1 };

    std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;

    return 0;
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>

// word by word
template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
  std::string word;
  while (is >> word)
  {
    // send the word to the output iterator
    *dest = word;
  }
}

// line by line:
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
  std::string line;
  while (std::getline(is, line))
  {
    // store the line to the output iterator
    *dest = line;
  }
}

int main()
{
  // 1) sending words from std. in std. out (end with Return)
  read_words(std::cin,
             std::ostream_iterator<std::string>(std::cout, " "));

  // 2) appending lines from std. to vector (end with Ctrl+Z)
  std::vector<std::string> v;
  read_lines(std::cin, std::back_inserter(v));

  return 0;
}

template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<std::string> InIt;
    std::copy(InIt(is), InIt(),
              dest);
}

namespace detail
{
    struct ReadableLine : public std::string
    {
        friend std::istream & operator>>(std::istream & is, ReadableLine & line)
        {
            return std::getline(is, line);
        }
    };
}

template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
    typedef std::istream_iterator<detail::ReadableLine> InIt;
    std::copy(InIt(is), InIt(),
              dest);
}

The code reads data from a text stream either word-by-word or line-by-line until there is no more data. The amount of data in the stream is unknown. The read words or lines are then sent to a generic output iterator using specific functions. Alternatively, istream iterators can be used for reading words or lines.


Library: LibXML
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>

#ifndef LIBXML_TREE_ENABLED
#   error libxml was not configured with DOM tree support
#endif

#ifndef LIBXML_OUTPUT_ENABLED
#   error libxml was not configured with serialization support
#endif

// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
//   1) a ScopeGuard-like type to handle cleanup functions; and
//   2) an exception type that transforms the library's errors.

// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
    // C++20: Constructor can (and should) be [[nodiscard]].
    /*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
        f_{std::move(f)}
    {}

    ~scope_exit()
    {
        f_();
    }

    // Non-copyable, non-movable.
    scope_exit(scope_exit const&) = delete;
    scope_exit(scope_exit&&) = delete;
    auto operator=(scope_exit const&) -> scope_exit& = delete;
    auto operator=(scope_exit&&) -> scope_exit& = delete;

private:
    F f_;
};

// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
    libxml_error() : libxml_error(std::string{}) {}

    explicit libxml_error(std::string message) :
        std::runtime_error{make_message_(std::move(message))}
    {}

private:
    static auto make_message_(std::string message) -> std::string
    {
        if (auto const last_error = ::xmlGetLastError(); last_error)
        {
            if (not message.empty())
                message += ": ";
            message += last_error->message;
        }

        return message;
    }
};

auto add_text(::xmlNode* node, ::xmlChar const* content)
{
    // Create a new text node with the desired content.
    auto const text_node = ::xmlNewText(content);
    if (not text_node)
        throw libxml_error{"failed to create text node"};

    // Try to add it to the node. If it succeeds, that node will take
    // ownership of the text node. If it fails, we have to clean up the text
    // node ourselves first, then we can throw.
    if (auto const res = ::xmlAddChild(node, text_node); not res)
    {
        ::xmlFreeNode(text_node);
        throw libxml_error{"failed to add text node"};
    }

    return text_node;
}

auto main() -> int
{
    // Set this to true if you don't want the XML declaration.
    constexpr auto no_xml_declaration = false;

    try
    {
        // Initialize libxml.
        ::xmlInitParser();
        LIBXML_TEST_VERSION
        auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};

        // Create a new document.
        auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
        if (not doc)
            throw libxml_error{"failed to create document"};
        auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};

        // Create the root element.
        auto root = ::xmlNewNode(nullptr,
            reinterpret_cast<::xmlChar const*>(u8"root"));
        if (not root)
            throw libxml_error{"failed to create root element"};
        ::xmlDocSetRootElement(doc, root); // doc now owns root

        // Add whitespace. Unless you know the whitespace is not significant,
        // you should do this manually, rather than relying on automatic
        // indenting.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n    "));

        // Add the child element.
        if (auto const res = ::xmlNewTextChild(root, nullptr,
                reinterpret_cast<::xmlChar const*>(u8"element"),
                reinterpret_cast<::xmlChar const*>(
                    u8"\n        Some text here\n    "));
                not res)
            throw libxml_error{"failed to create child text element"};

        // Add whitespace.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));

        // Output tree. Note that the output is UTF-8 in all cases. If you
        // want something different, use xmlSaveFileEnc() or the second
        // argument of xmlSaveDoc().
        if constexpr (no_xml_declaration)
        {
            auto const save_context = ::xmlSaveToFilename("-", nullptr,
                XML_SAVE_NO_DECL);
            auto const save_context_cleanup = scope_exit{[save_context] {
                ::xmlSaveClose(save_context); }};

            if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
        else
        {
            if (auto const res = ::xmlSaveFile("-", doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
    }
    catch (std::exception const& x)
    {
        std::cerr << "ERROR: " << x.what() << '\n';
        return EXIT_FAILURE;
    }
}

Create a simple DOM and serialize it into the specified XML format.


#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main( ) {
   boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
   std::cout << to_simple_string( t ) << std::endl ;
   return 0 ;
}

C++ 11[edit]
#include <chrono>
#include <ctime> //for conversion std::ctime()
#include <iostream>

int main() {
    auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::cout << std::ctime(&timenow) << std::endl;
}

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The code is related to the task of date formatting and is compiled under Linux using g++ with the boost_date_time library.


#include <numeric>
#include <cctype>
#include <iostream>
#include <string>

template<typename result_sink_t>
auto sedol_checksum(std::string const& sedol, result_sink_t result_sink)
{
    if(sedol.size() != 6)
        return result_sink(0, "length of sedol string != 6");

    const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789";
    if(sedol.find_first_not_of(valid_chars) != std::string::npos)
        return result_sink(0, "sedol string contains disallowed characters");

    const int weights[] = {1,3,1,7,3,9};
    auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0
                                           , [](int acc, int prod){ return acc + prod; }
                                           , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; }
                                             );
    return result_sink((10 - (weighted_sum % 10)) % 10, nullptr);
}

int main()
{
    using namespace std;
    string inputs[] = {
       "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
       "557910", "B0YBKR", "585284", "B0YBKT", "B00030"
   };
   for(auto const & sedol : inputs)
   {
        sedol_checksum(sedol, [&](auto sum, char const * errorMessage)
        {
            if(errorMessage)
                cout << "error for sedol: " << sedol << " message: " <<  errorMessage << "\n";
            else
                cout << sedol << sum << "\n";
        });
   }
   return 0;
}

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


Library: Qt
// Based on https://www.cairographics.org/samples/gradient/

#include <QImage>
#include <QPainter>

int main() {
    const QColor black(0, 0, 0);
    const QColor white(255, 255, 255);

    const int size = 300;
    const double diameter = 0.6 * size;

    QImage image(size, size, QImage::Format_RGB32);
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing);

    QLinearGradient linearGradient(0, 0, 0, size);
    linearGradient.setColorAt(0, white);
    linearGradient.setColorAt(1, black);

    QBrush brush(linearGradient);
    painter.fillRect(QRect(0, 0, size, size), brush);

    QPointF point1(0.4 * size, 0.4 * size);
    QPointF point2(0.45 * size, 0.4 * size);
    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
    radialGradient.setColorAt(0, white);
    radialGradient.setColorAt(1, black);

    QBrush brush2(radialGradient);
    painter.setPen(Qt::NoPen);
    painter.setBrush(brush2);
    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));

    image.save("sphere.png");
    return 0;
}

represent the functionality to draw a sphere either graphically or in ASCII art, with the option for static or rotational projection, depending on the language capabilities.


#include <string>
#include <iostream>

using namespace std;

string Suffix(int num)
{
    switch (num % 10)
    {
        case 1 : if(num % 100 != 11) return "st";
           break;
        case 2 : if(num % 100 != 12) return "nd";
           break;
        case 3 : if(num % 100 != 13) return "rd";
    }

    return "th";
}

int main()
{
    cout << "Set [0,25]:" << endl;
    for (int i = 0; i < 26; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    cout << "Set [250,265]:" << endl;
    for (int i = 250; i < 266; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    cout << "Set [1000,1025]:" << endl;
    for (int i = 1000; i < 1026; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    return 0;
}

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


Works with: C++11
#include <algorithm>
#include <iostream>
#include <string>

std::string stripchars(std::string str, const std::string &chars)
{
    str.erase(
        std::remove_if(str.begin(), str.end(), [&](char c){
            return chars.find(c) != std::string::npos;
        }),
        str.end()
    );
    return str;
}

int main()
{
    std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
    return 0;
}

"Function to remove specific characters from a given string"


#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

class pair  {
public:
    pair( int s, std::string z )            { p = std::make_pair( s, z ); }
    bool operator < ( const pair& o ) const { return i() < o.i(); }
    int i() const                           { return p.first; }
    std::string s() const                   { return p.second; }
private:
    std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
    bool output;
    for( int x = 1; x <= c; x++ ) {
        output = false;
        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
            if( !( x % ( *i ).i() ) ) {
                std::cout << ( *i ).s();
                output = true;
            }
        }
        if( !output ) std::cout << x;
        std::cout << "\n";
    }
}
int main( int argc, char* argv[] ) {
    std::vector<pair> v;
    v.push_back( pair( 7, "Baxx" ) );
    v.push_back( pair( 3, "Fizz" ) );
    v.push_back( pair( 5, "Buzz" ) );
    std::sort( v.begin(), v.end() );
    gFizzBuzz( 20, v );
    return 0;
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


include <vector>
#include <algorithm>
#include <string>
#include <iostream>

int main( ) {
   std::vector<std::string> myStrings { "prepended to" , "my string" } ;
   std::string prepended = std::accumulate( myStrings.begin( ) ,
	 myStrings.end( ) , std::string( "" ) , []( std::string a ,
	    std::string b ) { return a + b ; } ) ;
   std::cout << prepended << std::endl ;
   return 0 ;
}

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.