Skip to content

Instantly share code, notes, and snippets.

@stungeye
Created January 27, 2022 21:32
Show Gist options
  • Save stungeye/fec7ca4c3f1c199288aedfc6376ca784 to your computer and use it in GitHub Desktop.
Save stungeye/fec7ca4c3f1c199288aedfc6376ca784 to your computer and use it in GitHub Desktop.
Lambdas in C++
#include <iostream> // std::cout
#include <string> // std::string
#include <vector> // std::vector
#include <algorithm> // std::count_if, std::adjacent_find, std::sort
#include <numeric> // std::accumulate
#include <functional> // std::function
#include <array> // std::array
void printIt(const std::function<int(const std::string& word)>& fnc, const std::string& word) {
std::cout << fnc(word) << "\n";
}
int main() {
printIt([](const std::string& word)-> int { return word.length(); },
"Hello Class!!!!");
std::vector<std::string> words{
"the", "origin", "of", "consciousness", "in", "the", "breakdown", "of", "the", "bicameral", "mind"
};
int longWordLength;
std::cout << "Define the length of a 'long word': ";
std::cin >> longWordLength;
// Count the number of words with a length greater than 8.
const int longWordCount = std::count_if(words.begin(), words.end(),
[=](const std::string& word)-> bool {
return word.length() >= longWordLength;
});
std::cout << "There are " << longWordCount << " words greater or equal in length to " << longWordLength <<
" characters.\n";
// Find the sum of the lengths of the words.
const double sumOfLengths = std::accumulate(words.begin(),
words.end(),
0,
[](const double sum, const std::string& word)-> double {
return sum + word.length();
});
std::cout << "The sum of the lengths of the words is: " << sumOfLengths << "\n";
// Calculate the average length of the words. (sum / # of words)
std::cout << "The average length of our words is: " << (sumOfLengths / words.size()) << "\n";
std::array<std::string, 12> months{
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"
};
// Find the first two consecutive months that start with the same letter.
const auto sameLetter{
std::adjacent_find(months.begin(), months.end(),
[](const auto& a, const auto& b) { return a.size() == b.size(); }
)
};
if (sameLetter == months.end()) {
std::cout << "Sorry, nothing found.";
} else {
std::cout << *sameLetter << " and " << *std::next(sameLetter)
<< " have the same length.\n";
}
std::array numbers{
9, 99, 4, 44, 300, 3, 12, 2, 200,
3, 23, 1, 2983, 23, 123, 23, 19282, 45
};
int numberOfComparisons = 0;
std::sort(numbers.begin(), numbers.end(),
[&](auto a, auto b) {
numberOfComparisons++;
return a > b;
}
);
std::cout << "The sort required " << numberOfComparisons << " comparisons.\n";
for (const auto number : numbers) {
std::cout << number << " ";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment