C++ <vector> size function

C++ container class <vector>


sizeis one of the most commonly used and fundamental functions in vector, used forGet the number of elements in the container。

sizeis a member function of the container class, used toreturn the number of elements currently contained in the container. This value represents the actual amount of data stored in the vector.

sizeis the most frequently used function when operating on vector, used in scenarios such as loop traversal, boundary checks, and conditional judgment.

Word Definitions: sizemeans "size", indicating the number of elements in the container.


Basic syntax and parameters

sizeis a member function of the container class; calling it requires no parameters.

Syntax format

size_type size() const;

Parameter description

  • Parameter: No parameters
    • sizetakes no parameters.

Function description

  • Return Value: returnssize_typeType (usuallysize_t), indicating the current number of elements in the container.
  • Effect: Returns a non-negative integer, indicating the number of elements actually stored in the container.
  • Note: size()What is returned is the number of elements, not the capacity. You can usecapacity()Get capacity.

Example

Let's thoroughly master it through a series of examplessizeUsage.

Example 1: Basic Usage - Getting the Number of Elements

Example

#include <iostream>
#include <vector>

int main() {
    // 1. Empty vector
    std::vector<int> emptyVec;
    std::cout << "Size of empty vector: " << emptyVec.size() << std::endl;

    // 2. Vector with elements
    std::vector<int> numbers = {10, 20, 30, 40, 50};
    std::cout << "Size of vector with elements: " << numbers.size() << std::endl;

    // 3. Use push_back to add elements
    std::vector<std::string> names;
    names.push_back("Alice");
    names.push_back("Bob");
    names.push_back("Charlie");
    std::cout << "Size after adding 3 elements: " << names.size() << std::endl;

    return 0;
}

Expected output:

空 vector 的大小: 0
有元素 vector 的大小: 5
添加 3 个元素后的大小: 3

Code analysis:

  1. empty vector'ssize()Returns 0.
  2. A vector with 5 elements returns 5.
  3. Each timepush_backAfter adding an element,size()will increase by 1.

Example 2: Using size() in a Loop

size()most commonly used to control loop iteration.

Example

#include <iostream>
#include <vector>

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

    // Use size() to control the loop
    std::cout << "Iterate over all elements: ";
    for(size_t i = 0; i < numbers.size(); ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    // Use size() to get the boundary for reverse traversal
    std::cout << "Reverse traversal: ";
    for(size_t i = numbers.size(); i > 0; --i) {
        std::cout << numbers[i - 1] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Expected output:

遍历所有元素: 10 20 30 40 50
反向遍历: 50 40 30 20 10

Code analysis:

  • numbers.size()returns 5, loop conditioni < numbers.size()Ensure no out-of-bounds access.
  • When iterating in reverse, starting fromsize()starts decreasing to 1, then accesses[i-1]。

Example 3: Using size() for Conditional Judgment

size()can be used for various conditional checks.

Example

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

void processVector(const std::vector<int>& v) {
    if(v.size() == 0) {
        std::cout << "Container is empty, no need to handle" << std::endl;
        return;
    }

    if(v.size() == 1) {
        std::cout << "Container has only one element: " << v[0] << std::endl;
        return;
    }

    std::cout << "Container has " << v.size() << " elements" << std::endl;

    // Check if it is large enough
    if(v.size() >= 10) {
        std::cout << "This is a large container" << std::endl;
    }
}

int main() {
    std::vector<int> empty;
    std::vector<int> single = {42};
    std::vector<int> normal = {1, 2, 3, 4, 5};
    std::vector<int> large(15, 1);

    processVector(empty);
    processVector(single);
    processVector(normal);
    processVector(large);

    return 0;
}

Expected output:

容器为空,无需处理
容器只有一个元素: 42
容器有 5 个元素
这是一个大容器

Code analysis:

  • size() == 0can be used to check if the container is empty.
  • size() == 1can be used to check if there is only one element.
  • size() >= 10can be used to check if the container is large enough.

Example 4: Difference between size() and capacity()

size()Returns the number of elements,capacity()returns the allocated storage space.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;

    std::cout << "Initial state:" << std::endl;
    std::cout << "  size: " << numbers.size() << std::endl;
    std::cout << "  capacity: " << numbers.capacity() << std::endl;

    // Add elements
    for(int i = 0; i < 5; ++i) {
        numbers.push_back(i + 1);
    }

    std::cout << "\nAfter adding 5 elements:" << std::endl;
    std::cout << "  size: " << numbers.size() << std::endl;
    std::cout << "  capacity: " << numbers.capacity() << std::endl;

    // Use resize to change the size
    numbers.resize(10);

    std::cout << "\nAfter resize(10):" << std::endl;
    std::cout << "  size: " << numbers.size() << std::endl;
    std::cout << "  capacity: " << numbers.capacity() << std::endl;

    // Use reserve to preallocate space
    numbers.reserve(100);

    std::cout << "\nAfter reserve(100):" << std::endl;
    std::cout << "  size: " << numbers.size() << std::endl;
    std::cout << "  capacity: " << numbers.capacity() << std::endl;

    return 0;
}

Expected output:

初始状态:
  size: 0
  capacity: 0
添加 5 个元素后:
  size: 5
  capacity: 5
resize(10) 后:
  size: 10
  capacity: 10
reserve(100) 后:
  size: 10
  capacity: 100

Code analysis:

  • size()is the number of actual elements.
  • capacity()is the size of the storage space allocated for elements.
  • resize()changesize(), will also adjustcapacity()(if needed).
  • reserve()only changescapacity(), unchangedsize()。

Example 5: Using size() to Calculate the Average

Usagesize()works with loops to calculate statistical values.

Example

#include <iostream>
#include <vector>

int main() {
    std::vector<double> scores = {85.5, 92.0, 78.5, 90.0, 88.5};

    // Calculate the sum
    double sum = 0;
    for(size_t i = 0; i < scores.size(); ++i) {
        sum += scores[i];
    }

    // Use size() to calculate the average
    double average = sum / scores.size();

    std::cout << Student scores:;
    for(double s : scores) {
        std::cout << s << " ";
    }
    std::cout << std::endl;
    std::cout << Total number of students: << scores.size() << std::endl;
    std::cout << Total score: << sum << std::endl;
    std::cout << Average score: << average << std::endl;

    return 0;
}

Expected output:

学生成绩: 85.5 92.0 78.5 90.0 88.5
总人数: 5
总成绩: 434.5
平均分: 86.9

Code analysis:

  • Usagesize()can conveniently calculate the average.
  • sum / scores.size()Calculate the average score.

C++ container class <vector>

other extensions