0% found this document useful (0 votes)
15 views22 pages

Vector and STL Operations in C++

The document contains a series of programming assignments that demonstrate various features of the C++ Standard Template Library (STL). Each assignment includes code examples for vector operations, iterator categories, STL algorithms, pairs, maps, sets, stacks, queues, unordered maps, and custom comparators. The assignments aim to illustrate the practical applications of STL in managing data structures and algorithms effectively.

Uploaded by

vishalrajguru05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views22 pages

Vector and STL Operations in C++

The document contains a series of programming assignments that demonstrate various features of the C++ Standard Template Library (STL). Each assignment includes code examples for vector operations, iterator categories, STL algorithms, pairs, maps, sets, stacks, queues, unordered maps, and custom comparators. The assignments aim to illustrate the practical applications of STL in managing data structures and algorithms effectively.

Uploaded by

vishalrajguru05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Assignment - 8

Q1)Write a program that demonstrates vector operations by creating a vector<int> and


inserting at least ten integers into it. Use iterators to display all elements, then apply STL
functions to find the maximum and minimum values, reverse the contents of the vector, and
finally sort it in ascending order.

#include <bits/stdc++.h>

int main()
{
// Add 10 iterms to a vector
std::vector<int> array;
for (int i = 0; i < 10; i++)
{
array.push_back(i);
}

// Display all elements using iterator


std::vector<int>::iterator it = [Link]();
for (int i = 0; i < 10; i++)
{
std::cout << *it << " ";
it++;
}
std::cout << std::endl;

// Find min and max using stl functions


std::vector<int>::iterator start_it = [Link]();
std::vector<int>::iterator end_it = [Link]();
std::cout << *std::max_element(start_it, end_it) << std::endl;
std::cout << *std::min_element(start_it, end_it) << std::endl;

// Reverse the vector


std::reverse(start_it, end_it);
for (int i = 0; i < 10; i++)
{
std::cout << *start_it << " ";
start_it++;
}
std::cout << std::endl;

// Sort in ascending
start_it = [Link]();
std::sort(start_it, end_it);
for (int i = 0; i < 10; i++)
{
std::cout << *start_it << " ";
start_it++;
}
std::cout << std::endl;
}

Output:
Q2)Develop a program to illustrate the use of different iterator categories by creating a list >
and a vector. Use forward iterators to traverse and display the elements of the vector, and use
bidirectional iterators to display the elements of the list in reverse order. Explain the
difference in iterator behavior through the program.

#include <iostream>
#include <vector>
#include <list>
using namespace std;

int main()
{
// Vector uses Random Access / Forward Iterator
vector<int> vec = {10, 20, 30, 40, 50};

cout << "Vector elements (Forward Iterator Traversal):" << endl;

// Forward iteration using vector<int>::iterator


for (vector<int>::iterator it = [Link](); it != [Link](); ++it)
{
cout << *it << " ";
}
cout << endl
<< endl;

// List uses Bidirectional Iterator


list<int> lst = {100, 200, 300, 400, 500};

cout << "List elements:" << endl;

// Bidirectional iteration: using reverse iterators


for (list<int>::reverse_iterator rit = [Link](); rit != [Link](); ++rit)
{
cout << *rit << " ";
}
cout << endl;

return 0;
}

Output:
Q3)Write a program that applies various STL algorithms on a vector of integers. The program
should accept elements from the user and then use count() to count occurrences of a
particular number, accumulate() to compute the sum, find() to search for a value, and
remove_if() with a lambda expression to remove all odd numbers. Display the output after
each operation.

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

int main()
{
int n, value;

// INPUT FROM USER


cout << "Enter number of elements: ";
cin >> n;

vector<int> vec(n);

cout << "Enter " << n << " integers:\n";


for (int i = 0; i < n; i++)
{
cin >> vec[i];
}

// 1. count()
cout << "\nEnter a number to count its occurrences: ";
cin >> value;

int occurrences = count([Link](), [Link](), value);


cout << "Occurrences of " << value << ": " << occurrences << endl;

// 2. accumulate()
int sum = accumulate([Link](), [Link](), 0);
cout << "Sum of all elements: " << sum << endl;

// 3. find()
cout << "Enter a number to search: ";
cin >> value;
auto it = find([Link](), [Link](), value);
if (it != [Link]())
cout << value << " found at position: " << (it - [Link]()) << endl;
else
cout << value << " not found in the vector." << endl;

// 4. remove_if() + lambda
cout << "\nRemoving all odd numbers..." << endl;

[Link](remove_if([Link](), [Link](),
[](int x)
{ return x % 2 != 0; }),
[Link]());

cout << "Vector after removing odd numbers: ";


for (int x : vec)
cout << x << " ";
cout << endl;

return 0;
}

Output:
Q4)Create a program using pairs and vectors of pairs to store roll numbers and corresponding
marks for a set of students. Insert multiple pair<int, float> objects into a vector, sort the
vector based on marks using the STL sort() function, and finally display the sorted result.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
int n;
cout << "Enter number of students: ";
cin >> n;

vector<pair<int, float>> students;

// Input: Roll No. and Marks


for (int i = 0; i < n; i++)
{
int roll;
float marks;
cout << "Enter Roll No. and Marks for student " << i + 1 << ": ";
cin >> roll >> marks;
students.push_back(make_pair(roll, marks));
}

// Sort based on marks (ascending)


sort([Link](), [Link](),
[](const pair<int, float> &a, const pair<int, float> &b)
{
return [Link] < [Link]; // sort by marks
});

// Display sorted results


cout << "\nStudents sorted by marks:\n";
cout << "Roll No.\tMarks\n";
for (const auto &p : students)
{
cout << [Link] << "\t\t" << [Link] << endl;
}

return 0;
}

Output:
Q5)Write a program that implements a simple dictionary using the STL map container. The
program should allow the user to insert English words along with their meanings, search for
the meaning of a given word, display all dictionary entries in sorted order, and delete any
word requested by the user.

#include <iostream>
#include <map>
#include <string>

using namespace std;

int main()
{
map<string, string> dictionary;
int choice;
string word, meaning;

do
{
cout << "\n------ Simple Dictionary Menu ------\n";
cout << "1. Insert a word and its meaning\n";
cout << "2. Search for a word\n";
cout << "3. Display all dictionary entries\n";
cout << "4. Delete a word\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice)
{

case 1: // Insert
cout << "Enter word: ";
cin >> word;
[Link]();
cout << "Enter meaning: ";
getline(cin, meaning);

dictionary[word] = meaning;
cout << "Word added successfully!\n";
break;

case 2: // Search
cout << "Enter word to search: ";
cin >> word;

if ([Link](word) != [Link]())
{
cout << "Meaning of '" << word << "': "
<< dictionary[word] << endl;
}
else
{
cout << "Word not found in dictionary.\n";
}
break;

case 3: // Display
cout << "\n--- Dictionary Entries (Sorted) ---\n";
for (const auto &entry : dictionary)
{
cout << [Link] << " : " << [Link] << endl;
}
break;

case 4: // Delete
cout << "Enter word to delete: ";
cin >> word;

if ([Link](word))
{
cout << "Word deleted successfully.\n";
}
else
{
cout << "Word not found.\n";
}
break;

case 5:
cout << "Exiting...\n";
break;

default:
cout << "Invalid choice. Try again.\n";
}

} while (choice != 5);


return 0;
}

Output:
Q6)Develop a program to demonstrate the use of sets by taking fifteen integers from the user
and storing them in a set<int> to automatically eliminate duplicates. After displaying the
unique elements, perform insertion of a new value, deletion of an existing value, and display
the set in both ascending and descending order using iterators and reverse iterators.

#include <iostream>
#include <set>
using namespace std;

int main()
{
set<int> s;
int x;

// Step 1: Input 15 integers


cout << "Enter 15 integers:\n";
for (int i = 0; i < 15; i++)
{
cin >> x;
[Link](x);
}

// Display unique elements


cout << "\nUnique elements in the set:\n";
for (auto it = [Link](); it != [Link](); ++it)
{
cout << *it << " ";
}
cout << endl;

// Step 2: Insert a new value


cout << "\nEnter a value to insert: ";
cin >> x;
[Link](x);
cout << "Value inserted.\n";

// Display after insertion


cout << "Set after insertion:\n";
for (auto it = [Link](); it != [Link](); ++it)
{
cout << *it << " ";
}
cout << endl;
// Step 3: Delete a value
cout << "\nEnter a value to delete: ";
cin >> x;

if ([Link](x))
cout << "Value deleted successfully.\n";
else
cout << "Value not found in the set.\n";

// Display after deletion


cout << "Set after deletion:\n";
for (auto it = [Link](); it != [Link](); ++it)
{
cout << *it << " ";
}
cout << endl;

// Step 4: Display in ascending order


cout << "\nSet in ascending order:\n";
for (auto it = [Link](); it != [Link](); ++it)
{
cout << *it << " ";
}
cout << endl;

// Step 5: Display in descending order


cout << "Set in descending order:\n";
for (auto rit = [Link](); rit != [Link](); ++rit)
{
cout << *rit << " ";
}
cout << endl;

return 0;
}

Output:
Q7)Write a program that uses the STL adaptors stack and queue. Insert at least five integers
into a stack and pop two values, then insert five integers into a queue and dequeue two
values. Display the remaining elements in both the stack and queue to illustrate LIFO and
FIFO behavior.

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

int main()
{
stack<int> st;
queue<int> q;

// Stack operations (LIFO)


cout << "Pushing 5 values into stack: 10, 20, 30, 40, 50\n";
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

// Pop two values


cout << "Popping two values from stack...\n";
[Link]();
[Link]();

// Display remaining stack elements (LIFO)


cout << "Remaining stack elements (Top to Bottom):\n";
stack<int> tempSt = st;
while (![Link]())
{
cout << [Link]() << " ";
[Link]();
}
cout << endl
<< endl;

// Queue operations (FIFO)


cout << "Enqueuing 5 values into queue: 100, 200, 300, 400, 500\n";
[Link](100);
[Link](200);
[Link](300);
[Link](400);
[Link](500);

// Dequeue two values


cout << "Dequeuing two values from queue...\n";
[Link]();
[Link]();

// Display remaining queue elements


cout << "Remaining queue elements (Front to Rear):\n";
queue<int> tempQ = q;
while (![Link]())
{
cout << [Link]() << " ";
[Link]();
}
cout << endl;

return 0;
}

Output:
Q8)Create a program that uses an unordered map to count character frequencies in a given
string. Display the frequency of each character, then compare the performance of
unordered_map and map by measuring the time taken to perform the same operation using
both containers.

#include <iostream>
#include <unordered_map>
#include <map>
#include <string>
#include <chrono>

using namespace std;


using namespace std::chrono;

int main()
{

string text;

cout << "Enter a string: ";


getline(cin, text);

// CHARACTER FREQUENCY USING unordered_map


unordered_map<char, int> umap;

for (char c : text)


{
if (c != ' ')
umap[c]++;
}

cout << "\nCharacter frequencies using unordered_map:\n";


for (auto &p : umap)
{
cout << "'" << [Link] << "' : " << [Link] << endl;
}

// PERFORMANCE TEST: unordered_map


unordered_map<char, int> umap_test;

auto start1 = high_resolution_clock::now();


for (char c : text)
{
umap_test[c]++;
}
auto end1 = high_resolution_clock::now();
auto duration_unordered = duration_cast<nanoseconds>(end1 - start1).count();

// PERFORMANCE TEST: map


map<char, int> map_test;

auto start2 = high_resolution_clock::now();


for (char c : text)
{
map_test[c]++;
}
auto end2 = high_resolution_clock::now();
auto duration_map = duration_cast<nanoseconds>(end2 - start2).count();

// RESULTS
cout << "\nTime taken using unordered_map: "
<< duration_unordered << " ns" << endl;

cout << "Time taken using map: "


<< duration_map << " ns" << endl;

cout << "\nPerformance Observation:\n";


if (duration_unordered < duration_map)
{
cout << "unordered_map is faster (as expected due to hashing).\n";
}
else
{
cout << "map is faster in this case (depends on input size, data, and system).\n";
}

return 0;
}
Q9)Try: Write aprogram that demonstrates the internal memory behavior of vectors by
inserting integers one at a time into a vector and printing the size and capacity after every
insertion. Then erase elements and observe how the capacity behaves. Use the output to
explain how vectors manage memory dynamically.

#include <iostream>
#include <vector>
using namespace std;

int main()
{

vector<int> v;

cout << "Inserting elements one by one...\n\n";

// Insert 10 integers one at a time


for (int i = 1; i <= 10; i++)
{

v.push_back(i);

// printing what's happening internally


cout << "After inserting " << i << ": "
<< "size = " << [Link]()
<< ", capacity = " << [Link]() << endl;
}

cout << "\nNow erasing elements...\n\n";

// Erase elements one by one from the end


for (int i = 1; i <= 5; i++)
{

v.pop_back();

cout << "After removing " << i << " element(s): "
<< "size = " << [Link]()
<< ", capacity = " << [Link]() << endl;
}
return 0;
}

Output:
Q10)Try: Develop a program to demonstrate the use of custom comparators with the STL sort
algorithm. Create a vector of strings, display it in its original order, then sort it in default
lexicographical order. Next, sort the same vector using a user-defined comparator that
arranges strings based on their length. Display both sorted results to show the effect of
comparator-based sorting.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// custom comparator for sorting strings by length


bool sortByLength(const string &a, const string &b)
{
return [Link]() < [Link]();
}

int main()
{

vector<string> words = {
"apple", "cat", "banana", "dog", "watermelon", "hi"};

// showing original order


cout << "Original order:\n";
for (const auto &w : words)
{
cout << w << " ";
}
cout << "\n\n";

// sorting in default lexicographical order


sort([Link](), [Link]());

cout << "Sorted in default lexicographical order:\n";


for (const auto &w : words)
{
cout << w << " ";
}
cout << "\n\n";

// now sorting by length using our own comparator


sort([Link](), [Link](), sortByLength);
cout << "Sorted by length (using custom comparator):\n";
for (const auto &w : words)
{
cout << w << " ";
}
cout << "\n";

return 0;
}

Output:

You might also like