Skip to content

Instantly share code, notes, and snippets.

@adamcrussell adamcrussell/ch-1.cxx
Last active Nov 17, 2019

Embed
What would you like to do?
Perl Weekly Challenge 034
/**
* Write a program that demonstrates using hash slices and/or array slices.
**/
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
void print_element(std::string s){
if(s != "")
std::cout << s << std::endl;
}
int main(int argc, char** argv){
std::vector<int> v {2, 4};
std::map<int, std::string> mapExp = { {1, "first"}, {2, "second"}, {3, "third"}, {4,"fourth"} };
std::vector<std::string> vValue;
std::transform(mapExp.begin(), mapExp.end(), std::back_inserter(vValue),
[=](const std::pair<int, std::string> &mapItem){
std::vector<int>::const_iterator iter = std::find(v.begin(), v.end(), mapItem.first);
if(iter != v.end())
return mapItem.second;
return std::string("");
});
std::for_each(vValue.begin(), vValue.end(), print_element);
}
use strict;
use warnings;
##
# Write a program that demonstrates using hash slices and/or array slices.
##
my %h = (
1 => "first",
2 => "second",
3 => "third",
4 => "fourth"
);
my @a = @h{2, 4};
print join("\n", @a) . "\n";
/**
* Write a program that demonstrates a dispatch table.
**/
#include <map>
#include <string>
#include <iostream>
#include <functional>
int main(){
std::map< const std::string , std::function<void(void)> > dispTable{
{"hello",[](){ std::cout << "Hello!" << std::endl; } },
{"goodbye",[](){ std::cout << "Goodbye!" << std::endl; } }
};
dispTable["hello"]();
dispTable["goodbye"]();
};
use strict;
use warnings;
##
# Write a program that demonstrates a dispatch table.
##
my %dispatch_table = (
hello => sub { print "Hello!\n"; },
goodbye => sub { print "Goodbye!\n"; }
);
$dispatch_table{hello}();
$dispatch_table{goodbye}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.