#include <iostream> #include <vector> #include <map> #include <algorithm> #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) struct SomeItem { SomeItem(int i, int b) : id(i), played(b) { } bool IsNotPlayed() { return !played; } void Print() { std::cout << "id: " << id << ", is played: " << played << std::endl; } int id; bool played; }; int main(int argc, char *argv[]) { std::vector<SomeItem> items; for (size_t i = 0; i < 10; ++i) { SomeItem item(i, i == 7 || i == 8 ? true : false); items.push_back(item); } std::vector<SomeItem> playedItems; // 由于C++之父在gcc3.4.4在实现STL时, 遗漏了copy_if, 在他的书The C++ Programming Language勘误表中有说明 // 在gcc4.8.1中已经支持了C++11, 也添加了copy_if算法, 如果你使用的不是gcc的最新版本4.8.1, 只能使用另一个相反的算法remove_copy_if std::cout << GCC_VERSION << std::endl; #if GCC_VERSION >= 40801 std::copy_if(items.begin(), items.end(), std::back_inserter(playedItems), std::mem_fun_ref(&SomeItem::IsPlayed)); #else std::remove_copy_if(items.begin(), items.end(), std::back_inserter(playedItems), std::mem_fun_ref(&SomeItem::IsNotPlayed)); #endif std::for_each(playedItems.begin(), playedItems.end(), std::mem_fun_ref(&SomeItem::Print)); // 另外gcc中使用map嵌套要注意, 右尖括号要带个空格才能正常识别, 不然会被认为是流输入操作符 //std::map<int, std::vector<int>> someMap; // 编译错误 std::map<int, std::vector<int> > someMap; // 编译通过 std::cin.get(); return 0; }
以上代码在gcc4.5.3上编译通过
g++ test.cpp -o test.exe