What Is Vector Data Structure in C?
In C programming, a vector is a dynamic data structure that allows storing and manipulating a collection of elements. It is similar to an array but with added flexibility. The vector data structure is part of the Standard Template Library (STL) in C++ and is widely used due to its efficiency and convenience.
Advantages of Using Vectors:
- Vectors can dynamically grow or shrink their size as needed, unlike arrays that have a fixed size.
- Vectors provide fast access to elements using random access iterators.
- They support various useful member functions such as insertion, deletion, sorting, searching, etc.
Declaring and Initializing Vectors:
Before using vectors in your C program, you need to include the header file <vector.h>
. Here’s how you can declare and initialize a vector:
#include <vector.h>
int main() {
// Declare an empty vector
vector<int> numbers;
// Declare and initialize a vector with values
vector<int> primes = {2, 3, 5, 7, 11};
return 0;
}
Accessing Elements in Vectors:
You can access individual elements in a vector using their index. The index starts from zero for the first element. Here’s an example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> fruits = {"apple", "banana", "orange"};
// Accessing elements
cout << fruits[0] << endl; // Output: apple
cout << fruits[1] << endl; // Output: banana
cout << fruits[2] << endl; // Output: orange
Manipulating Vectors:
Vectors provide several member functions to manipulate their contents. Here are some common operations:
- push_back(element): Adds an element to the end of the vector.
- pop_back(): Removes the last element from the vector.
- size(): Returns the number of elements in the vector.
- insert(position, element): Inserts an element at a specific position.
- erase(position): Removes an element at a specific position.
Example:
int main() {
vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
cout << "Size: " << numbers.size() << endl;
numbers.insert(numbers.begin() + 1, 15);
for (int i = 0;i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp amp;i<numbers.size(); i++) {
cout << numbers[i] << " ";
}
cout << endl;
numbers.erase(numbers.begin() + 2);
for (int i = 0;i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp amp;i<numbers.size(); i++) {
cout << numbers[i] << " ";
}
cout << endl;
Conclusion:
Vectors are a powerful data structure in C that offer flexibility and efficiency. They allow dynamic resizing, fast access to elements, and provide various useful member functions for manipulation. Understanding vectors is essential for writing efficient and scalable C programs.