C++ Programming Examples: Templates, Data Structures, and Algorithms
C++ Programming Examples
Templates
Maximal Function
This template function returns the larger of two items:
template<typename item>
item maximal(item a, item b) {
if (a > b)
return a;
else
return b;
}
Swap Function
This template function swaps the values of two items:
template<typename item>
void swap(item& x, item& y) {
item temp = x;
x = y;
y = temp;
}
Linked Lists
Bag Class
This template class implements a bag data structure using a linked list:
template<typename item>
class bag {
public:
// ... (member functions)
private:
node *head_ptr;
size_type many_nodes;
};
Linked List Toolkit
This code provides functions for manipulating linked lists:
template<typename item>
void list_clear(node*& head_ptr); // Clears the linked list
// ... (other linked list functions)
Recursion
Power Function (Iterative)
This function calculates x raised to the power of n iteratively:
double power(double x, int n) {
// ... (implementation)
}
Power Function (Recursive)
This function calculates x raised to the power of n recursively:
double pow(double x, int n) {
// ... (implementation)
}
Queues
Queue Class
This template class implements a queue data structure:
template<typename T>
class queue {
public:
// ... (member functions)
private:
T data[array_size];
int front;
int back;
};
Palindrome Checker
This program checks if an input line is a palindrome, ignoring spaces, punctuation, and case:
int main() {
queue<char> q;
stack<char> s;
// ... (implementation)
}