Understanding the time complexity of common operations in C++ is crucial for writing efficient code. Here's a list of some common operations and their Big OÂ complexities:
Accessing an element in an array by its index is a constant time operation, regardless of the size of the array.
int array[10000];
std::cout << array[0];// O(1)
std::cout << array[9999];// Also O(1)
In C++, a vector
 is a dynamic array that can grow in size. Inserting an element at the end of a vector is typically an operation. However, if the vector needs to resize to accommodate the new element, it might need to copy all existing elements to a new memory location, which is an operation. But this resizing happens infrequently (doubling each time), so the amortized (average over many insertions) time complexity is .
std::vector<int> vec;
vec.push_back(1);// O(1) on average
Inserting an element at the beginning or middle of a vector requires shifting all the subsequent elements one position to the right, which is a linear operation.
std::vector<int> vec {1, 2, 3, 4, 5};
vec.insert(vec.begin(), 0);// O(n)
In the worst case, a search may need to check every element, resulting in linear complexity.
int array[5] = {3, 1, 4, 1, 5};
for (int i = 0; i < 5; i++) {
if (array[i] == 1) {// O(n)
std::cout << "Found";
break;
}
}
If the array is sorted, we can use binary search, which has logarithmic complexity.
std::vector<int> vec {1, 2, 3, 4, 5};
bool found = std::binary_search(
vec.begin(), vec.end(), 3); // O(log n)
These are just a few examples. The C++ standard library provides many data structures and algorithms, each with its own time (and space) complexity guarantees. It's a good practice to familiarize yourself with these complexities to write efficient code.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to algorithms - the foundations of computer science. Learn how to design, analyze, and compare them.