vector size
The size of a vector in C++ can be determined using the size()
function. Here are the steps to get the size of a vector:
- Declare a vector variable: Start by declaring a vector variable. For example, you can declare a vector of integers like this:
std::vector<int> myVector;
- Populate the vector: Add elements to the vector using the
push_back()
function. For example, add three integers to the vector:
myVector.push_back(10);
myVector.push_back(20);
myVector.push_back(30);
- Get the size of the vector: To obtain the size of the vector, call the
size()
function on the vector variable. This function returns an integer representing the number of elements in the vector. For example:
int vectorSize = myVector.size();
- Use the vector size: You can now use the
vectorSize
variable to perform operations based on the size of the vector. For example, you can iterate over the vector using a loop:
for (int i = 0; i < vectorSize; i++) {
std::cout << myVector[i] << " ";
}
That's how you can determine the size of a vector in C++ using the size()
function.