Algoritmy “transform” a “replace”
C++ 11

image_printTisk

Úvod

Algoritmus transform

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

template<typename C>
void print(C container, const char separator=';') {
    for(auto c : container)
        cout << c << separator;
    cout << endl;
}

int main() {
    auto generator = []() {
        static int val = 0;
        return ++val;
    };
    vector<int> data;
    generate_n(back_inserter(data), 10, generator);
    
    auto transformation = [](int item) {
        string s;
        fill_n(back_inserter(s), item, 'x');
        return s;
    };
    vector<string> transformedData;
    transform(data.begin(), data.end(), back_inserter(transformedData), transformation);
    
    print(data);
    print(transformedData, '\n');
    return 0;
}
Unable to connect to the JDoodle service.

Algoritmus replace

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s = "Hello, world !!!!";
    cout << s << endl;
    replace(s.begin(), s.end(), 'l', '_');
    cout << s << endl;
}
Unable to connect to the JDoodle service.

Algoritmus replace_if

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template<typename C>
void print(C c) {
    for(auto val : c)
        cout << val << ";";
    cout << endl;
}

int main() {
    vector<int> data;
    auto generator = []() {
        static int val = 0;
        return ++val;
    };
    generate_n(back_inserter(data), 20, generator);
    
    print(data);
    replace_if(data.begin(), data.end(), [](int item) { return item % 2 == 0; }, 0);
    print(data);
    return 0;
}
Unable to connect to the JDoodle service.

Algoritmus replace_copy

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    string s = "Hello, world !!!!";
    string s2;
    replace_copy(s.begin(), s.end(), back_inserter(s2), 'l', '_');
    cout << s << endl;
    cout << s2 << endl;
}
Unable to connect to the JDoodle service.

Algoritmus replace_copy_if

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template<typename C>
void print(C c) {
    for(auto val : c)
        cout << val << ";";
    cout << endl;
}

int main() {
    vector<int> data;
    auto generator = []() {
        static int val = 0;
        return ++val;
    };
    generate_n(back_inserter(data), 20, generator);
    
    vector<int> data2;
    replace_copy_if(data.begin(), data.end(), back_inserter(data2), 
        [](int item) { return item % 3 == 0; }, -1);
    print(data);
    print(data2);
    return 0;
}
Unable to connect to the JDoodle service.

Shrnutí

 

image_printTisk
Algoritmy “transform” a “replace”
C++ 11
Ohodnoťte tento článek

Související články