When working with std::vector
in C++, inserting and erasing elements efficiently is crucial for performance, especially when dealing with large datasets. Here are some tips and techniques to handle these operations effectively:
To insert elements into a std::vector
, you can use the push_back()
method, which adds an element to the end of the vector. This is an efficient operation, as it usually runs in constant-time (O(1)). However, if the underlying array needs to be resized, it can lead to a potential time complexity of O(n).
If you need to insert an element at a specific position, you can use the insert()
method. This operation may take O(n) time because all elements after the insertion point have to be shifted.
To remove elements, you can use the erase()
method, which also takes O(n) time since it requires shifting elements to fill in the gap left by the erased element. For better performance, consider marking elements as "deleted" rather than actually removing them until you really need to.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector vec;
// Inserting elements
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
vec.insert(vec.begin() + 1, 15); // Insert 15 at index 1
// Display vector
cout << "Vector after insertion: ";
for (int x : vec) {
cout << x << " ";
}
cout << endl;
// Erasing an element
vec.erase(vec.begin() + 1); // Erase element at index 1
// Display vector
cout << "Vector after erasing: ";
for (int x : vec) {
cout << x << " ";
}
cout << endl;
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?