SIZE()

size() and length() do exactly the same thing: they both return the number of characters in the string. They are interchangeable, using one the other is mostly a matter of style or readability.

This method is used to determine the number of elements in a container or the number of characters in a string. For the std::string class, size() returns the length of the string, which is equivalent to length(), allowing you to know how many characters are stored. Similarly, for standard containers like std::vector, std::array, or std::deque, size() returns the number of elements currently held in the container. This method is essential for loops, bounds checking, and dynamic operations, as it provides a safe and convenient way to query the current size without manually tracking the number of elements. It is a constant-time operation (O(1)) for most standard containers, making it efficient for performance-sensitive code.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, world!";
    
    cout << "Using size(): " << text.size() << endl;
    cout << "Using length(): " << text.length() << endl;

    return 0;
}

OUTPUT:
 Using size(): 13
 Using length(): 13

Last updated