Modifying a Vector
In addition to creating a vector and accessing its elements, the Vector Library provides various methods to modify the vector. These methods allow you to add, remove, and modify elements as needed.
Adding Elements
To add elements to a vector, you can use the push_back()
method. This method appends the element to the end of the vector. Here's an example:
1std::vector<int> numbers = {1, 2, 3};
2numbers.push_back(4);
After executing this code, the numbers
vector will contain the elements [1, 2, 3, 4]
.
Modifying Elements
You can modify elements in a vector by accessing them using the subscript operator []
and assigning a new value. Here's an example:
1std::vector<int> numbers = {1, 2, 3, 4};
2numbers[1] = 5;
After executing this code, the numbers
vector will contain the elements [1, 5, 3, 4]
. The element at index 1 (2
) has been replaced with the value 5
.
Removing Elements
To remove elements from a vector, you can use the pop_back()
method. This method removes the last element from the vector. Here's an example:
1std::vector<int> numbers = {1, 2, 3};
2numbers.pop_back();
After executing this code, the numbers
vector will contain the elements [1, 2]
. The last element (3
) has been removed.
By using these methods, you can easily add, modify, and remove elements in a vector to suit your needs.
Next, we will explore common operations performed on vectors, such as sorting, searching, and merging.
xxxxxxxxxx
int main() {
// Creating a vector
std::vector<int> numbers = {1, 2, 3};
// Adding elements to the vector
numbers.push_back(4);
// Modifying elements in the vector
numbers[1] = 5;
// Removing elements from the vector
numbers.pop_back();
// Printing the vector
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
return 0;
}