Algoritmy “unique” a “reverse”
C++ 11

image_printTisk

Úvod

Algoritmus unique

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

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

int main() {
    vector<int> data = {0, 1, 1, 1, 1,  0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};
    print(data);
    auto it = unique(data.begin(), data. end());
    data.resize(distance(data.begin(), it));
    print(data);
    
}
Unable to connect to the JDoodle service.

Algoritmus unique_copy

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

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

int main() {
    vector<int> data = {0, 1, 1, 1, 1,  0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3};
    vector<int> data2;
    unique_copy(data.begin(), data. end(), back_inserter(data2));
    print(data);
    print(data2);
    
}
Unable to connect to the JDoodle service.

Algoritmus reverse

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

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

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

Algoritmus reverse_copy

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

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

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

Shrnutí

 

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

Související články