Skip to content

Instantly share code, notes, and snippets.

@sturmer
Created December 11, 2013 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmer/7915819 to your computer and use it in GitHub Desktop.
Save sturmer/7915819 to your computer and use it in GitHub Desktop.
Functors versus lambdas
#include "task.hpp"
#include <iostream>
#include <queue>
#include <vector>
#include <string>
using std::priority_queue;
using std::ostream;
using std::cout;
using std::string;
using std::less;
using std::vector;
int main()
{
Task task1(1, "Laundry");
Task task2(3, "Hackery");
Task task3(2, "Grocery");
priority_queue<Task, vector<Task>, less<Task>> q;
q.push(task1);
q.push(task2);
q.push(task3);
while (!q.empty()) {
cout << q.top() << '\n';
q.pop();
}
}
#include <iostream>
#include <queue>
#include <vector>
#include <string>
using std::priority_queue;
using std::ostream;
using std::cout;
using std::string;
using std::less;
using std::vector;
struct Task {
int priority_;
string description_;
Task(int p, string d) : priority_(p), description_(d) {}
};
ostream& operator<<(ostream& os, const Task& t)
{
os << t.priority_ << ": " << t.description_;
return os;
}
int main()
{
Task task1(1, "Laundry");
Task task2(3, "Hackery");
Task task3(2, "Grocery");
auto compare_tasks = [](const Task& t1, const Task& t2) { return t1.priority_ < t2.priority_; };
priority_queue<Task, vector<Task>, decltype(compare_tasks)> q(compare_tasks);
q.push(task1);
q.push(task2);
q.push(task3);
while (!q.empty()) {
cout << q.top() << '\n';
q.pop();
}
}
# Yeah, I am bad at writing Makefiles on the fly :(
all: example_functors.cpp example_lambdas.cpp
g++ -std=c++0x -g -Wall -Werror example_functors.cpp -o ef
g++ -std=c++0x -g -Wall -Werror example_lambdas.cpp -o el
#ifndef TASK_HPP
#define TASK_HPP
#include <iostream>
#include <string>
using std::ostream;
using std::string;
// example with prio_queues, then example with sort of vector
struct Task {
int priority_;
string description_;
Task(int p, string d) : priority_(p), description_(d) {}
};
namespace std {
template<>
struct less<Task> {
bool operator()(const Task& t1, const Task& t2)
{
return t1.priority_ < t2.priority_;
}
};
}
ostream& operator<<(ostream& os, const Task& t)
{
os << t.priority_ << ": " << t.description_;
return os;
}
#endif // TASK_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment