C++ <vector> back function

C++ container class <vector>


In various operations of vector,backis a very practical function, used toget the last element。

backis a member function of container classes, used toreturns the last element of the container. It is equivalent toat(size()-1)oroperator[](size()-1), but with clearer semantics.

backit provides an intuitive way to access the last element of a container, commonly used in implementing data structures such as stacks and queues.

Word Definitions: backIt means "back", i.e., get the last (rearmost) element.


Basic syntax and parameters

backIt is a member function of container classes; calling it is very straightforward and requires no parameters.

Syntax format

reference back();
const_reference back() const;

Parameter description

  • Parameter: No parameters
    • backdoes not accept any parameters.

Function description

  • Return Value: returns the last element of the container'sReference. If the container is a const container, it returns a const reference.
  • Effect: Returns the last element of the container (indexsize()-1element at).
  • Note: callbackBefore [use], ensure the container is not empty; otherwise, the behavior is undefined. It is recommended to first useempty()orsize() > 0Check.

Example

Let's thoroughly master [it] through a series of examples.backUsage.

Example 1: Basic usage - get the last element

Example

#include <iostream>
#include <vector>

int main() {
    // 1. Create a vector and add some elements
    std::vector<int> numbers = {10, 20, 30, 40, 50};

    std::cout << "The size of the vector is: " << numbers.size() << std::endl;

    // 2. Use back() to get the last element
    std::cout << "The last element (back): " << numbers.back() << std::endl;
    std::cout << "Using at(size()-1): " << numbers.at(numbers.size() - 1) << std::endl;
    std::cout << "Using [size()-1]: " << numbers[numbers.size() - 1] << std::endl;

    return 0;
}

Expected output:

vector的大小是: 5
最后一个元素 (back): 50
使用 at(size()-1): 50
使用 [size()-1]: 50

Code analysis:

  1. numbers.back()returns the last element50。
  2. It andnumbers.at(numbers.size()-1)andnumbers[numbers.size()-1]returns the same value, but with more explicit semantics.

Example 2: Modify the value of the last element

backIt returns a reference, so it can be used to modify the value of the element.

Example

#include <iostream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> tasks = {"Learn C++", "Do homework", "Read documentation"};

    std::cout << "Before modification, the last task: " << tasks.back() << std::endl;

    // Use back() to get a reference and modify the element
    tasks.back() = "Complete project";

    std::cout << "After modification, the last task: " << tasks.back() << std::endl;

    // Now the contents of tasks are: learn C++, do homework, complete the project

    return 0;
}

Expected output:

Before modification, last task: read documentation. After modification, last task: complete project.

Code analysis:

  • tasks.back() = "完成项目";The value of the last element is modified through the reference.
  • back()returns a modifiable lvalue reference.

Example 3: Safe use of back - check whether the container is empty

When usingbackBefore, you should first check whether the container is empty.

Example

#include <iostream>
#include <vector>

void printBack(const std::vector<int>& v) {
    if(!v.empty()) {
        std::cout << The last element is: << v.back() << std::endl;
    }
    else {
        std::cout << Container is empty, cannot get the last element << std::endl;
    }
}

int main() {
    std::vector<int> numbers = {10, 20, 30};

    // Normal case
    printBack(numbers);

    // Empty container case
    std::vector<int> emptyVec;
    printBack(emptyVec);

    return 0;
}

Expected output:

最后一个元素是: 30
容器为空,无法获取最后一个元素

Code analysis:

  • !v.empty()check whether the container is not empty.
  • When callingbackChecking before [use] can avoid undefined behavior.

Example 4: Implement a stack using back

backis often used to implement stack data structures (together withpush_backandpop_back)。

Example

#include <iostream>
#include <vector>

class Stack {
private:
    std::vector<int> data;

public:
    // Push
    void push(int value) {
        data.push_back(value);
    }

    // Pop
    void pop() {
        if(!data.empty()) {
            data.pop_back();
        }
    }

    // Get the top element of the stack
    int top() {
        if(!data.empty()) {
            return data.back();
        }
        return 0; // Indicates the stack is empty
    }

    // Check if the stack is empty
    bool empty() {
        return data.empty();
    }

    // Get the size of the stack
    size_t size() {
        return data.size();
    }
};

int main() {
    Stack s;

    // Push operation
    s.push(10);
    s.push(20);
    s.push(30);

    std::cout << Stack size: << s.size() << std::endl;
    std::cout << Top element (back): << s.top() << std::endl;

    // Pop operation
    s.pop();
    std::cout << After popping, the top element: << s.top() << std::endl;

    s.pop();
    std::cout << After popping again, the top element: << s.top() << std::endl;

    s.pop();
    std::cout << After popping again, is the stack empty: << (s.empty() ? Yes : No) << std::endl;

    return 0;
}

Expected output:

栈的大小: 3
栈顶元素 (back): 30
出栈后,栈顶元素: 20
再出栈后,栈顶元素: 10
再出栈后,栈是否为空: 是

Code analysis:

  • back()Used to get the top element of the stack (the element pushed last).
  • A stack is a last-in-first-out (LIFO) data structure,back()Exactly corresponds to the top of the stack.

Example 5: Dynamically obtaining the maximum value

UsagebackCoordinationsortGet the maximum element after sorting.

Example

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>

int main() {
    std::srand(std::time(nullptr));

    std::vector<int> numbers;
    // Randomly generate 5 numbers
    for(int i = 0; i < 5; ++i) {
        numbers.push_back(std::rand() % 100);
    }

    std::cout << Original data:;
    for(int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    // Sort
    std::sort(numbers.begin(), numbers.end());

    std::cout << "After sorting: ";
    for(int n : numbers) {
        std::cout << n << " ";
    }
    std::cout << std::endl;

    std::cout << Minimum value (front): << numbers.front() << std::endl;
    std::cout << Maximum value (back): << numbers.back() << std::endl;

    return 0;
}

Code analysis:

  • After sorting,front()Returns the minimum value,back()Returns the maximum value.
  • This is a simple way to get the maximum/minimum value.

C++ container class <vector>

other extensions