Vector i per C++
Vector i per C++
Vector i per C++
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when
an element is inserted or deleted, with their storage being handled automatically by the container.
Vector elements are placed in contiguous storage so that they can be accessed and traversed
using iterators.
In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes
the array may need to be extended. Removing the last element takes only constant time because
no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.
vector in C++ is the class template that contains the vector container and its member functions.
It is defined inside the <vector> header file. The member functions of the vector class provide
various functionalities to vector containers.
vector<dataType> vectorName;
where the data type is the type of data of each element of the vector. You can remove the if you
have already used the std namespace.
Initialization of Vector in C++
We can initialize a vector in the following ways:
1. Initialization Using List
This initialization is done with a declaration. Here, we pass the list of elements to the vector
constructor to create a vector with the specified elements.
#include <iostream>
#include <vector>
int main() {
// 1. Default Initialization
vector<int> vec1; // Creates an empty vector
cout << "Default Initialization (vec1): Size = " << vec1.size() << endl; // Output: 0
// 6. Copy Constructor
vector<int> vec6(vec5); // Copies elements from 'vec5'
cout << "Copy Constructor (vec6): ";
for (int val : vec6) {
cout << val << " "; // Output: 1 2 3 4 5
}
cout << endl;
// 8. Range Initialization
vector<int> vec8(vec5.begin() + 1, vec5.end() - 1); // Initializes with elements from index 1 to
3
cout << "Range Initialization (vec8): ";
for (int val : vec8) {
cout << val << " "; // Output: 2 3 4
}
cout << endl;
return 0;
}
Explanation
vec1: Demonstrates Default Initialization, creating an empty vector.
vec2: Demonstrates Initialization with Specific Size, creating a vector of size 5 with all
elements initialized to 0.
vec3: Demonstrates Initialization with Size and Default Value, creating a vector of size
5 with all elements initialized to 10.
vec4: Demonstrates Initialization Using an Array, initializing a vector with the
elements of an array.
vec5: Demonstrates Initialization Using an Initializer List, initializing with specified
values.
vec6: Demonstrates Copy Constructor, copying the contents of vec5.
vec7: Demonstrates Using assign() Method, assigning 5 elements with the value 20.
vec8: Demonstrates Range Initialization, initializing a vector with a subset of elements
from vec5.
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Initialize a vector with some values
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
Explanation :
1. begin(): Returns an iterator pointing to the first element. Using *vec.begin(), we can
dereference it to get the first element.
o Output: Using begin(): 10
2. end(): Returns an iterator pointing to the element after the last one. This iterator is
commonly used in loops to iterate over all elements.
o Output: Using end(): 10 20 30 40 50
3. rbegin(): Returns a reverse iterator pointing to the last element. We can use this to iterate
backward.
o Output: Using rbegin(): 50
4. rend(): Returns a reverse iterator pointing to the element before the first one. We use it to
iterate backward from rbegin() to rend().
o Output: Using rend(): 50 40 30 20 10
5. cbegin(): Returns a constant iterator pointing to the first element. It ensures that elements
cannot be modified via this iterator.
o Output: Using cbegin(): 10
6. cend(): Returns a constant iterator pointing to the element after the last one. It is used in a
loop to ensure elements are not modified.
o Output: Using cend(): 10 20 30 40 50
7. crbegin(): Returns a constant reverse iterator pointing to the last element. It ensures
elements are not modified when iterating backward.
o Output: Using crbegin(): 50
8. crend(): Returns a constant reverse iterator pointing to the element before the first one. It
is used to iterate backward in a read-only manner.
o Output: Using crend(): 50 40 30 20 10
This example covers each of the iterator types and shows how they are used to access or traverse
the elements in a vector.
-----
Capacity
1. size() – Returns the number of elements in the vector.
2. max_size() – Returns the maximum number of elements that the vector can hold.
3. capacity() – Returns the size of the storage space currently allocated to the vector expressed
as number of elements.
4. resize(n) – Resizes the container so that it contains ‘n’ elements.
5. empty() – Returns whether the container is empty.
6. shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements
beyond the capacity.
7. reserve() – Requests that the vector capacity be at least enough to contain n elements.
example
#include <iostream>
#include <vector>
int main() {
// Initialize a vector with some elements
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
------
Element access
1. reference operator [g] – Returns a reference to the element at position ‘g’ in the vector
2. at(g) – Returns a reference to the element at position ‘g’ in the vector
3. front() – Returns a reference to the first element in the vector
4. back() – Returns a reference to the last element in the vector
5. data() – Returns a direct pointer to the memory array used internally by the vector to store its
owned elements.
#include <iostream>
#include <vector>
int main() {
// Initialize a vector with some values
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
6. Reference Operator []: Returns a reference to the element at position g in the vector.
1. Usage: vec[2] accesses the element at index 2. It also allows modification of that
element.
2. Output: Element at index 2 using []: 30, then modifies the value and prints
Modified element at index 2: 35.
7. at(g): Returns a reference to the element at position g in the vector with bounds checking.
If g is out of bounds, an exception is thrown.
1. Usage: vec.at(3) accesses and modifies the element at index 3.
2. Output: Element at index 3 using at(): 40, then modifies the value and prints
Modified element at index 3: 45.
8. front(): Returns a reference to the first element in the vector.
1. Usage: vec.front() accesses and modifies the first element.
2. Output: First element using front(): 10, then modifies the value and prints
Modified first element: 5.
9. back(): Returns a reference to the last element in the vector.
1. Usage: vec.back() accesses and modifies the last element.
2. Output: Last element using back(): 50, then modifies the value and prints
Modified last element: 55.
10. data(): Returns a pointer to the first element in the array used internally by the vector.
You can use this pointer to access elements like a normal array.
1. Usage: vec.data() returns the pointer, and we use it to print all elements.
2. Output: Elements using data(): 5 20 35 45 55
------------------------------------------------------------------------------------
Modifiers
1. assign() – It assigns new value to the vector elements by replacing old ones
2. push_back() – It push the elements into a vector from the back
3. pop_back() – It is used to pop or remove elements from a vector from the back.
4. insert() – It inserts new elements before the element at the specified position
5. erase() – It is used to remove elements from a container from the specified position or range.
6. swap() – It is used to swap the contents of one vector with another vector of same type. Sizes
may differ.
7. clear() – It is used to remove all the elements of the vector container
8. emplace() – It extends the container by inserting new element at position
9. emplace_back() – It is used to insert a new element into the vector container, the new
element is added to the end of the vector
example
#include <iostream>
#include <vector>
int main() {
// Initialize a vector with some elements
vector<int> vec = {1, 2, 3, 4, 5};
return 0;
}
1. assign(): Replaces the contents of the vector with n copies of a given value.
o Usage: vec.assign(3, 10); creates a vector with three elements, all set to 10.
o Output: 10 10 10
2. push_back(): Adds an element to the end of the vector.
o Usage: vec.push_back(20); adds 20 to the end.
o Output: 10 10 10 20
3. pop_back(): Removes the last element from the vector.
o Usage: vec.pop_back(); removes the last element.
o Output: 10 10 10
4. insert(): Inserts an element before the specified position.
o Usage: vec.insert(vec.begin() + 1, 5); inserts 5 at index 1.
o Output: 10 5 10 10
5. erase(): Removes the element at the specified position.
o Usage: vec.erase(vec.begin() + 2); erases the element at index 2.
o Output: 10 5 10
6. swap(): Swaps the contents of two vectors.
o Usage: vec.swap(otherVec); swaps vec with otherVec.
o Output: vec becomes 100 200, and otherVec becomes 10 5 10.
7. clear(): Removes all elements from the vector, reducing its size to zero.
o Usage: vec.clear(); clears the vector.
o Output: size of vec: 0
8. emplace(): Inserts a new element at a specified position, constructed in place.
o Usage: vec.emplace(vec.begin(), 50); inserts 50 at the beginning.
o Output: 50
9. emplace_back(): Inserts a new element at the end of the vector, constructed in place.
o Usage: vec.emplace_back(60); inserts 60 at the end.
o Output: 50 60
These examples show how to use each function to manipulate and manage a vector in C++.
This example shows simple operations: adding elements, accessing them, and printing.
#include <iostream>
#include <vector>
int main() {
vector<int> vec; // Creates an empty vector
return 0;
}
Using a vector to store a series of numbers and print them using a for-each loop.
#include <iostream>
#include <vector>
int main() {
vector<int> numbers = {1, 2, 3, 4, 5}; // Initialize with values
return 0;
}
Using resize() to change the size of a vector and filling it with values.
#include <iostream>
#include <vector>
int main() {
vector<int> vec(5, 0); // Creates a vector with 5 elements, all
initialized to 0
return 0;
}
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
#include <iostream>
#include <vector>
int main() {
vector<string> words; // Create a vector of strings
// Modify an element
words[1] = "Vector";
return 0;
}
Summary of Examples
Prompting the user to enter numbers to fill a vector and then printing the vector.
#include <iostream>
#include <vector>
int main() {
vector<int> numbers;
int n, input;
return 0;
}
Taking user input to fill a vector and calculating the sum of all elements.
#include <iostream>
#include <vector>
int main() {
vector<int> numbers;
int n, input, sum = 0;
cout << "Sum of elements: " << sum << endl; // Output: sum of numbers
return 0;
}
Taking input from the user and finding the largest number in the vector.
#include <iostream>
#include <vector>
int main() {
vector<int> numbers;
int n, input;
cout << "Largest element: " << largest << endl; // Output: largest number
return 0;
}
Taking user input and counting how many numbers are even and how many are odd.
#include <iostream>
#include <vector>
int main() {
vector<int> numbers;
int n, input, evenCount = 0, oddCount = 0;
return 0;
}
#include <iostream>
#include <vector>
int main() {
vector<int> numbers;
int n, input;
return 0;
}
Summary of Examples
1. Taking Input to Fill a Vector: Collects a series of numbers from the user and prints them.
2. Calculating the Sum of Elements: Calculates and prints the sum of the user-inputted numbers.
3. Finding the Largest Element: Finds the largest number in a vector.
4. Counting Even and Odd Numbers: Counts how many numbers are even and how many are odd.
5. Reversing a Vector: Reverses and prints the elements of the vector.
C++, iterators are objects that function as pointers and are used to traverse through elements of
a container, like arrays, vector, list, or other Standard Template Library (STL) containers.
They are an integral part of the STL and provide a way to access elements in a sequential
manner, just like a pointer.
Here is a complete guide to understanding iterators in C++, including their types, common
functions, and examples.
1. Input Iterator:
o Can only be used to read elements in a forward direction.
o Suitable for single-pass input operations (e.g., reading from an input stream).
2. Output Iterator:
o Can only be used to write elements in a forward direction.
o Suitable for single-pass output operations (e.g., writing to an output stream).
3. Forward Iterator:
o Can be used to read or write elements in a forward direction.
o Supports multiple passes over the data.
4. Bidirectional Iterator:
o Can be used to read or write elements in both forward and backward directions.
o Examples include list and set.
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
Explanation:
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
return 0;
}
Explanation:
auto automatically deduces the type of the iterator, making the code cleaner.
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {10, 20, 30, 40, 50};
return 0;
}
Explanation:
6. Const Iterators
Const iterators are used when you want to make sure that the elements of the container are not
modified.
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
return 0;
}
Explanation:
#include <iostream>
#include <vector>
int main() {
vector<int> vec = {10, 20, 30, 40, 50};
cout << "Element at position 2: " << *it << endl; // Output: 30
return 0;
}
Explanation:
it += 2: Moves the iterator forward by two elements.
This feature is only available for random access iterators, like those used with vector and
deque.
Summary
Iterators in C++ are essential tools for accessing and manipulating elements in containers.
They come in different types: input, output, forward, bidirectional, and random access.
You can use iterator functions like begin(), end(), rbegin(), rend(), and cbegin() to
work with iterators.
The auto keyword and reverse/const iterators make it easier and more efficient to traverse and
manipulate containers.
C++ that demonstrate how to use vectors for various tasks, including taking input, performing
calculations, and using iterators.
This program collects a series of numbers from the user and stores them in a vector, then prints
the elements.
#include <iostream>
#include <vector>
int main() {
vector<int> vec;
int n, num;
return 0;
}
This program calculates and prints the sum of the numbers in the vector.
#include <iostream>
#include <vector>
int main() {
vector<int> vec;
int n, num, sum = 0;
cout << "The sum of the elements is: " << sum << endl;
return 0;
}
This program finds and prints the largest element in the vector.
#include <iostream>
#include <vector>
#include <algorithm> // For max_element()
int main() {
vector<int> vec;
int n, num;
cout << "The largest element is: " << *max_it << endl;
return 0;
}
This program counts how many even and odd numbers are in the vector.
#include <iostream>
#include <vector>
int main() {
vector<int> vec;
int n, num, even_count = 0, odd_count = 0;
return 0;
}
5. Reversing a Vector
This program reverses the elements of the vector using reverse iterators and prints them.
#include <iostream>
#include <vector>
int main() {
vector<int> vec;
int n, num;
return 0;
}
Explanation:
Taking Input: Each program collects numbers from the user and stores them in a vector.
Sum of Elements: A simple loop with iterators calculates the sum of elements.
Largest Element: Uses the max_element() function to find the largest element.
Even/Odd Count: The program iterates through the vector and uses modulo operation (% 2) to
count even and odd numbers.
Reversing: A reverse iterator (rbegin(), rend()) is used to traverse the vector from the end
to the beginning.
iterators with strings in C++, along with detailed explanations for each:
This example demonstrates how to use iterators to traverse through the characters of a string
and print each character.
int main() {
string str = "Hello, World!";
Explanation:
Output:
H e l l o , W o r l d !
This example demonstrates how to modify the characters of a string using iterators. It changes all
lowercase letters to uppercase.
int main() {
string str = "hello, world!";
return 0;
}
Explanation:
Output:
This example demonstrates how to use reverse iterators (rbegin() and rend()) to traverse a
string in reverse order and print each character.
int main() {
string str = "Hello, World!";
return 0;
}
Explanation:
str.rbegin() returns a reverse iterator pointing to the last character of the string.
str.rend() returns a reverse iterator pointing one before the first character (the theoretical
reverse end).
The for loop uses rit to iterate backward through the string, and *rit prints each character
in reverse order.
Output:
! d l r o W , o l l e H
1. Traversing with Iterators: You can use regular iterators (begin(), end()) to traverse a string
character by character.
2. Modifying Elements: You can modify characters of a string using iterators by dereferencing
them and assigning new values.
3. Reverse Traversal: Reverse iterators (rbegin(), rend()) allow you to traverse a string from
the last character to the first.
Iterator-based Traversal:
o Iterators are objects that point to elements in a container.
o You use begin() and end() (or rbegin() and rend() for reverse iteration) to define
the range of traversal.
o Iterators are more flexible and can work with different container types (e.g., vector,
list, string), supporting uniform syntax for all container types.
2. Accessing Elements
Iterator-based Traversal:
o You access elements through dereferencing the iterator (*it).
o Example:
Example:
Iterator-based Traversal:
o Works uniformly across all container types in C++ Standard Library (such as vector,
list, map, etc.), including those that do not support direct indexing.
o Iterators work with non-contiguous containers like list and set where random access
(indexing) is not available.
o Example: You can use iterators with containers like list which don’t support direct
indexing.
Normal Traversal (Index-based):
o Limited to containers that support random access (like vector, array).
o Containers like list or map do not allow direct indexing.
o Example: list<int> lst; does not support lst[i].
4. Reverse Traversal
Iterator-based Traversal:
o Iterators provide built-in support for reverse iteration using reverse iterators
(rbegin() and rend()).
o Example:
Example:
Iterator-based Traversal:
o Iterators automatically handle boundary conditions and are safer when iterating
through containers, reducing the risk of accessing out-of-bounds elements.
o With iterators, it’s less likely to make errors like accessing an invalid index.
6. Performance Considerations
Iterator-based Traversal:
o Typically, iterators and index-based access have similar performance for containers like
vector (since both are random access).
o For containers like list, iterators are more efficient, as they are optimized for linked
structures and allow for constant-time traversal.
Iterator-based Traversal:
o Iterators are widely used with the C++ Standard Library algorithms (like for_each,
sort, find, etc.).
o Example using an algorithm with iterators:
Iterator-based Traversal:
o Works seamlessly with all types of containers, including non-contiguous ones like list,
set, map, and others.
o Example:
Summary of Differences
manipulation
Similar performance for random-access O(1) for random access, but not
Performance containers; more efficient for non-random applicable for non-random
containers containers
More flexible, especially for non-contiguous Simpler for containers that support
Ease of Use
containers indexing
Both iterator-based traversal and index-based traversal have their strengths and are suited to
different situations. Iterators are more flexible, safe, and compatible with a wide range of
containers, making them a powerful feature in C++. However, for simple, random-access
containers like vector, index-based traversal may be more intuitive and easier to write