#include <iostream> #include <cstring> // C std string ops #include <algorithm> // STL algorithms, find ... int main() { char* s = "C++ is the better C"; int len = strlen(s); char * where = find(&s[0],&s[len],'e'); cout << *(where) << *(where+1) << endl; };
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cstring> using namespace std; int main() { const char* s = "C++ is the better C"; int len = strlen(s); vector<char> vec1(&s[0],&s[len]); // vector of chars created and filled cout << vec1.size() << endl; sort( vec1.begin(), vec1.end() ); cout << vec1.data() << endl; // .data() returns char array }
Viele Varianten:
#include <numeric> ... int* ia = { 1, 4, 9, 16, 25 }; vector<int> vi(ia, ia+5); // vector mit ints int sum = accumulate( vi.begin(), vi.end() , 0); ...
reverse : Reihenfolge umdrehen
#include <numeric> ... vector<char> vec1(&s[0],&s[len]); // vector mit chars reverse( vec1.begin(), vec1.end() ); ...
random_shuffle : in zufällige Reihenfolge bringen
#include <numeric> ... int* ia = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } vector<int> vi(ia, ia+5); // vector mit ints random_shuffle( vi.begin(), vi.end() ); // in zufaellige Reihenfolge bringen ...
#include <list> #include <vector> #include <algorithm> #include <iterator> ... vector<char> vec1(&s[0],&s[len]); // vector mit chars list<char> list1; // liste mit chars copy( vec1.begin(), vec1.end(), back_inserter(list1) )); ...
back_inserter() ist template-iterator function analog zu push_back()
istream_iterator<double> inp(cin); istream_iterator<double> eof; vector<double> vec2; copy( inp, eof, back_inserter(vec2) );
Liest Daten von Standard-Eingabe und packt sie in Vektor (beliebig viele, bis zum end-of-file)
analog die Ausgabe
#include <vector> #include <iterator> ostream_iterator<double> out(cout, "\n" ); copy( vec2.begin(), vec2.end(), out );
// partition algorithm example // from http://www.cplusplus.com // #include <iostream> // std::cout #include <algorithm> // std::partition #include <vector> // std::vector #include <iterator> using namespace std; bool IsOdd (int i) { return (i%2)==1; } int main () { vector<int> vec; // set some values: for (int i=1; i<10; ++i) vec.push_back(i); // 1 2 3 4 5 6 7 8 9 vector<int>::iterator bound; bound = partition (vec.begin(), vec.end(), IsOdd); //bound = stable_partition (vec.begin(), vec.end(), IsOdd); // print out content: cout << "odd elements:"; ostream_iterator<int> out(cout, " " ); copy( vec.begin(), bound, out ); cout << endl; cout << "even elements:"; copy( bound, vec.end(), out ); cout << endl; return 0; }
Variante stable_partition : Ändert nicht die bisherige Reihenfolge.
siehe
CppReference
oder
105 STL algorithms ...
Wann immer möglich STL-Algorithmen verwenden statt eigene Schleifen zu programmieren
higher level of abstraction
GDuckeck 2019-08-01