Solved Problems

Output a string to the console

Write the string "Hello World!" to STDOUT
cpp
std::cout << "Hello World" << std::endl;
std::printf("Hello World\n");
Console::WriteLine(L"Hello World");

Retrieve a string containing ampersands from the variables in a url

My PHP script first does a query to obtain customer info for a form. The form has first name and last name fields among others. The customer has put entries such as "Ron & Jean" in the first name field in the database. Then the edit form script is called with variables such as

"http://myserver.com/custinfo/edit.php?mode=view&fname=Ron & Jean&lname=Smith".

The script variable for first name $_REQUEST['firstname'] never gets beyond the "Ron" value because of the ampersand in the data.

I have tried various functions like urldecode but all to no avail. I even tried encoding the url before the view screen is painted so that the url looks like "http://myserver/custinfo/edit.php?mode=view&fname="Ronxxnbsp;xxamp;xxnbsp;Jean"&lname=SMITH". (sorry I had to add the xx to replace the ampersand or it didn't display meaningful url contents the browser sees.)

Of course this fails for the same reasons. What is a better approach?
cpp
QUrl url("http://myserver.com/custinfo/edit.php");
url.addQueryItem("mode", "view");
url.addQueryItem("fname", "Ron & Jean");
url.addQueryItem("lname", "Smith");
QByteArray encodedUrl = url.toEncoded();

string-wrap

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> "

Expected output:
> The quick brown fox jumps over the lazy dog. The quick brown fox jumps over t
> he lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox
> jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The qui
> ck brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy
> dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps o
> ver the lazy dog. The quick brown fox jumps over the lazy dog.
cpp
#include <iostream>
#include <sstream>
#include <string>

using namespace std;

void rep(ostream &os, const string& str, int times)
{
while (times--)
os << str;
}

void wrap(ostream &os, const string& str, const string &prefix, int width)
{
for (int offset = 0; offset < str.size(); offset += width)
os << prefix << str.substr(offset, width) << endl;
}

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 78);
}

write a recursive c function to compute gcd(x,y).

cpp
// C code
#include <stdio.h>
#include <stdlib.h>

int gcd(int a, int b) {
if (b>a) return gcd(b,a); // Or just swap `b` with `a`
else if (b==0) return a;
return gcd (b, a%b);
}

int main(int argc, char *argv[]) {
printf("gcd = %d", gcd(atoi(argv[1]), atoi(argv[2])));
}

Define a string containing special characters

Define the literal string "\#{'}${"}/"
cpp
std::string special = "\\#{'}${\"}/";
String^ special = L"\\#{'}${\"}/";

Define a multiline string

Define the string:
"This
Is
A
Multiline
String"
cpp
std::string text =
"This\n"
"Is\n"
"A\n"
"Multiline\n"
"String";
String^ text = L"This\nIs\nA\nMultiline\nString";
std::string text = "This\nIs\nA\nMultiline\nString";

Define a string containing variables and expressions

Given variables a=3 and b=4 output "3+4=7"
cpp
Console::WriteLine(L"{0}+{1}={2}", a, b, a+b);
std::printf("%d+%d=%d\n", a, b, a+b);
std::cout << boost::format("%|1|+%|1|=%|1|") % a % b % (a+b) << std::endl;

Reverse the characters in a string

Given the string "reverse me", produce the string "em esrever"
cpp
String^ s = "reverse me";
array<Char>^ sa = s->ToCharArray();
Array::Reverse(sa);
String^ sr = gcnew String(sa);
std::string s = "reverse me";
std::reverse(s.begin(), s.end());
std::string s = "reverse me";
std::string sr(s.rbegin(), s.rend());
std::string s = "reverse me";
std::swap_ranges(s.begin(), (s.begin() + s.size() / 2), s.rbegin());

Reverse the words in a string

Given the string "This is a end, my only friend!", produce the string "friend! only my end, the is This"
cpp
array<Char>^ sep = {L' '};
array<String^>^ words =
String(L"This is the end, my only friend!").Split(sep, StringSplitOptions::RemoveEmptyEntries);

Array::Reverse(words); String^ newwords = String::Join(L" ", words);
std::string words = "This is the end, my only friend!"; std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" ")); std::reverse(swv.begin(), swv.end());
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ())).value();

Text wrapping

Wrap the string "The quick brown fox jumps over the lazy dog. " repeated ten times to a max width of 78 chars, starting each line with "> ", yielding this result:

> The quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog. The quick brown fox jumps
> over the lazy dog. The quick brown fox jumps over the lazy dog. The
> quick brown fox jumps over the lazy dog.
cpp
String^ input = ::copies("The quick brown fox jumps over the lazy dog. ", 10);
String^ sep = " "; String^ prefix = "> ";

String^ wrapped = textwrap(input, 74 - prefix->Length, sep, prefix);
Console::WriteLine("{0}", wrapped);
void rep(ostream &os, const string& str, int times)
{
while (times--)
os << str;
}

void wrap(ostream &os, const string& str, const string &prefix, int width)
{
int line_len = width;
bool first_word = true;

width -= prefix.size();
BOOST_FOREACH(string word, tokenizer<char_separator<char>>(str, char_separator<char>(" ")))
{
line_len += word.size();
if (line_len++ < width)
os << ' ';
else {
if (first_word)
first_word = false;
else
os << endl;
os << prefix;
line_len = word.size();
}
os << word;
}
os << endl;
}

int main()
{
stringstream input;

rep(input, "The quick brown fox jumps over the lazy dog. ", 10);
wrap(cout, input.str(), "> ", 72);
}

Remove leading and trailing whitespace from a string

Given the string "  hello    " return the string "hello".
cpp
String^ s = " hello "; String^ trimmed = s->Trim();

Simple substitution cipher

Take a string and return the ROT13 and ROT47 (Check Wikipedia) version of the string.
For example:
String is: Hello World #123
ROT13 returns: Uryyb Jbeyq #123
ROT47 returns: w6==@ (@C=5 R`ab
cpp
#include <algorithm>
#include <iostream>
#include <cctype>
using namespace std;

int rot13(int c) {
if (!isalpha(c)) {
return c;
} else {
char start = islower(c) ? 'a' : 'A';
return ((c - start) + 13) % 26 + start;
}
}

int rot47(int c) {
if (c < 33 || c > 126) {
return c;
} else {
return ((c - 33) + 47) % 94 + 33;
}
}

int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
string original = argv[i];

string rot13enc = original;
transform(original.begin(), original.end(), rot13enc.begin(), rot13);

string rot47enc = original;
transform(original.begin(), original.end(), rot47enc.begin(), rot47);

cout << "original: " << original << endl
<< "rot 13: " << rot13enc << endl
<< "rot 47: " << rot47enc << endl;
}
return 0;
}

Make a string uppercase

Transform "Space Monkey" into "SPACE MONKEY"
cpp
String(L"Space Monkey").ToUpper();
std::string s = "Space Monkey";
std::transform(s.begin(), s.end(), s.begin(), std::toupper);
std::string s = "Space Monkey";
boost::to_upper(s);

Make a string lowercase

Transform "Caps ARE overRated" into "caps are overrated"
cpp
std::string s = "Caps ARE overRated";
std::string sl(boost::to_lower_copy(s));
String(L"Caps ARE overRated").ToLower();

Capitalise the first letter of each word

Transform "man OF stEEL" into "Man Of Steel"
cpp
std::string words = "mAn OF stEEL";
std::transform(words.begin(), words.end(), words.begin(), ToCaps<>());
StringBuilder^ sb = gcnew StringBuilder(L"man OF stEEL");

for (int i = 0, isFirst = 1; i < sb->Length; ++i)
{
sb[i] = Char::IsWhiteSpace(sb[i]) ? (isFirst = 1, sb[i]) : isFirst ? (isFirst = 0, Char::ToUpper(sb[i])) : Char::ToLower(sb[i]);
}
std::string words = "mAn OF stEEL";
std::vector<std::string> swv;

boost::split(swv, words, boost::is_any_of(" "));
std::string newwords = (std::for_each(swv.begin(), swv.end(), StringTAndJ(WordToCaps))).value();

Find the distance between two points

cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);

How to calculate a number fatorial?

How can we calculate a number without using recursion?

Ex. 4! = 4*3*2*1 = 24
cpp
int fatorial(int n)
{
int i = n;
int ret = 1;
while (i>0){
ret*=i;
i--;
}
return ret;
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
cpp
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
String^ formatted = String::Format("{0,8:D8}", 42);
std::printf("%08d", 42);
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|08|") % 42 << std::endl;

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
cpp
String^ formatted = Convert::ToString(1024)->PadRight(6);
String^ formatted = String::Format("{0,-6:D}", 1024);
std::printf("%-6d\n", 1024);
std::ostringstream os;
os << std::setw(6) << std::setfill(' ') << std::left << 1024 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|-6|") % 1024 << std::endl;

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
cpp
String^ formatted = String::Format("{0,3:F2}", result);
Console::WriteLine("{0,3:F2}", (7. / 8.));
std::printf("%3.2f\n", result);
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|3.2f|") % result << std::endl;

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
cpp
String^ formatted = Convert::ToString(73)->PadLeft(10);
String^ formatted = String::Format("{0,10:D}", 73);
std::printf("%10d\n", 73);
std::ostringstream os;
os << std::setw(10) << std::setfill(' ') << 73 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|10|") % 73 << std::endl;

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
cpp
Random^ rnd = gcnew Random;
int rndInt = rnd->Next(100, 201);
std::srand(std::time(NULL));

unsigned lb = 100, ub = 200;
unsigned rnd = lb + (rand() % ((ub - lb) + 1));
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng; rng.seed(std::time(NULL));
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

unsigned rnd = generator();

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
cpp
void printAction(int i) { Console::Write("{0} ", i); }

array<int>^ genFillRand(array<int>^ arr, Random^ rnd, int lb, int ub)
{
for (int i = 0; i < arr->Length; ++i) arr[i] = rnd->Next(lb, ub + 1); return arr;
}

int main()
{
array<int>^ arr1 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);
array<int>^ arr2 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);

Action<int>^ print = gcnew Action<int>(printAction);
Array::ForEach<int>(arr1, print); Console::WriteLine();
Array::ForEach<int>(arr2, print); Console::WriteLine();
}
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng;
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

rng.seed(42L);
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);

rng.seed(42L);
std::cout << std::endl;
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);

Check if a string matches a regular expression

Display "ok" if "Hello" matches /[A-Z][a-z]+/
cpp
if ((gcnew Regex("[A-Z][a-z]+"))->IsMatch("Hello")) Console::WriteLine("ok");
if (Regex::IsMatch("Hello", "[A-Z][a-z]+")) Console::WriteLine("ok");
Regex^ rx = gcnew Regex("[A-Z][a-z]+");
if (rx->IsMatch("Hello")) Console::WriteLine("ok");
cmatch what;
if (regex_match("Hello", what, regex("[A-Z][a-z]+")))
cout << "ok" << endl;

Check if a string matches with groups

Display "two" if "one two three" matches /one (.*) three/
cpp
Match^ match = Regex::Match("one two three", "one (.*) three");
if (match->Success) Console::WriteLine("{0}", match->Groups[1]->Captures[0]);
cmatch what;
if (regex_match("one two three", what, regex("one (.*) three")))
cout << what[1] << endl;

Check if a string contains a match to a regular expression

Display "ok" if "abc 123 @#$" matches /\d+/
cpp
if (Regex::IsMatch("abc 123 @#$", "\\d+")) Console::WriteLine("ok");

Loop through a string matching a regex and performing an action for each match

Create a list [fish1,cow3,boat4] when matching "(fish):1 sausage (cow):3 tree (boat):4" with regex /\((\w+)\):(\d+)/
cpp
Match^ match = Regex::Match("(fish):1 sausage (cow):3 tree (boat):4", "\\((\\w+)\\):(\\d+)");

while (match->Success)
{
list->Add(match->Groups[1]->Captures[0]->ToString() + match->Groups[2]->Captures[0]->ToString());
match = match->NextMatch();
}

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
cpp
String^ Replaced = (gcnew Regex("e"))->Replace("Red Green Blue", "*", 1);

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
cpp
String^ Replaced = (gcnew Regex("{(\\w+)}"))->Replace("The {Quick} Brown {Fox}", gcnew MatchEvaluator(&RegRep::RepGroup));
String^ Replaced = Regex::Replace("The {Quick} Brown {Fox}", "{(\\w+)}", gcnew MatchEvaluator(&RegRep::RepGroup));

Define an empty list

Assign the variable "list" to a list with no elements
cpp
Generic::List<String^>^ list = gcnew Generic::List<String^>();
std::list<std::string> list;

Define a static list

Define the list [One, Two, Three, Four, Five]
cpp
array<String^>^ input = {"One", "Two", "Three", "Four", "Five"};
Generic::List<String^>^ list = gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) input);
Generic::List<String^>^ list = gcnew Generic::List<String^>();

list->Add("One");
list->Add("Two");
list->Add("Three");
list->Add("Four");
list->Add("Five");
std::string input[] = {"One", "Two", "Three", "Four", "Five"};
std::list<std::string> list(input, input + 5);
std::list<std::string> list;

list.push_back("One");
list.push_back("Two");
list.push_back("Three");
list.push_back("Four");
list.push_back("Five");
list<string> lst = { "One", "Two", "Three", "Four", "Five" };
list<string> lst;
lst += "One", "Two", "Three", "Four", "Five";

Join the elements of a list, separated by commas

Given the list [Apple, Banana, Carrot] produce "Apple, Banana, Carrot"
cpp
String^ result = String::Join(L", ", fruit->ToArray());
string fruits[] = {"Apple", "Banana", "Carrot"};
string result = boost::algorithm::join(fruits, ", ");

Join the elements of a list, in correct english

Create a function join that takes a List and produces a string containing an english language concatenation of the list. It should work with the following examples:
join([Apple, Banana, Carrot]) = "Apple, Banana, and Carrot"
join([One, Two]) = "One and Two"
join([Lonely]) = "Lonely"
join([]) = ""
cpp
Console::WriteLine(join(fruit));
string join(const vector<string> &s, int b=0)
{
switch (s.size() - b)
{
case 0: return "";
case 1: return s[b];
case 2: return s[b] + (s.size() > 2 ? "," : "") + " and " + s[b+1];
default: return s[b] + ", " + join(s, b+1);
}
}

Produce the combinations from two lists

Given two lists, produce the list of tuples formed by taking the combinations from the individual lists. E.g. given the letters ["a", "b", "c"] and the numbers [4, 5], produce the list: [["a", 4], ["b", 4], ["c", 4], ["a", 5], ["b", 5], ["c", 5]]
cpp
Specialized::StringCollection^ combinations = gcnew Specialized::StringCollection;

for each(int number in numbers)
for each(String^ letter in letters)
combinations->Add(makeCombo(letter, number));
string letters[] = { "a", "b", "c" };
int numbers[] = { 4, 5 };
list<pair<string,int> > combo;

for (int n = 0; n < sizeof numbers / sizeof *numbers; n++)
for (int l = 0; l < sizeof letters / sizeof *letters; l++)
combo.push_back(make_pair(letters[l], numbers[n]));

cout << combo << endl;

From a List Produce a List of Duplicate Entries

Taking a list:
["andrew", "bob", "chris", "bob"]

Write the code to produce a list of duplicates in the list:
["bob"]
cpp
vector<string> lst = { "andrew", "bob", "chris", "bob" };
vector<string> lst_no_dups;
vector<string> tmp;
vector<string> dups;

sort(lst.begin(), lst.end());
unique_copy(lst.begin(), lst.end(), back_inserter(lst_no_dups));
set_difference(lst.begin(), lst.end(),
lst_no_dups.begin(), lst_no_dups.end(),
back_inserter(tmp));
unique_copy(tmp.begin(), tmp.end(), back_inserter(dups));

cout << dups << endl;
list<string> lst = { "andrew", "bob", "chris", "bob" };
map<string,int> num_identical;
list<string> dups;

for (auto &s: lst)
num_identical[s]++;
for (auto &n: num_identical)
if (n.second > 1)
dups.push_back(n.first);
cout << dups << endl;

Fetch an element of a list by index

Given the list [One, Two, Three, Four, Five], fetch the third element ('Three')
cpp
String^ result = list[2];

Fetch the last element of a list

Given the list [Red, Green, Blue], access the last element ('Blue')
cpp
String^ result = list[list->Count - 1];
string last_elem = lst.back();

Find the common items in two lists

Given two lists, find the common items. E.g. given beans = ['broad', 'mung', 'black', 'red', 'white'] and colors = ['black', 'red', 'blue', 'green'], what are the bean varieties that are also color names?
cpp
array<String^>^ inbeans = {"broad", "mung", "black", "red", "white"};
Generic::ICollection<String^>^ beans = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) inbeans));

array<String^>^ incolors = {"black", "red", "blue", "green"};
Generic::ICollection<String^>^ colors = makeSET<String^>(gcnew Generic::List<String^>((Generic::IEnumerable<String^>^) incolors));

Generic::ICollection<String^>^ result = intersectSET<String^>(beans, colors);

Display the unique items in a list

Display the unique items in a list, e.g. given ages = [18, 16, 17, 18, 16, 19, 14, 17, 19, 18], display the unique elements, i.e. with duplicates removed.
cpp
array<int>^ input = {18, 16, 17, 18, 16, 19, 14, 17, 19, 18};
Generic::List<int>^ ages = gcnew Generic::List<int>((Generic::IEnumerable<int>^) input);

Generic::ICollection<int>^ result = makeSET<int>(ages);
list<int> input;
input += 18, 16, 17, 18, 16, 19, 14, 17, 19, 18;
input.sort();
unique_copy(input.begin(), input.end(), ostream_iterator<int>(cout, "\n"));

Remove an element from a list by index

Given the list [Apple, Banana, Carrot], remove the first element to produce the list [Banana, Carrot]
cpp
fruit->RemoveAt(0);

Remove the last element of a list

cpp
fruit->RemoveAt(fruit->Count - 1);

Rotate a list

Given a list ["apple", "orange", "grapes", "bananas"], rotate it by removing the first item and placing it on the end to yield ["orange", "grapes", "bananas", "apple"]
cpp
fruit->Add(fruit[0]); fruit->RemoveAt(0);
rotate(fruit.begin(), fruit.begin()+1, fruit.end());

Gather together corresponding elements from multiple lists

Given several lists, gather together the first element from every list, the second element from every list, and so on for all corresponding index values in the lists. E.g. for these three lists, first = ['Bruce', 'Tommy Lee', 'Bruce'], last = ['Willis', 'Jones', 'Lee'], years = [1955, 1946, 1940] the result should produce 3 actors. The middle actor should be Tommy Lee Jones.
cpp
array<String^>^ first = {"Bruce", "Tommy Lee", "Bruce"}; array<String^>^ last = {"Willis", "Jones", "Lee"}; array<String^>^ years = {"1955", "1946", "1940"};

array<String^>^ result = zip<String^>(",", first, last, years);
list<string> first = { "Bruce", "Tommy Lee", "Bruce" };
list<string> last = {"Willis", "Jones", "Lee"};
list<int> years = {1955, 1946, 1940};
list<tuple<string,string,int> > actors;

for (firstIt = first.begin(), lastIt = last.begin(), yearIt = years.begin();
firstIt != first.end() && lastIt != last.end() && yearIt != years.end();
++firstIt, ++lastIt, ++yearIt)
actors.push_back(make_tuple(*firstIt, *lastIt, *yearIt));

List Combinations

Given two source lists (or sets), generate a list (or set) of all the pairs derived by combining elements from the individual lists (sets). E.g. given suites = ['H', 'D', 'C', 'S'] and faces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'], generate the deck of 52 cards, confirm the deck size and check it contains an expected card, say 'Ace of Hearts'.
cpp
Specialized::StringCollection^ cards = gcnew Specialized::StringCollection;

for each(String^ suite in suites)
for each(String^ face in faces)
cards->Add(makeCard(suite, face));

Console::WriteLine("Deck has {0} cards", cards.Count);
if (cards->Contains(makeCard("h", "A"))) Console::WriteLine("Deck contains 'Ace of hearts'"); else Console::WriteLine("'Ace of hearts' not in deck");
auto suites = {"h", "d", "c", "s"};
auto faces = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
list<card> cards;

for (auto s: suites)
for (auto f: faces)
cards.push_back(make_pair(s,f));

cout << "Deck has " << cards.size() << " cards." << endl;

card ace_of_harts = make_pair("h", "A");
if (end(cards) != find_if(begin(cards), end(cards),
[&](const card& c) { return c == ace_of_harts; }))
cout << "Deck contain 'Ace of Harts'" << endl;
else
cout << "Deck lacks 'Ace of Harts'" << endl;

Perform an operation on every item of a list

Perform an operation on every item of a list, e.g.
for the list ["ox", "cat", "deer", "whale"] calculate
the list of sizes of the strings, e.g. [2, 3, 4, 5]
cpp
list<string> words;

words.push_back("ox");
words.push_back("cat");
words.push_back("deer");
words.push_back("whale");

for (list<string>::iterator it = words.begin(); it != words.end(); ++it)
cout << it->size() << ' ';
cout << endl;
auto words = { "ox", "cat", "deer", "whale" };
list<size_t> word_sizes;

transform(begin(words),
end(words),
back_inserter(word_sizes),
[](const string& s) { return s.size(); });

Split a list of things into numbers and non-numbers

Given a list that might contain e.g. a string, an integer, a float and a date,
split the list into numbers and non-numbers.
cpp
typedef variant<int,float,string,date> dynamic;

class is_number : public static_visitor<bool>
{
public:
bool operator()(int &) const {
return true;
}
bool operator()(float &) const {
return true;
}
bool operator()(string &) const {
return false;
}
bool operator()(date &) const {
return false;
}
};

int main()
{
list<dynamic> lst;
list<dynamic> numbers;
list<dynamic> non_numbers;

lst += "hello", 3.14f, 42, date(2011,Aug,23);

BOOST_FOREACH(dynamic v, lst)
if (apply_visitor(is_number(), v))
numbers += v;
else
non_numbers += v;
#include <iostream>
#include <list>

#include <boost/any.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/foreach.hpp>

using namespace boost;
using namespace boost::gregorian;
using namespace std;

int main()
{
list<any> lst;
list<any> numbers;
list<any> non_numbers;

lst.push_back(string("hello"));
lst.push_back(42);
lst.push_back(3.14f);
lst.push_back(date(day_clock::local_day()));

BOOST_FOREACH(const any &a, lst)
try
{
numbers.push_back(any_cast<int>(a));
}
catch (bad_any_cast &e)
{
try
{
numbers.push_back(any_cast<float>(a));
}
catch (bad_any_cast &e)
{
non_numbers.push_back(a);
}
}

// float and int are now in 'numbers' and the rest in 'non_numbers'
}

Test if a condition holds for all items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for all items of the list.
cpp
template <typename InputIterator, typename Predicate>
bool match_all(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, !pred(_1)) == last;
}

Test if a condition holds for any items of a list

Given a list, test if a certain logical condition (i.e. predicate) holds for any items of the list.
cpp
template <typename InputIterator, typename Predicate>
bool match_any(InputIterator first, InputIterator last, Predicate pred)
{
return find_if(first, last, pred) != last;
}

Define an empty map

cpp
Hashtable^ hash = gcnew Hashtable;
Generic::Dictionary<String^, String^>^ dict = gcnew Generic::Dictionary<String^, String^>();
std::map<int, std::string> m;

Define an unmodifiable empty map

cpp
const std::map<T1,T2> immutable_map_instance_of_type_t1_to_t2;

Define an initial map

Define the map {circle:1, triangle:3, square:4}
cpp
Hashtable^ shapes = gcnew Hashtable;

shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
Generic::Dictionary<String^, int>^ shapes = gcnew Generic::Dictionary<String^, int>();

shapes->Add("circle", 1);
shapes->Add("triangle", 3);
shapes->Add("square", 4);
map<string, int> shapes;

shapes["circle"] = 1;
shapes["triangle"] = 3;
shapes["square"] = 4;

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
cpp
if (pets->ContainsKey("mary")) Console::WriteLine("ok");
if (pets.find("mary") != pets.end()){
std::cout << "ok" << std::endl;
}
if (pets.count("mary") > 0)
cout << "ok" << endl;

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
cpp
if (pets->ContainsKey("joe")) Console::WriteLine(pets["joe"]);
cout << pets["joe"] << endl;

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
cpp
pets->Add("rob", "dog");
pets["rob"] = "dog";

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
cpp
if (pets->ContainsKey("bill"))
{
String^ value = safe_cast<String^>(pets["bill"]); pets->Remove("bill");
Console::WriteLine("{0}", value);
}

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
cpp
for each(String^ entry in input) hash[entry] = hash->ContainsKey(entry)
? Convert::ToInt32(hash[entry]->ToString()) + 1 : 1;
for each(String^ entry in input) dict[entry] = dict->ContainsKey(entry) ? dict[entry] + 1 : 1;
map<string,int> hist;
for (auto e: { "a","b","a","c","b","b" })
++hist[e];
for (auto e: hist)
cout << e.first << " : " << e.second << endl;

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
cpp
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}

Perform an action if a condition is true (IF .. THEN)

Given a variable name, if the value is "Bob", display the string "Hello, Bob!". Perform no action if the name is not equal.
cpp
if (name == "Bob") Console::WriteLine("Hello, {0}!", name);
if (name == "Bob") std::cout << "Hello, " << name << "!" << std::endl;

Perform different actions depending on a boolean condition (IF .. THEN .. ELSE)

Given a variable age, if the value is greater than 42 display "You are old", otherwise display "You are young"
cpp
if (age > 42) Console::WriteLine("You are old");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 42 ? "old" : "young"));
std::printf("You are %s\n", (age > 42 ? "old" : "young"));

Perform different actions depending on several boolean conditions (IF .. THEN .. ELSIF .. ELSE)

cpp
if (age > 84) Console::WriteLine("You are really ancient");
else if (age > 30) Console::WriteLine("You are middle-aged");
else Console::WriteLine("You are young");
Console::WriteLine("You are {0}", (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young"));
std::cout << "You are " << (age > 84 ? "really ancient" : age > 30 ? "middle-aged" : "young") << std::endl;

Replacing a conditional with many branches with a switch/case statement

Many languages support more compact forms of branching than just if ... then ... else such as switch or case or match. Use such a form to add an appropriate placing suffix to the numbers 1..40, e.g. 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 39th, 40th
cpp
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,x;
cout<<"Enter the range:";
cin>>num;
for(i=1;i<=num;i++)
{
x=i%10;
switch(i)
{
case 11:
case 12:
case 13:cout<<i<<"th ";
continue;
}
switch(x)
{
case 1: cout<<i<<"st ";break;
case 2: cout<<i<<"nd ";break;
case 3: cout<<i<<"rd ";break;
default: cout<<i<<"th ";
}
}
getch();
}

Perform an action multiple times based on a boolean condition, checked before the first action (WHILE .. DO)

Starting with a variable x=1, Print the sequence "1,2,4,8,16,32,64,128," by doubling x and checking that x is less than 150.
cpp
int x = 1;

while (x < 150) { x *= 2; Console::Write("{0},", x); }
Console::WriteLine();
for (int x = 1; x < 150; x *= 2) { std::cout << x << ","; }
std::cout << std::endl;

Perform an action multiple times based on a boolean condition, checked after the first action (DO .. WHILE)

Simulate rolling a die until you get a six. Produce random numbers, printing them until a six is rolled. An example output might be "4,2,1,2,6"
cpp
Random^ rnd = gcnew Random;

int dice = rnd->Next(1, 7); Console::Write("{0}", dice);
do { Console::Write(",{0}", (dice = rnd->Next(1, 7))); } while (dice != 6);
Console::WriteLine();

Perform an action a fixed number of times (FOR)

Display the string "Hello" five times like "HelloHelloHelloHelloHello"
cpp
for(int i = 0; i < 5; ++i) Console::Write("Hello");
for(int i = 5; i > 0; --i) Console::Write("Hello");
dotimes(5, hello);
fill_n(ostream_iterator<string>(cout), 5, "Hello");

Perform an action a fixed number of times with a counter

Display the string "10 .. 9 .. 8 .. 7 .. 6 .. 5 .. 4 .. 3 .. 2 .. 1 .. Liftoff!"
cpp
for(int i = 10; i != 0; --i) Console::Write("{0} .. ", i);
Console::WriteLine("Liftoff!");

Read the contents of a file into a string

cpp
IO::FileStream^ file; String^ buffer;

try
{
file = gcnew IO::FileStream("test.txt", IO::FileMode::Open);
buffer = gcnew String((gcnew IO::BinaryReader(file))->ReadChars(file->Length));
}
IO::StreamReader^ stream; String^ buffer;

try
{
stream = gcnew IO::StreamReader("test.txt");
buffer = stream->ReadToEnd();
}
String^ buffer = IO::File::ReadAllText("test.txt");

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
cpp
IO::StreamReader^ stream; String^ ln; int i = 0;

try
{
stream = gcnew IO::StreamReader("test.txt");
while ((ln = stream->ReadLine())) Console::WriteLine("{0}> {1}", ++i, ln);
}
int i = 0;
for each(String^ line in IO::File::ReadAllLines("test.txt")) Console::WriteLine("{0}> {1}", ++i, line);

Write a string to a file

cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", false);
stream->WriteLine("This line overwites file contents!");
}

Append to a file

cpp
IO::StreamWriter^ stream;

try
{
stream = gcnew IO::StreamWriter("test.txt", true);
stream->WriteLine("This line appended to file!");
}

Process each file in a directory

cpp
for each(String^ filename in IO::Directory::GetFiles(dirname)) process(filename);

Process each file in a directory recursively

cpp
void processFile(String^ filename) { Console::WriteLine("{0}", filename); }

void processDirectory(String^ dirname)
{
for each(String^ filename in IO::Directory::GetFiles(dirname)) processFile(filename);
for each(String^ subdirname in IO::Directory::GetDirectories(dirname)) processDirectory(subdirname);
}

int main()
{
processDirectory("c:\\");
}

Parse a date and time from a string

Given the string "2008-05-06 13:29", parse it as a date representing 6th March, 2008 1:29:00pm in the local time zone.
cpp
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Use format specifiers to appropriately format string
// 1. Default culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"));

// 2. Nominated culture
Console::WriteLine("{0}", dateTime->ToString("d MMMM, yyyy h:mm:sstt"), Globalization::CultureInfo::CreateSpecificCulture("en-us"));
DateTimeOffset^ dateTime = DateTimeOffset::Parse("2008-05-06 13:29");

// Customize date/time string
Text::StringBuilder^ dsb = gcnew Text::StringBuilder(40);
dsb->Append(dateTime->ToString("%d"))->Append("th ")->Append(dateTime->ToString("MMMM, yyyy h:mm:ss"))->Append(dateTime->ToString("tt")->ToLower());

Console::WriteLine("{0}", dsb);

Display information about a date

Display the day of month, day of year, month name and day name of the day 8 days from now.
cpp
QDate dateEightDaysFromNow = QDate::currentDate().addDays(8);

Display a date in different locales

Display a language/locale friendly version of New Year's Day for 2009 for several languages/locales. E.g. for languages English, French, German, Italian, Dutch the output might be something like:

Thursday, January 1, 2009
jeudi 1 janvier 2009
giovedì 1 gennaio 2009
Donnerstag, 1. Januar 2009
donderdag 1 januari 2009

(Indicate in comments where possible if any language specific or operating system configuration needs to be in place.)
cpp
QList<QLocale::Language> locales;
locales << QLocale::English
<< QLocale::French
<< QLocale::German
<< QLocale::Italian
<< QLocale::Dutch;

QDate date(2009, 1, 1);
foreach (QLocale::Language ll, locales)
{
QLocale::setDefault(ll);
qDebug() << date.toString(Qt::DefaultLocaleLongDate);
}

Display the current date and time

Create a Date object representing the current date and time. Print it out.
If you can also do this without creating a Date object you can show that too.
cpp
QDate now = QDate::currentData();
qDebug() << now.toString();
time_t date = time(0);
cout << ctime(&date);
OOP

Define a class

Declare a class named Greeter that takes a string on creation and greets using this string if you call the "greet" method.
cpp
class Greeter
{
public:
Greeter(const std::string& whom);
void greet() const;

private:
std::string whom;
};

int main()
{
Greeter* gp = new Greeter("world");
gp->greet();
delete gp;
}

Greeter::Greeter(const std::string& whom) : whom(whom) {}

void Greeter::greet() const
{
std::cout << "Hello, " << whom << std::endl;
}
public ref class Greeter
{
public:
Greeter(String^ whom);
void greet();

private:
initonly String^ whom;
};

int main()
{
(gcnew Greeter(L"world"))->greet();
}

Greeter::Greeter(String^ whom) : whom(whom) {}

void Greeter::greet()
{
Console::WriteLine(L"Hello, {0}", whom);
}

Instantiate object with mutable state

Reimplement the Greeter class so that the 'whom' property or data member remains private but is mutable, and is provided with getter and setter methods. Invoke the setter to change the greetee, invoke 'greet', then use the getter in displaying the line, "I have just greeted {whom}.".

For example, if the greetee is changed to 'Tommy' using the setter, the 'greet' method would display:

Hello, Tommy!

The getter would then be used to display the line:

I have just greeted Tommy.
cpp
#include <iostream>

using namespace std;

class Greeter {
string whom_;

public:
Greeter(const string &whom) : whom_(whom) {}

string get_whom() const {
return whom_;
}

void set_whom(const string &whom) {
whom_ = whom;
}

void greet() const {
cout << "Hello " << whom_ << "!" << endl;
}
};

int main()
{
Greeter greeter("world");
greeter.greet();
greeter.set_whom("Tommy");
greeter.greet();
cout << "I have just greeted " + greeter.get_whom() << "." << endl;
}

Implement Inheritance Heirarchy

Implement a Shape abstract class which will form the base of an inheritance hierarchy that models 2D geometric shapes. It will have:

* A non-mutable 'name' property or data member set by derived or descendant classes at construction time
* A 'area' method intended to be overridden by derived or descendant classes ( double precision floating point return value)
* A 'print' method (also for overriding) will display the shape's name, area, and all shape-specific values

Two derived or descendant classes will be created:
* Circle    -> Constructor requires a '
radius' argument, and a 'circumference' method to be implemented  
* Rectangle -> Constructor requires '
length' and 'breadth' arguments, and a 'perimeter' method to be implemented 

Instantiate an object of each class, and invoke each objects '
print' method to show relevant details.
cpp
#include <string>
#include <iostream>

using namespace std;

static const double PI = 3.141592;

class Shape {
protected:
string name_;
public:
Shape(const string& name) : name_(name) { }
virtual double area() const = 0;
virtual void print() const = 0;
};

class Circle : public Shape {
double radius_;
public:
Circle(double radius) : Shape("circle"), radius_(radius) { }
double area() const {
return PI * radius_ * radius_;
}
void print() const {
cout << "A " << name_ << " with radius " << radius_ << ", area "
<< area() << " and circumference " << circumference() << "."
<< endl;
}
double circumference() const {
return 2 * PI * radius_;
}
};

class Rectangle : public Shape {
double length_;
double breadth_;
public:
Rectangle(double length, double breadth) :
Shape("rectangle"), length_(length), breadth_(breadth) { }
double area() const {
return length_ * breadth_;
}
void print() const {
cout << "A " << name_ << " with length " << length_ << ", breadth "
<< breadth_ << ", area " << area() << " and perimeter "
<< perimeter() << "." << endl;
}
double perimeter() const {
return 2 * length_ + 2 * breadth_;
}
};

int main(int argc, char *argv[])
{
Circle circle(4);
circle.print();
Rectangle rectangle(2, 5.5);
rectangle.print();
}

Implement and use an Interface

Create a Serializable interface consisting of 'save' and 'restore' methods, each of which:

* Accept a stream or handle or descriptor argument for the source or destination
* Save to destination or restore from source the properties or data members of the implementing class (restrict yourself to the primitive types 'int' and 'string')

Next, create a Person class which has 'name' and 'age' properties or data members and implements this interface. Instantiate a Person object, save it to a serial stream, and instantiate a new Person object by restoring it from the serial stream.
cpp
struct person
{
person(){}
person(const string &name, int age) : name_(name), age_(age) {}

string name_;
int age_;

template<typename Archive>
void serialize(Archive &ar, const unsigned int version) {
ar & name_ & age_;
}
};


int main()
{
const char *fn = "filename.txt";

person k("Ken", 38);
{
ofstream ofs(fn);
archive::text_oarchive oa(ofs);
oa << k;
}

person restored_person;
{
ifstream ifs(fn);
archive::text_iarchive ia(ifs);
ia >> restored_person;
}

cout << "Name : " << restored_person.name_ << endl
<< "Age : " << restored_person.age_ << endl;
}

Check your language appears on the langref.org site

Your language name should appear within the HTML found at the http://langreg.org main page.
cpp
HttpWebRequest^ httpReq = safe_cast<HttpWebRequest^>(WebRequest::Create(url)); httpReq->KeepAlive = false;
StreamReader^ httpStream = gcnew StreamReader(httpReq->GetResponse()->GetResponseStream());
String^ htmlPage = httpStream->ReadToEnd(); httpStream->Close();

Console::WriteLine("{0} {1} {2}", url, (htmlPage->IndexOf(url + language) > 0 ? "offers" : "does not offer"), language);
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
cpp
char input[] =
"<shopping>"
" <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>"
" <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>"
"</shopping>";

xml_document<> doc;
doc.parse<0>(input);
xml_node<> *shopping = doc.first_node();

float total_price = 0;
for (xml_node<> *item = shopping->first_node(); item != NULL; item = item->next_sibling())
{
float item_sum = 0;
float val;

if (string(item->name()) != "item")
continue;

for (xml_attribute<> *attr = item->first_attribute(); attr != NULL; attr = attr->next_attribute())
{
string name(attr->name());
if (name == "quantity" || name == "price")
{
stringstream v(attr->value());
v >> val;
if (item_sum)
item_sum *= val;
else
item_sum = val;
}
}
total_price += item_sum;
}

cout.setf(ios::fixed, ios::floatfield);
cout << "Total price is $" << setprecision(2) << total_price << endl;

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
cpp
string input("bread,3,2.50\nmilk,2,3.50\n");

tokenizer<char_separator<char> > tokens(input, char_separator<char>(", \n"));
tokenizer<char_separator<char> >::iterator it = tokens.begin();

xml_document<> doc;
xml_node<> *shopping = doc.allocate_node(node_element, "shopping");
doc.append_node(shopping);

while (it != tokens.end()) {
xml_node<> *item = doc.allocate_node(node_element, "item");
shopping->append_node(item);

item->append_attribute(doc.allocate_attribute("name", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("quantity", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("price", doc.allocate_string((*it++).c_str())));
}

cout << doc << endl;

Find all Pythagorean triangles with length or height less than or equal to 20

Pythagorean triangles are right angle triangles whose sides comply with the following equation:

a * a + b * b = c * c

where c represents the length of the hypotenuse, and a and b represent the lengths of the other two sides. Find all such triangles where a, b and c are non-zero integers with a and b less than or equal to 20. Sort your results by the size of the hypotenuse. The expected answer is:

[3, 4, 5]
[6, 8, 10]
[5, 12, 13]
[9, 12, 15]
[8, 15, 17]
[12, 16, 20]
[15, 20, 25]
cpp
vector<solution> solutions;

for (int a = 1; a <= 20; ++a)
for (int b = a + 1; b <= 20; ++b)
{
int c_squared = a*a + b*b;
int c = b + 1;
while (c * c < c_squared)
++c;
if (c * c == c_squared)
solutions.push_back(make_tuple(a, b, c));
}

sort(begin(solutions), end(solutions),
[](const solution& s1, const solution& s2) { return get<2>(s1) < get<2>(s2); });

for (const auto &s: solutions)
cout << '[' << get<0>(s) << ", " << get<1>(s) << ", " << get<2>(s) << ']' << endl;

Greatest Common Divisor

Find the largest positive integer that divides two given numbers without a remainder. For example, the GCD of 8 and 12 is 4.

cpp
#include <iostream>
#include <cstdlib>
#include <algorithm>

using namespace std;

int gcd_recursive(int i, int j) {
if (min(i, j) == 0)
return max(i, j);
else
return gcd_recursive(min(i, j), abs(i - j));
}

int gcd_recursive2(int x, int y) {
if (y == 0)
return x;
else
return gcd_recursive2(y, (x % y));
}

int gcd_iterative(int i, int j) {
while (min(i, j) != 0) {
i = min(i, j);
j = abs(i - j);
}
return max(i, j);
}

int main() {
std::cout << gcd_recursive(8, 12) << std::endl;
std::cout << gcd_recursive2(8, 12) << std::endl;
std::cout << gcd_iterative(8, 12) << std::endl;
return 0;
}
Fun

produces a copy of its own source code

In computing, a quine is a computer program which produces a copy of its own source code as its only output.
cpp
#include <cstdio>
#define B(x) x; printf("{ B(" #x ") }\n");
int main()
{ B(printf("#include <cstdio>\n#define B(x) x; printf(\"{ B(\" #x \") }\\n\");\nint main()\n")) }

Subdivide A Problem To A Pool Of Workers (No Shared Data)

Take a hard to compute problem and split it up between multiple worker threads. In your solution, try to fully utilize available cores or processors. (I'm looking at you, Python!)

Note: In this question, there should be no need for shared state between worker threads while the problem is being solved. Only after every thread completes computation are the answers recombined into a single output.

Example:

-Input-

(In python syntax)

["ab", "we", "tfe", "aoj"]

In other words, a list of random strings.

-Output-

(In python syntax)

[ ["ab", "ba", "aa", "bb", "a", "b"], ["we", "ew", "ww", "ee", "w", "e"], ...

In other words, all possible permutations of each input string are computed.
cpp
vector<string> input;
input.push_back("ab");
input.push_back("we");
input.push_back("tfe");
input.push_back("aoj");

// Make the capacity for 'output' the same as 'input'
vector<set<string> > output(input.size());
#pragma omp parallel for
for (int i = 0; i < input.size(); ++i) {
set<string> perms;
generate_perms(input[i], perms);
#pragma omp critical
// Must use operator[]() and not push_back() since this line
// might be called in any order with respect to 'i'
output[i] = perms;
}

cout << output << endl;

Create a multithreaded "Hello World"

Create a program which outputs the string "Hello World" to the console, multiple times, using separate threads or processes.

Example:

-Output-

Thread one says Hello World!
Thread two says Hello World!
Thread four says Hello World!
Thread three says Hello World!

-Notice that the threads can print in any order.
cpp
#include <iostream>
#include <string>

using namespace std;

int main(){
int pid;
string text[4]={"one","two","three","four"};
for (int i=0;i<4;i++){
pid=fork();
if (pid>0){
//cout << "Process("<<pid<<") - " << "Thread " << text[i] << " says Hello World!" << endl;
cout << "Thread " << text[i] << " says Hello World!" << endl;
exit(0);
}
}
return 0;
}
#include <iostream>
#include <string>

#include <omp.h>

int main() {
unsigned int const num_threads = 4;

std::string const names[] = { "one", "two", "three", "four" };

# pragma omp parallel num_threads(num_threads)
{
unsigned const id = omp_get_thread_num();
// Stream concatenation isn't thread-safe so we use a critical section.
# pragma omp critical
std::cout << "Thread " << names[id] << " says Hello World!" << std::endl;
}
}

Create read/write lock on a shared resource.

Create multiple threads or processes who are either readers or writers. There should be more readers then writers.

(From Wikipedia):

Multiple readers can read the data in parallel but an exclusive lock is needed while writing the data. When a writer is writing the data, readers will be blocked until the writer is finished writing.

Example:

-Output-

Thread one says that the value is 8.
Thread three says that the value is 8.
Thread two is taking the lock.
Thread four tried to read the value, but could not.
Thread five tried to write to the value, but could not.
Thread two is changing the value to 9.
Thread two is releasing the lock.
Thread four says that the value is 9.
...

--Notice that when a needed resource is locked, a thread can set a timer and try again in the future, or wait to be notified that the resource is no longer locked.
cpp
class reader
{
string name_;
public:
reader(const string& name) : name_(name) {}

void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
shared_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
cout << " says that the value is " << shared_value << "." << endl;
else
cout << " tried to read the value, but could not." << endl;
}
}
};

class writer
{
string name_;
public:
writer(const string& name) : name_(name) {}
void operator()() {
for (;;this_thread::sleep(posix_time::milliseconds(1)))
{
unique_lock<shared_mutex> lock(m, try_to_lock);
lock_guard<mutex> cout_lock(io_m);
cout << "Thread " << name_;
if (lock)
{
cout << " is taking the lock." << endl;
shared_value = rand() % 10;
cout << "Thread " << name_ << " is changing the value to " << shared_value << endl;
cout << "Thread " << name_ << " is releasing the lock. " << endl;
}
else
cout << " tried to write to the value, but could not." << endl;
}
}
};

int main()
{
thread t1 = thread(reader("one"));
thread t2 = thread(reader("two"));
thread t3 = thread(reader("three"));
thread t4 = thread(writer("four"));
writer("five")();
}

Separate user interaction and computation.

Allow your program to accept user interaction while conducting a long running computation.

Example:

Hello user! Please input a string to permute: (input thread)
abcdef
Passing on abcdef... (input thread)
Please input another string to permute: (input thread)
lol
Passing on lol... (input thread)
Done Work On abcdef! (worker thread)
["abcdef", "abcefd", ... ] (worker thread)
Please input another string to permute: (input thread)
EXIT
Quitting, I'll let my worker thread know... (input thread)
We'
re quitting! Alright! (worker thread)

--Notice, that this could be accomplished on the command line or within a GUI. The point is that computation and user interaction should take place on separate threads of control.
cpp
class bg_worker
{
mutex bg_mutex_;
condition_variable work_present_;
deque<string> work_queue_;

result calc_perm(string s) {
result perms = result(new list<string>());

// sleep to simulate lots of work...
this_thread::sleep(posix_time::seconds(3));
sort(s.begin(), s.end());
do {
perms->push_back(s);
} while (next_permutation(s.begin(), s.end()));
return perms;
}

public:
void submit_work(const string &s) {
lock_guard<mutex> lock(bg_mutex_);
work_queue_.push_back(s);
work_present_.notify_one();
}

void operator()() {
for (;;) {
unique_lock<mutex> lock(bg_mutex_);
while (work_queue_.empty())
work_present_.wait(lock);
string s = work_queue_.front();
work_queue_.pop_front();
lock.unlock();

if (s == "EXIT") {
lock_guard<mutex> cout_lock(cout_mutex);
cout << "We're quitting! Alright!" << endl;
break;
}

result perm = calc_perm(s);
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Done Work On " << s << "!" << endl;
cout << perm << endl;
}
}
};

int main()
{
bg_worker worker;
thread bg_thr(boost::ref(worker));
bool done = false;

{
lock_guard<mutex> cout_lock(cout_mutex);
cout << "Hello user! Please input a string to permute:" << endl;
}

while (!done)
{
string input;
cin >> input;
{
lock_guard<mutex> cout_lock(cout_mutex);
if (input == "EXIT") {
cout << "Quitting, I'll let my worker thread know..." << endl;
done = true;
} else {
cout << "Passing on " << input << "..." << endl;
cout << "Please input another string to permute:" << endl;
}
}
worker.submit_work(input);
}

bg_thr.join();
}