Skip to content

Instantly share code, notes, and snippets.

@nikanos
Last active November 29, 2022 17:14
Show Gist options
  • Save nikanos/f4bbac05074bed76ed6e89ec9816f3a2 to your computer and use it in GitHub Desktop.
Save nikanos/f4bbac05074bed76ed6e89ec9816f3a2 to your computer and use it in GitHub Desktop.
Add 10 to all input numbers using bind2nd, bind with placeholder (C++11) and generic lambda (C++14)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
ifstream inf("input.txt");
if (!inf.fail())
{
ofstream outf("out.txt");
if (!outf.fail())
{
istream_iterator<int> beg(inf), end;
ostream_iterator<int> oit(outf, "\n");
transform(beg, end, oit, bind(plus<int>(), atoi("10"), placeholders::_1));//using bind with placeholder (C++11)
}
else
{
cerr << "Error writing out.txt\n";
return EXIT_FAILURE;
}
}
else
{
cerr << "Error reading input\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
ifstream inf("input.txt");
if (!inf.fail())
{
ofstream outf("out.txt");
if (!outf.fail())
{
istream_iterator<int> beg(inf), end;
ostream_iterator<int> oit(outf, "\n");
transform(beg, end, oit, bind2nd(plus<int>(), atoi("10")));//using bind2nd
}
else
{
cerr << "Error writing out.txt\n";
return EXIT_FAILURE;
}
}
else
{
cerr << "Error reading input\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
ifstream inf("input.txt");
if (!inf.fail())
{
ofstream outf("out.txt");
if (!outf.fail())
{
istream_iterator<int> beg(inf), end;
ostream_iterator<int> oit(outf, "\n");
transform(beg, end, oit, [&](auto const& elem) { //using generic lambda (C++14)
return elem + 10;
});
}
else
{
cerr << "Error writing out.txt\n";
return EXIT_FAILURE;
}
}
else
{
cerr << "Error reading input\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment