Lists (Vectors)

NOTE: This article was only written in C++, therefore only C++ code will be displayed.

Basic list functions

// vector<type>
vector<int> nums;
vector<string> strings;

// all the examples below use "nums" as the example vector

// add an element to the list
nums.push_back(5);
nums.push_back(8);
nums.push_back(2);

// get number of elements in the list
int size = nums.size();

// erase element
nums.erase(nums.begin() + 2); // erases value with index 2

// erase multiple elements
// erases values from index 2 to 5 (the 6 is not a typo; that index is not included in the erase)
nums.erase(nums.begin() + 2, nums.begin() + 6);

Sorting, finding and other operations

// sorting
sort(nums.begin(), nums.end());

// sorting in reverse (high to low)
sort(nums.rbegin(), nums.rend());

// reverse a list
reverse(nums.begin(), nums.end());

// find an element in a list
auto it = nums.find(nums.begin(), nums.end(), 6);

// this can check if the element was found or not

if(it != nums.end()){
    // do stuff when the item was found

    // index would contain the index of the value found
    int index = it - nums.begin();
    cout << "found 6 at index: " << index << endl;
} else{
        // do stuff when it was not found
    cout << "6 was not found" << endl;
}

Maximum and minimum element

// finding max / minimum element

// max_element() or min_element() depending on what is needed
auto it = max_element(nums.begin(),nums.end());
int index = it - nums.begin();
int value = nums[index];
Copied to Clipboard