Skip to content

Instantly share code, notes, and snippets.

@mrts
Created November 8, 2012 20:37
Show Gist options
  • Save mrts/4041421 to your computer and use it in GitHub Desktop.
Save mrts/4041421 to your computer and use it in GitHub Desktop.
copy_if in C++03 and C++11
#include <algorithm>
#include <vector>
#include <iostream>
// for C++03
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
using namespace std;
bool is_divisble_by(int divisor, int item)
{
return item % divisor == 0;
}
void cpp_03()
{
vector<int> items;
for (int i = 1; i < 5; i++)
items.push_back(i);
vector<int> filtered_items;
remove_copy_if(items.begin(), items.end(),
back_inserter(filtered_items),
boost::bind(is_divisble_by, 2, _1) == false);
foreach (int item, filtered_items)
cout << item << " ";
cout << endl;
}
void cpp_11()
{
vector<int> items = { 1, 2, 3, 4 };
vector<int> filtered_items;
copy_if(begin(items), end(items),
back_inserter(filtered_items),
[](const int item) { return item % 2 == 0; });
for (auto item : filtered_items)
cout << item << " ";
cout << endl;
}
int main()
{
cpp_03();
cpp_11();
return 0;
}
@mrts
Copy link
Author

mrts commented Nov 8, 2012

NAME     = main

TARGET   = $(NAME)

EXTRA    = -O2 -I/usr/include/clang/3.0/include -std=c++11
COMPILER = clang++-3.1

CXX      = $(COMPILER)
CXXFLAGS = -pipe $(EXTRA) -Wall -Wextra -Werror

LINK     = $(COMPILER)
LFLAGS   = -Wl,-O2

# Generic source file lists

SRC      = $(wildcard *.cpp)
OBJS     = $(patsubst %.cpp, %.o, $(SRC))

# Targets

%.o: %.cpp
    $(CXX) -c $(CXXFLAGS) $(INCPATH) -o $@ $<

$(TARGET): $(OBJS)
    $(LINK) $(LFLAGS) -o $@ $(OBJS)

run: $(TARGET)
    ./$(TARGET)

dbg: $(TARGET)
    cgdb ./$(TARGET)

clean:
    rm -f $(OBJS) $(TARGET)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment