How to Check Size how to check size of std vector std::vector in C
In this article, we will discuss how to check the size of a std::vector in C . The size of a std::vector refers to the number of elements it currently holds.
1. **Using the `size()` Function**:
The easiest way to check the size of a std::vector is by using the `size()` function.
This function returns the number of elements in the vector. Here's an example:
```cpp
#include
#include
int main() {
std::vector myVector = {1, 2, 3, 4, 5};
size_t vectorSize = myVector.size();
std::cout << "The size of the vector is: " << vectorSize << std::endl;
return 0;
}
```
In this example, we create a vector of integers, `myVector`, and then use the `size()` function to get the number of elements in the vector.
This number is stored in `vectorSize` and printed to the console.
2. **Using the `empty()` Function**:
The `empty()` function checks if a std::vector is empty. It returns `true` if the vector is empty and `false` otherwise. Here's how to use it:
```cpp
#include
#include
int main() {
how to check size of std vector std::vector myVector = {1, 2, 3, 4, 5};
if (myVector.empty()) {
std::cout << "The vector is empty." << std::endl;
} else {
std::cout << "The vector is not empty." << std::endl;
std::cout << "The size of the vector is: " << myVector.size() << std::endl;
}
return 0;
}
```
In this example, we check if `myVector` how to check size of std vector empty using the `empty()` function.
If the vector is empty, we print a message to the console. If it's not empty, we print a message and the size of the vector using the `size()` function.
3. **Using Range-based For Loop**:
You can also check the size of a std::vector by iterating through it using a range-based for loop.
Here's an example:
```cpp
#include
#include
int main() {
std::vector myVector = {1, 2, 3, 4, 5};
for (const auto& element : myVector) {
// Do something with each element.
}
std::cout << "The size of the vector is: " << myVector.size() << std::endl;
return 0;
}
```
In this example, we iterate through `myVector` using a range-based for loop.
After the loop, we print the size of the vector using the `size()` function.
In conclusion, there are multiple ways to check the size of a std::vector in C . The most common methods are using the `size()` function, the `empty()` function, and iterating through the vector using a range-based how to check size of std vector loop.
Choose the method that best fits your needs.