Damon's Blog
  • Damon's Blog
  • 💻Tech
    • Understand C++ Special Member Function Generation
    • Understand C++ Template Type Deduction
    • Using Windows Keymap in Mac and Intellij
    • Setup C++ Dev Env in MacOS using Docker
    • Floating-point Arithmetic
    • Java HFT Toolbox
    • Interesting Bitwise Operation
    • Python Metaclass
    • Memory Order
    • Grind 75+
      • Array
      • String
      • Matrix
      • Binary Search
      • Graph
      • Tree
      • Math
      • Hash Table
      • Recursion
      • Linked List
      • Stack
      • Heap
      • Trie
      • Dynamic Programming
      • Binary Operation
    • C++ for Java Developers
    • Typical Domain Driven Design Application Architecture
    • How to Deploy Applications in Linux Properly
    • Design Patterns with Java Examples
    • Tools for Reliability
    • MVCC in Database
    • Two Microservice Tech Stacks
    • The Difference between 127.0.0.1 and 0.0.0.0
  • âž—Math
    • Local Volatility in Terms of Implied Volatility
    • Mean and Variance of Squared Gaussian
    • A Simple Explanation of Information Gain
  • 💲Trading
    • Understanding Risk-Neutral Density Functions
    • The Deriving of Black-Scholes Equation
    • Quant Questions
  • 💎Gems
    • 2024
  • 📖Books
    • Performance Analysis and Tuning on Modern CPUs
Powered by GitBook
On this page
  • Array
  • String
  • IO
  • List
  • Vector / ArrayList
  • Linked List
  • Heap
  • Map
  • Set
  • Queue
  • Stack
  • Template / Generics / metaclass

Was this helpful?

  1. Tech

Grind 75+

PreviousMemory OrderNextArray

Last updated 5 months ago

Was this helpful?

More than .

Here is the common syntax in JDK, C++ STL and Python core module.

Array

Note that in Python NumPy is required for array type.

  1. CREATE

    // c++
    int a[3] = {0}; // init with default value, same as `int a[3] = {};` or `int a[3]{}` or `int a[3]{0}`
    
    int length = 3; // not a constant
    int a[length]; // cannot init with default value when the length is not a constant
    std::fill(a, a+length, 1); // init with default value using std::fill()
    
    int a[] = {1, 1}; // init with length 2 and default values as 1
    // java
    int[] a = new int[3]; // init with default value 0 for int
    
    int[] a = new int[] {1, 1, 1}; // init with length 3 and default values as 1
    
    int[] a = {1, 2, 3};
    # python
    import numpy as np
    a = np.zeros(3) # init with default value 0 for int
    a = np.array([1, 1, 1]) # int with default values 
  2. READ

    // c++
    int a[] = {1, 2, 3};
    int size = sizeof(a) / sizeof(a[0]);
    
    // classic
    for (int i = 0; i < size; i++) {
        cout<< a[i] << endl;
    }
    
    // range-based for loop
    for (auto& e : a) {
        cout<< e << endl;
    }
    
    // iterator
    for (auto it = std::begin(a); it != std::end(a); ++it) {
         cout << *it << endl;
    }
    
    // algorithm, note here the output array is also a
    std::transform(std::begin(a), std::end(a), std::begin(a), [](int x) { 
        cout << x << endl; 
        return x; 
    });
    // java
    int[] a = {1, 2, 3};
    
    // classic
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
    
    // we have to transform it to list to use iterator
    Iterator<Integer> it = Arrays.asList(a).iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
    
    // or use stream api 
    a = IntStream.of(numbers).map(x -> {
        System.out.println(x);
        return x;
    }).toArray();
  3. MODIFY

    // c++
    int a[3] = {0}; // {0, 0, 0}
    std::fill(a, a+3, 1); // {1, 1, 1}
    // java
    int[] a = new int[3];
    Arrays.fill(a, 1); // {1, 1, 1}
    # python
    a = np.array([0, 0, 0])
    a.fill(1) # {1, 1, 1}
  4. SIZE

    // c++
    int a[6]{};
    int length = sizeof(a) / sizeof(a[0]);
    // java
    int[] a = new int[6];
    int length = a.length;
    # python
    import numpy as np
    a = np.zeros(6)
    length = len(a)
  5. SORT

    // c++
    int a[] = {3, 2, 1};
    
    std::sort(a, a+3); // {1, 2, 3}
    
    std::sort(arr, arr + size, [](int a, int b) {
        return a > b; // Custom comparison logic for descending order
    }); // {3, 2, 1}
    
    std::sort(std::begin(a), std::end(a)); // {1, 2, 3}
    
    std::sort(std::begin(a), std::end(a), [] (int a, int b) {
        return a > b;
    }); // {3, 2, 1}
    // java
    int[] a = {3, 2, 1};
    
    // !! you cannot apply the comparator to a
    Arrays.sort(a); // {1, 2, 3}
    
    // Note it's important to note that Collections.reverseOrder() cannot be directly applied to primitive arrays (like int[]). Instead, you need to use wrapper classes (like Integer[]) for this purpose.
    Integer[] arr = {1, 2, 3};
    Arrays.sort(arr, Collections.reverseOrder()); // {3, 2, 1}
    
    // stream API
    a = IntStream.of(a).sorted().toArray();
    a = IntStream.of(a).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
    # python
    import numpy as np
    a = np.array([3, 1, 2])
    np.sort(a)
    a = np.sort(a)[::-1] # create a new array
    a[::-1].sort() # sort in place
  6. MAX / MIN

    // c++
    int a[] = {1, 2, 3};
    int max = *std::max_element(a, a+3);
    int min = *std::min_element(a, a+3);
    // java
    int[] a = {1, 2, 3};
    int max = Arrays.stream(a).max().getAsInt(); // note that stream may auto box the int to Integer
    int max = Arrays.stream(a).max().orElse(Integer.MIN_VALUE); // note that in the end it will auto unbox the Integer to int
    int min = Arrays.stream(a).min().getAsInt();
    int min = Arrays.stream(a).min().getAsInt();
    # python
    import numpy as np
    a = np.array([1, 2, 3])
    max = np.max(a)
    min = np.min(a)
  7. BINARY SEARCH

    // c++
    int a[] = {2, 3, 4, 10, 10, 10, 40};
    bool found = std::binary_search(a, a + n, 10); // true
    
    // lower_bound finds the first position where the value could be inserted without violating the order, 
    // while upper_bound finds the last position where the value could be inserted without violating the order.
    auto it = std::lower_bound(a, a + n, 10); // element >= 10, (it - a) == 3
    if (it != a + n && *it == key) {
        // found
    } else {
        // not found
    }
    
    auto it2 = std::upper_bound(a, a+n, 10); // element > 10, (it - a) == 6
    if (it2 != a + n && *it2 == key) {
        // found
    } else {
        // not found
    }
    // java
    int result = Arrays.binarySearch(arr, key);
    if (result >= 0) {
        System.out.println("Element found at index: " + result);
    } else {
        int insertPos = ~result;
        System.out.println("Element not found, insert position is: " + insertPos);
    }
    # python
    import numpy as np
    a = np.array([1, 2, 2, 3, 3, 3, 4, 5, 6, 6])
    left_index = np.searchsorted(arr, 3, side='left', sorter=None) # 3, it returns the index of the first suitable location found
    right_index = np.searchsorted(arr, 3, side='right') # 6, it returns the index of the last suitable location

String

#include <iostream>
#include <cstring>
#include <string>

int main() {
    // Using std::string
    std::string greeting = "Hello";
    greeting += ", World!"; // Concatenation
    std::cout << greeting << std::endl; // Output: Hello, World!

    // Finding substring
    size_t pos = greeting.find("World");
    if (pos != std::string::npos) {
        std::cout << "'World' found at position: " << pos << std::endl;
    }

    // Replacing substring
    greeting.replace(pos, 5, "C++");
    std::cout << greeting << std::endl; // Output: Hello, C++!

    // Getting length of the string
    std::cout << "Length of greeting: " << greeting.length() << std::endl;

    // Using C-style strings
    char cstr[100] = "Hello";
    strcat(cstr, ", World!");
    std::cout << cstr << std::endl; // Output: Hello, World!

    return 0;
}
  1. CREATE

    // c
    char cs[] = "hello world"; // c-style string
    
    // c++
    std::string s = "hello world";
    
    std::stringstream ss;
    ss << "Hello " << "World";
    s = ss.str();
    
    const char* cs = s.c_str(); // string to c-style string
    // java
    String s = "a";
    String s1 = "a"; // String is a special semi-singleton class in Java, here s == s1 and s.equals(s1)
    String s2 = new String("a"); // here s != s2 but s.equals(s2)
    
    char[] cs = s.toCharArray();
    char char = cs[0]; // 'a'
    char char2 = s.charAt(0); // 'a'
    
    StringBuilder sb = new StringBuilder("hello "); // StringBuilder is not thread-safe
    sb.append("world");
    String s = sb.toString(); // "hello world"
    
    StringBuffer sb = new StringBuffer("hello "); // StringBuffer is thread-safe
    sb.append("world");
    String s = sb.toString(); // "hello world"
    # python
    s = "a"
    s1 = 'a'
    s2 = """
    hello world
    """
  2. READ

    // c
    char cs[] = "hello world"; // c-style string
    
    for (int i = 0; i < strlen(cs); i++) {
        cout << cs[i] << endl;
    }
    
    // c++
    string s = "hello world";
    
    for (char c : s) {
        cout << c << endl;
    }
    String s = "Hello World";
    for (char c : s.toCharArray()) {
        System.out.print(c);
    }
  3. MODIFY

    // c
    char cs[] = "hello world"; // c-style string
    char destination[50]; // Ensure destination is large enough
    
    strcpy(destination, cs);
    strncpy(destination, source, 5); // Copy only the first 5 characters
    
    const char* append = "!";
    strcat(destination, append); // "hello world!"
    
    destination[0] = 'H'; // "Hello world!"
    
    // c++
    string s = "hello world";
    s[0] = 'H'; // "Hello world"
    
    string sub = s.substr(6, 5); // substr starting from index 6 and length is 5
    
    string append = "!";
    string d = s + append; // "Hello world!"
    string d = s.append(append); // "Hello world!"
  4. LENGTH

    // c
    char cs[] = "hello world"; // c-style string
    size_t size = strlen(cs); // size == 11; note that size_t is platform-dependent
    
    // c++
    string s = "hello world";
    size_t size = s.size();
    size_t size = s.length(); // inter-changable
  5. ITERATOR

    // c++
    String s = "hello world!";
    std::string::iterator it;
    string t = "world";
    it = std::search(s.begin(), s.end(), t.begin(), t.end()); // the algorithm use == to compare which is case-sensitive
    if (it != s.end()) {
        std::string::difference_type diff = it - s.begin();
        // If the substring is found, we print its characters by iterating from the it iterator until the end of the string s.
        cout << *it << endl; // "world!"
    } else {
        cout << "not found" << endl;
    }
  6. SORT

    // c++
    std::string str = "Hello, World!";
    std::sort(str.begin(), str.end()); // !,HWdellloor, case-sensitive ASC
    
    auto caseInsensitiveCompare = [](char a, char b) {
         return std::tolower(a) < std::tolower(b);
     };
    std::sort(str.begin(), str.end(), caseInsensitiveCompare);
  7. SEARCH

    // c++
    String s = "hello world!";
    size_t pos = s.find('h'); // find the first 'h' in string, return 0
    size_t pos = s.find('l', 3); // find the first 'l' in string, starting from index 3, return 3
    size_t pos = s.find('z'); // return std::string::npos, which is defined as size_t(-1), which represents the largest value that can be represented by `size_t` type
    
    string t = "world";
    size_t pos = s.find(t);
    if (pos != std::string::npos) {
         // Print the found substring using the found index
         std::cout << "Found substring: " << s.substr(found, findStr.length()) << std::endl; // "world"
    } else {
        cout << "not found" << endl;
    }

IO

// c++
int number;
std::cout << "Enter a number: ";
std::cin >> number; // Reads an integer from stdin
std::cout << "You entered: " << number << std::endl;

std::string line;
std::cout << "Enter a line of text: ";
std::getline(std::cin, line); // Reads an entire line from stdin
std::cout << "You entered: " << line << std::endl;

std::string line;
std::cout << "Enter lines of text (empty line to stop):" << std::endl;
while (std::getline(std::cin, line) && !line.empty()) {
    std::cout << "You entered: " << line << std::endl;
}

// Redirect stdin to a file
freopen("input.txt", "r", stdin);

std::string line;
while (std::getline(std::cin, line)) {
  std::cout << "Read from file: " << line << std::endl;
}
// java
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");
String myString = scanner.nextLine(); // Read a string

System.out.print("Enter an integer: ");
int myInt = scanner.nextInt(); // Read an integer

scanner.close(); // Close the scanner

System.out.println("You entered: " + myString);
System.out.println("You entered: " + myInt);

List

Vector / ArrayList

Note that in Python the default list is not backed by array.

Note that in C++ begin() and end() provide iterators to the first and one-after-last element of the vector. and rbegin() and rend() provide iterators in reverse order.

  1. CREATE

    // c++
    vector<int> v; // empty
    vector<int> v(3); // init with a capacity of  6, not emtpy; [0, 0, 0]
    vecotr<int> v(3, 1); // init with a capacity of 6 and default value as 1; [1, 1, 1]
    // java
    ArrayList<Integer> a = new ArrayList<>();
    ArrayList<Integer> a = new ArrayList<>(3); // init with a capacity of  3, but it's empty; []
    int[] tmp = new int[3];
    Arrays.fill(tmp, 1);
    ArrayList<Integer> a = new ArrayList<>(Arrays.asList(tmp)); // [1, 1, 1]
  2. READ

    // c++
    vecotr<int> v(3, 1); // [1, 1, 1]
    
    v.front(); // or v[0]
    v.back(); // or v[v.size()-1]
    // java
    int[] tmp = new int[3];
    ArrayList<Integer> a = new ArrayList<>(tmp);
    
    a.get(0); // first element
    a.get(a.size()-1); // last element
  3. MODIFY

    // c++
    vecotr<int> v(3, 1); // [1, 1, 1]
    
    v.push_back(2); // [1, 1, 1, 2]
    v.pop_back(); // [1, 1, 1]
    
    v.insert(v.begin(), 2); // [2, 1, 1, 1], insert at the front
    v.insert(v.begin()+1, 3); // [2, 3, 1, 1, 1]
    v.insert(v.end(), 5); // [2, 3, 1, 1, 1, 5], insert at the end, same as `v.push_back(5)`
    
    vector<int> v2(2, 2); // [2, 2]
    v.insert(v.end(), v2.begin(), v2.end()); // [2, 3, 1, 1, 1, 5, 2, 2]
    
    int a[2] = {3, 3}; // [3, 3]
    v.insert(v.end(), std::begin(a), std:;end(a)); // [2, 3, 1, 1, 1, 5, 2, 2, 3, 3]
    
    v.insert(v.end(), 2, 4); // [2, 3, 1, 1, 1, 5, 2, 2, 3, 3, 4, 4], insert 4 twice
    // java
    int[] tmp = new int[] {1, 1, 1};
    ArrayList<Integer> a = new ArrayList<>(tmp); // [1, 1, 1]
    
    a.add(2); // [1, 1, 1, 2]
    a.remove(a.size()-1); // [1, 1, 1]
    
    a.add(0, 2); // [2, 1, 1, 1], insert at the front
    a.add(1, 3); // [2, 3, 1, 1, 1]
    // note that if you run `a.add(4, 3)` it will throw IndexOutOfBoundsException,
    // this is because valid indices for an ArrayList are from 0 to size() - 1.
    a.add(5); // [2, 3, 1, 1, 1, 5], insert at the end
    
    ArrayList<Integer> a2 = new ArrayList<>(new int[] {2, 2}); // [2, 2]
    a.addAll(a2); // [2, 3, 1, 1, 1, 5, 2, 2]
    
    int[] tmp = new int[] {3, 3};
    a.addAll(Arrays.asList(tmp)); // [2, 3, 1, 1, 1, 5, 2, 2, 3, 3]
  4. SIZE

    // c++
    vector<int> v(3, 1); // [1, 1, 1]
    int s = v.size(); // s == 3
    v.resize(5, -1); // [1, 1, 1, -1, -1]
    v.resize(3, -2); // [-2, -2, -2]
    v.resize(6); // [-2, -2, -2, 0, 0, 0]
    bool b = v.empty(); // b == false
    // java
    int[] tmp = new int[3];
    ArrayList<Integer> a = new ArrayList<>(tmp);
    int s = a.size(); // s == 3
    bool b = a.isEmpty(); // b == false
  5. ITERATOR

    // c++
    vector<int> v(3, 1);
    for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
        cout << *it << endl;
    }
    // java
    final List<Integer> a = new ArrayList<>();
    a.add(1);
    a.add(1);
    a.add(1);
    final ListIterator<Integer> it = a.listIterator();
    while (it.hasNext()) {
        System.out.print(it.next());
    }
  6. SORT

  7. BINARY SEARCH

  8. MATH

Linked List

Heap

// c++
//java

// Comparable

// Comparator

Map

// c++
std::unordered_map<char, int> myMap;
// Accessing a key that doesn't exist yet,
// try to access a key that doesn't exist, the map will automatically initialize the value for that key to the default value for the value type, which is 0 in the case of int.
std::cout << "Value of 'a': " << myMap['a'] << std::endl; // Output: 0

char key = 'a';
std::unordered_map<char, int>::iterator it = myMap.find(key)
if (it != myMap.end()) {
    // find it
} else {
    // not find it
}
Map<String, String> map = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<String, String> entry = it.next();
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

map.forEach((k, v) -> System.out.println(k + "/" + v));

map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + "/" + e.getValue()));

final String key = "a";
if (map.contains(key)) {
    // contains key
} else {
    // not contians key
}

Set

Queue

#include <iostream>
#include <queue>

int main() {
    std::queue<int> myQueue;

    // Enqueue elements
    myQueue.push(10);
    myQueue.push(20);
    myQueue.push(30);

    // Display front element
    if (!myQueue.empty()) {
        std::cout << "Front element: " << myQueue.front() << std::endl; // Output: 10
    }

    // Update front element by removing it and adding a new one
    if (!myQueue.empty()) {
        int oldValue = myQueue.front();
        std::cout << "Updating front element: " << oldValue << " to 25." << std::endl;
        myQueue.pop(); // Remove old value
        myQueue.push(25); // Add new value
    }

    // Display all elements in the queue after update
    std::cout << "Elements in queue after update: ";
    while (!myQueue.empty()) {
        std::cout << myQueue.front() << " "; // Output: 20 25 30 
        myQueue.pop();
    }
    
    return 0;
}

Stack

Template / Generics / metaclass

💻
Grind 75 questions