é¢æ°ãªãã¸ã§ã¯ãã¯å¥¥ãæ·±ã
ã¯ããã¦ã®é¢æ°ãªãã¸ã§ã¯ãä½é¨ã
åãã
ããvectorã®è¦ç´ ã§ãä»ã®vectorä¸ã«ãå
¥ã£ã¦ãããã¤ãåãé¤ããã¨ãã¦æ¬¡ã®ãããªã³ã¼ããæ¸ãããã³ã³ãã¤ã«ã¨ã©ã¼ã«ãªãã¾ããã
#include <iostream> #include <vector> #include <algorithm> #include <functional> bool contains(const std::vector<int> v, int x){ return std::find(v.begin(), v.end(), x) != v.end(); } int main(){ std::vector<int> v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); v1.push_back(6); std::vector<int> v2; v2.push_back(3); v2.push_back(4); v2.push_back(6); v2.push_back(8); v2.push_back(9); // v1ã®è¦ç´ ã§ãv2ä¸ã«ããããã¤ãé¤å»ãã std::vector<int>::iterator newEnd = std::remove_if(v1.begin(), v1.end(), std::bind1st(contains, v2)); // ã³ã³ãã¤ã«ã¨ã©ã¼ v1.erase(newEnd, v1.end()); }
std::binary_functionãstd::ptr_fun
ééã£ã¦ããã®ã¯ãstd::bind1st ã®å¼æ°ã«æ¸¡ãé¢æ°ãªãã¸ã§ã¯ã㯠std::binary_function ãç¶æ¿ãã¦ããªãã¦ã¯ãªããªããããåç´ãªé¢æ°ãã¤ã³ã¿ãã®ã¾ã¾ã¯æ¸¡ããªããã¨ããã¨ããã
ãªãã¡ã¬ã³ã¹ï¼MSDN - ptr_fun
// v1ã®è¦ç´ ã§ãv2ä¸ã«ããããã¤ãé¤å»ãã std::vector<int>::iterator newEnd = std::remove_if(v1.begin(), v1.end(), std::bind1st(std::ptr_fun(contains), v2)); // OK v1.erase(newEnd, v1.end()); for(std::vector<int>::iterator itr = v1.begin(); itr != v1.end(); ++itr){ std::cout << *itr << " "; }
åºå:
1 2 5
ãã¤ãå¿ è¦ã¨ããããã§ã¯ãªã
ç´ããããã®ããstd::remove_if ã®ç¬¬3å¼æ°èªä½ã«ã¯åç´ãªé¢æ°ãã¤ã³ã¿ã渡ãããã¨ã
#include <iostream> #include <vector> #include <algorithm> #include <functional> bool even(int i){ return i % 2 == 0; } int main(){ std::vector<int> v1; v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); v1.push_back(6); // å¶æ°ã®ãã¤ã ãåãé¤ã std::vector<int>::iterator newEnd = std::remove_if(v1.begin(), v1.end(), even); // evenã¯ãã ã®é¢æ°ãã¤ã³ã¿ v1.erase(newEnd, v1.end()); for(std::vector<int>::iterator itr = v1.begin(); itr != v1.end(); ++itr){ std::cout << *itr << " "; } }
åºå:
1 3 5
é¢æ°ãªãã¸ã§ã¯ãã使ãã¨ãã¯ãããã¤ã std::binary_function ã std::unary_function ãç¶æ¿ãã¦ãªãã¨ãããªãã®ãããã ã®é¢æ°ãã¤ã³ã¿ã§ãããã®ãï¼ã¤ã¾ããoperator()ã§å¼ã³åºãããããã°ããã®ãï¼ãæ°ãã¤ãã¦è¦ã¨ããªãã¨ã¨ãããªãã®ã ãªã
ããããããã