STL中replace/replace_if例子

STL 算法示例

--------------------------------------------------------------------------------

replace/replace_if
#include 
#include 
#include 
//#include  // greater<>

using namespace std;

template
void printVector(char *s, const vector& v) {
    cout << s << " = (";
    if (v.size() == 0) {
        cout << ")\n";
        return;
    }
    typename vector::const_iterator i = v.begin();
    for ( ; i != v.end()-1; i++)
        cout << *i << ' ';
    cout << *i << ")\n";
}
// 条件函数
bool Condition(int n) {
    return n < 4;
}

int main() {
    vector v1;
    for (int j = 1; j <= 5; j++)
      v1.push_back(j);
    v1.push_back(1);
    printVector("v1",v1);
	// 直接替换
    replace(v1.begin(),v1.end(),1,7);
    printVector("v1",v1);
    // 符合条件函数则替换
    replace_if(v1.begin(),v1.end(),Condition,7);
    printVector("v1",v1);
  }

你可能感兴趣的:(c++/c,算法)