Last active
November 3, 2022 19:42
-
-
Save mshafae/36392c28705f3b62dda5d99d1db340b3 to your computer and use it in GitHub Desktop.
CPSC 120 Demonstrate the use of iterators and a few algorithms from the C++ standard library.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Gist https://gist.github.com/36392c28705f3b62dda5d99d1db340b3 | |
#include <algorithm> | |
#include <iostream> | |
#include <iterator> | |
#include <string> | |
#include <vector> | |
int main(int argc, char const *argv[]) { | |
std::vector<int> my_vector{10, 11, 12, 13}; | |
std::cout << "Traditional counter based for loop\n"; | |
// https://en.cppreference.com/w/cpp/language/for | |
for (int index = 0; index < my_vector.size(); index++) { | |
std::cout << my_vector.at(index) << "\n"; | |
} | |
std::cout << "Range-based for loop\n"; | |
// https://en.cppreference.com/w/cpp/language/range-for | |
for (int element : my_vector) { | |
std::cout << element << "\n"; | |
} | |
std::cout << "Traditional for loop using an iterator\n"; | |
// https://en.cppreference.com/w/cpp/language/for | |
for (std::vector<int>::iterator my_iterator = my_vector.begin(); | |
my_iterator != my_vector.end(); my_iterator++) { | |
std::cout << *my_iterator << "\n"; | |
} | |
// Using the algorithms in the standard library | |
// This is a lambda to help with printing out the values in the array | |
auto print = [](int number) { std::cout << number << "\n"; }; | |
std::cout << "Using the for_each algorithm\n"; | |
// https://en.cppreference.com/w/cpp/algorithm/for_each | |
std::for_each(my_vector.begin(), my_vector.end(), print); | |
std::cout << "Using the copy algorithm\n"; | |
// https://en.cppreference.com/w/cpp/algorithm/copy | |
std::copy(my_vector.begin(), my_vector.end(), | |
std::ostream_iterator<int>(std::cout, "\n")); | |
// What's the longest word you can think of? | |
std::string word{"counterrevolutionaries"}; | |
// Strings are sequences too, just like arrays and vectors. | |
// Let's use a reverse iterator | |
// https://en.cppreference.com/w/cpp/string/basic_string | |
for (std::string::reverse_iterator string_iterator = word.rbegin(); | |
string_iterator != word.rend(); string_iterator++) { | |
std::cout << *string_iterator << " "; | |
} | |
std::cout << "\n"; | |
std::string reverse_word{word.rbegin(), word.rend()}; | |
std::cout << reverse_word << "\n"; | |
// Let's print that out with some extra spaces | |
std::copy(reverse_word.begin(), reverse_word.end(), | |
std::ostream_iterator<char>(std::cout, " ")); | |
std::cout << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment