# utility

***

**1. Array Manipulation with std::iota**

```cpp
int arr[5];
iota(arr, arr + 5, 1); // Initialize array to [1, 2, 3, 4, 5]
```

**2. Find Minimum and Maximum Elements with std::min and std::max**

```cpp
int a = 10, b = 20, c = 30;
int min_val = min({a, b, c}); // min_val = 10
int max_val = max({a, b, c}); // max_val = 30
```

**3. Swap Values with std::swap**

```cpp
int a = 10, b = 20;
swap(a, b); // a = 20, b = 10
```

**4. Check if Two Values Are Equal with std::equal\_to**

```cpp
int a = 10, b = 10;
bool are_equal = std::equal_to<int>()(a, b); // are_equal = true
```

**5. Count Occurrences in a Container with std::count**

```cpp
vector<int> v = {1, 2, 3, 4, 1};
int num_of_ones = count(v.begin(), v.end(), 1); // num_of_ones = 2
```

**6. Reverse a Container with std::reverse**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
reverse(v.begin(), v.end()); // v = {5, 4, 3, 2, 1}
```

**7. Copy Elements from One Container to Another with std::copy**

```cpp
vector<int> src = {1, 2, 3, 4, 5};
vector<int> dest;
copy(src.begin(), src.end(), back_inserter(dest)); // dest = {1, 2, 3, 4, 5}
```

**8. Search for an Element in a Container with std::find**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
auto it = find(v.begin(), v.end(), 3); // it points to the element with value 3
```

**9. Insert an Element into a Sorted Container with std::insert**

```cpp
set<int> s = {1, 2, 4, 5};
s.insert(3); // s = {1, 2, 3, 4, 5} (inserted in sorted order)
```

**10. Create a Vector with a Range of Values with std::iota**

```cpp
vector<int> v(10);
iota(v.begin(), v.end(), 1); // v = {1, 2, 3, ..., 10}
```

**11. Sort a Container with std::sort**

```cpp
vector<int> v = {5, 2, 3, 4, 1};
sort(v.begin(), v.end()); // v = {1, 2, 3, 4, 5}
```

**12. Randomize a Container with std::shuffle**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
random_shuffle(v.begin(), v.end()); // v is shuffled randomly
```

**13. Create a Temporary Copy with std::make\_unique**

```cpp
unique_ptr<int> p = make_unique<int>(10); // p points to a temporary copy of 10
```

**14. Check if a Container Is Empty with std::empty**

```cpp
vector<int> v;
bool is_empty = v.empty(); // is_empty = true
```

**15. Clear a Container with std::clear**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
v.clear(); // v is empty now
```

**16. Remove an Element from a Container with std::erase**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
v.erase(v.begin() + 2); // removes the third element (element with value 3)
```

**17. Transform a Container with std::transform**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
transform(v.begin(), v.end(), v.begin(), [](int x) { return x * x; }); // v = {1, 4, 9, 16, 25}
```

**18. Reduce a Container with std::accumulate**

```cpp
vector<int> v = {1, 2, 3, 4, 5};
int sum = accumulate(v.begin(), v.end(), 0); // sum = 15
```

**19. Partition a Container with std::partition**

```cpp
vector<int> v = {1, 3, 2, 5, 4};
auto it = partition(v.begin(), v.end(), [](int x) { return x % 2 == 0; }); // it points to the first odd element
```

**20. Convert to Uppercase with std::toupper**

```cpp
string s = "hello";
transform(s.begin(), s.end(), s.begin(), [](char c) { return toupper(c); }); // s = "HELLO"
```

**21. Convert to Lowercase with std::tolower**

```cpp
string s = "HELLO";
transform(s.begin(), s.end(), s.begin(), [](char c) { return tolower(c); }); // s = "hello"
```

**22. Trim Whitespace with std::trim**

```cpp
string s = "  hello  ";
s = trim(s); // s = "hello"
```

**23. Split a String with std::split**

```cpp
string s = "a,b,c,d,e";
vector<string> parts = split(s, ','); // parts = {"a", "b", "c", "d", "e"}
```

**24. Join Container Elements into a String with std::join**

```cpp
vector<string> parts = {"a", "b", "c", "d", "e"};
string s = join(parts, ","); // s = "a,b,c,d,e"
```

**25. Check if a File Exists with std::filesystem::exists**

```cpp
namespace fs = std::filesystem;
bool file_exists = fs::exists("test.txt"); // file_exists = true/false
```

**26. Create a Directory with std::filesystem::create\_directory**

```cpp
namespace fs = std::filesystem;
fs::create_directory("my_directory"); // creates a directory named "my_directory"
```

**27. Delete a File with std::filesystem::remove**

```cpp
namespace fs = std::filesystem;
fs::remove("test.txt"); // deletes the file named "test.txt"
```

**28. List Directory Contents with std::filesystem::directory\_iterator**

```cpp
namespace fs = std::filesystem;
for (const auto& entry : fs::directory_iterator("my_directory")) {
  // do something with the entry
}
```

**29. Get Current Working Directory with std::filesystem::current\_path**

```cpp
namespace fs = std::filesystem;
fs::path current_path = fs::current_path(); // get the current working directory
```

**30. Parse a Command Line with Boost::ProgramOptions**

```cpp
#include <boost/program_options.hpp>
using namespace boost::program_options;
int main(int argc, char** argv) {
  options_description desc("Allowed options");
  desc.add_options()
    ("help", "produce help message")
    ("input", value<string>(), "input file");

  variables_map vm;        
  store(parse_command_line(argc, argv, desc), vm);
  notify(vm);    

  if (vm.count("help")) {
    cout << desc << "\n";
    return 0;
  }

  string input_file = vm["input"].as<string>();
  // do something with the input file
  return 0;
}
```

**31. Create a HTTP Server with Boost::Beast**

```cpp
#include <boost/beast.hpp>
namespace http = boost::beast::http;
int main() {
  http::server server;
  server.listen("0.0.0.0", "8080");
  server.run();
  return 0;
}
```

**32. Parse JSON with RapidJSON**

```cpp
#include "rapidjson/document.h"
rapidjson::Document doc;
doc.Parse(json.c_str()); // parse the JSON string
int value = doc["key"].GetInt(); // get the value of the "key" member
```

**33. Create a WebSocket Server with websocketpp**

```cpp
#include <websocketpp/websocketpp.hpp>
using websocketpp::connection_hdl;
using websocketpp::server;
int main() {
  server<websocketpp::config::asio_tls> s;
  s.listen("0.0.0.0", "9002");
  s.run();
  return 0;
}
```

**34. Send an Email with SmtpClient**

```cpp
#include <SmtpClient.h>
SmtpClient client("smtp.server.com", 587);
client.Login("username", "password");
client.Send("from@example.com", "to@example.com", "Subject", "Body");
```

**35. Generate a Random Number with std::random\_device**

```cpp
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(1, 100);
int random_number = dist(gen); // get a random number between 1 and 100
```

**36. Create a Stopwatch with std::chrono**

```cpp
std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
// do some time-consuming operation
std::chrono::time_point<std::chrono::high_resolution_clock> end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end - start; // get the elapsed time in seconds
```

**37. Log Messages with spdlog**

```cpp
#include "spdlog/spdlog.h"
auto logger = spdlog::stdout_logger_mt("console");
logger->info("This is an info message");
logger->error("This is an error message");
```

**38. Create a Dependency Graph with Boost::Graph**

```cpp
#include <boost/graph/adjacency_list.hpp>
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;
Graph g;
boost::add_edge(0, 1, g); // add an edge between vertices 0 and 1
```

**39. Create a Regular Expression with Boost::Regex**

```cpp
#include <boost/regex.hpp>
boost::regex re("^a(b+)*$"); // create a regular expression for matching strings that start with "a" followed by any number of "b"s
bool match = boost::regex_match("abbb", re); // check if the string "abbb" matches the regular expression
```

**40. Perform a CPU-Intensive Task with std::thread and std::atomic**

```cpp
std::atomic<int> counter = 0;
std::thread t1([&counter]() {
  for (int i = 0; i < 1000000; i++) {
    counter++;
  }
});
std::thread t2([&counter]() {
  for (int i = 0; i < 1000000; i++) {
    counter--;
  }
});
t1.join();
t2.join();
cout << counter << endl; // prints a random value near zero
```

**41. Create a Non-Blocking Socket with Boost::ASIO**

```cpp
#include <boost/asio.hpp>
int main() {
  boost::asio::io_service io_service;
  boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8080));
  for (;;) {
    boost::asio::ip::tcp::socket socket(io_service);
    acceptor.accept(socket);
    // handle the connection
  }
  return 0;
}
```

**42. Create a Binary Tree with Boost::Tree**

```cpp
#include <boost/tree/tree.hpp>
typedef boost::tree<char> Tree;
Tree t;
t.insert(t.begin(), 'A');
t.append_child(t.begin(), 'B');
t.append_child(t.begin()->begin(), 'C');
```

**43. Perform Image Processing with OpenCV**

```cpp
#include <opencv2/opencv.hpp>
cv::Mat image = cv::imread("image.jpg");
cv::cvtColor(image, image, cv::COLOR_BGR2GRAY); // convert to grayscale
cv::blur(image, image, cv::Size(3, 3)); // blur the image
cv::imshow("Gray Image", image); // show the image in a window
cv::waitKey(0); // wait for a key press
```

**44. Create a Data Structure with Boost::MultiIndex**

```cpp
#include <boost/multi_index_container.hpp>
typedef boost::multi_index_container<
  int,
  boost::multi_index::indexed_by<
    boost::multi_index::sequenced<boost::multi_index::identity<int>>,
    boost::multi_index::random_access<boost::multi_index::identity<int>>,
    boost::multi_index::hashed_non_unique<int>
  >
> IntSet;
IntSet s;
s.insert(1);
s.insert(2);
s.insert(3);
```

**45. Generate a UUID with Boost::UUID**

```cpp
#include <boost/uuid/uuid.hpp>
boost::uuids::uuid uuid = boost::uuids::random_uuid(); // generate a random UUID
string uuid_str = boost::uuids::to_string(uuid); // convert the UUID to a string
```

**46. Compress Data with zlib**

```cpp
#include <zlib.h>
int main() {
  char* uncompressed_data = "Hello, world!";
  unsigned long uncompressed_size = strlen(uncompressed_data);
  unsigned long compressed_size = compressBound(uncompressed_size);
  char* compressed_data = new char[compressed_size];
  int result = compress(compressed_data, &compressed_size, uncompressed_data, uncompressed_size);
  // decompress the data
  char* decompressed_data = new char[uncompressed_size];
  int result = uncompress(decompressed_data, &uncompressed_size, compressed_data, compressed_size);
  cout << decompressed_data << endl; // prints "Hello, world!"
  delete[] compressed_data;
  delete[] decompressed_data;
  return 0;
}
```

**47. Check if a URL is Valid with Boost::URL**

```cpp
#include <boost/url.hpp>
boost::url::url u;
try {
  u = boost::url::url("http://example.com/path/to/file.html");
  cout << "URL: " << u.protocol() << "://" << u.host() << u.path() << endl;
} catch (const boost::url::bad_url_exception& e) {
  cout << "Invalid URL: " << e.what() << endl;
}
```

**48. Create a Random Forest with scikit-learn**

```python
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
```

**49. Perform a Natural Language Processing Task with spaCy**

```python
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Hello, world!")
for token in doc:
  print(f"{token.text} ({token.pos_})")
```

**50. Create a REST API with Flask**

```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/api/todos", methods=["GET"])
def get_todos():
  return jsonify([{"id": 1, "title": "Buy milk"}, {"id": 2, "title": "Do laundry"}])
app.run()
```
