C++ <vector> front function

C++ container class <vector>


Among the various operations of vector,frontis a very simple function, used toGet the first element。

frontis a member function of the container class, used toreturns the first element of the container. It is equivalent toat(0)oroperator[](0), but the semantics are clearer.

frontit provides an intuitive way to access the first element of the container.

Word Definitions: frontIt means "front", i.e., gets the first (frontmost) element.


Basic syntax and parameters

frontIt is a member function of container classes, and calling it is very straightforward without requiring any parameters.

Syntax format

reference front();
const_reference front() const;

Parameter description

  • Parameter: No parameters
    • frontdoes not accept any arguments.

Function description

  • Return Value: returns the first element of the containerReferenceIf the container is a const container, it returns a const reference.
  • EffectReturns the first element of the container (the element at index 0).
  • Note: callfrontBefore using it, 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.frontUsage.

Example 1: Basic Usage - Getting the First 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 front to get the first element
    std::cout << "The first element (front): " << numbers.front() << std::endl;
    std::cout << "Use at(0): " << numbers.at(0) << std::endl;
    std::cout << "Use [0]: " << numbers[0] << std::endl;

    return 0;
}

Expected run result:

vector的大小是: 5
第一个元素 (front): 10
使用 at(0): 10
使用 [0]: 10

Code analysis:

  1. numbers.front()Return the first element10。
  2. It andnumbers.at(0)andnumbers[0]returns the same value, but with clearer semantics.

Example 2: Modifying the value of the first element

frontIt 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> names = {"Alice", "Bob", "Charlie"};

    std::cout << "Before modification, the first element: " << names.front() << std::endl;

    // Use front() to get a reference and modify the element
    names.front() = "Andrew";

    std::cout << "After modification, the first element: " << names.front() << std::endl;

    // Now the contents of names are: Andrew, Bob, Charlie

    return 0;
}

Expected run result:

修改前,第一个元素: Alice
修改后,第一个元素: Andrew

Code analysis:

  • names.front() = "Andrew";The value of the first element was modified through the reference.
  • front()returns a modifiable lvalue reference.

Example 3: Safely Using front - Checking if the Container is Empty

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

Example

#include <iostream>
#include <vector>

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

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

    // Normal case
    printFront(numbers);

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

    return 0;
}

Expected run result:

第一个元素是: 10
容器为空,无法获取第一个元素

Code analysis:

  • !v.empty()checks whether the container is not empty.
  • When callingfrontChecking before use can avoid undefined behavior.

Example 4: Using front to Implement the Front of a Queue

frontIt can be used to implement queue-like data structures.

Example

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

class SimpleQueue {
private:
    std::vector<std::string> data;

public:
    // Enqueue
    void enqueue(const std::string& item) {
        data.push_back(item);
    }

    // Dequeue (remove the front element)
    void dequeue() {
        if(!data.empty()) {
            // Remove the first element, and the following elements move forward
            data.erase(data.begin());
        }
    }

    // Get the front element
    std::string front() const {
        if(!data.empty()) {
            return data.front();
        }
        return "";
    }

    // Check whether the queue is empty
    bool empty() const {
        return data.empty();
    }

    // Get the queue size
    size_t size() const {
        return data.size();
    }
};

int main() {
    SimpleQueue q;

    q.enqueue("User A");
    q.enqueue("User B");
    q.enqueue("User C");

    std::cout << "Queue size: " << q.size() << std::endl;

    while(!q.empty()) {
        std::cout << "Processing: " << q.front() << std::endl;
        q.dequeue();
    }

    std::cout << "Queue is empty" << std::endl;

    return 0;
}

Expected run result:

队列大小: 3
处理: 用户A
处理: 用户B
处理: 用户C
队列已清空

Code analysis:

  • front()Used to get the front element (the element waiting to be processed).
  • This example demonstrates how to usefrontImplement a first-in, first-out (FIFO) queue.

C++ container class <vector>

other extensions