STL and Header File in C++
Complete Tutorial with Project Practice
1. What is STL in C++?
STL (Standard Template Library) គឺជាក្រុម Library ស្រាប់នៅក្នុង C++ ដែលផ្តល់ Data Structure និង Algorithms សម្រាប់ការសរសេរកម្មវិធី។
STL មាន 3 ផ្នែកសំខាន់៖
- Containers
- Algorithms
- Iterators
2. Vector Container
Vector គឺជា Dynamic Array ដែលអាចបន្ថែម Data បានដោយប្រើ push_back().
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
for(int i=0;i<numbers.size();i++)
{
cout<<numbers[i]<<endl;
}
return 0;
}
3. Stack Container
Stack ប្រើគោលការណ៍ LIFO (Last In First Out)
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
cout<<s.top();
return 0;
}
4. Queue Container
Queue ប្រើ FIFO (First In First Out)
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
cout<<q.front();
return 0;
}
5. Algorithms in STL
Algorithm Library ប្រើសម្រាប់ Sorting និង Searching
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> num = {5,2,8,1,9};
sort(num.begin(), num.end());
for(int x : num)
cout<<x<<" ";
return 0;
}
6. Header File in C++
Header File គឺជា File ដែលផ្ទុក Function Declaration និង Class Definition។
Example Header Files:
- iostream
- vector
- stack
- queue
- algorithm
7. Creating Custom Header File
#ifndef MATHFUNCTIONS_H #define MATHFUNCTIONS_H int add(int a,int b); int sub(int a,int b); #endif
8. Project Practice – Student Management System
Features:
- Add Student
- Display Student
- Search Student
#include <iostream>
#include <vector>
using namespace std;
class Student
{
public:
int id;
string name;
float score;
};
int main()
{
vector<Student> students;
Student s;
cout<<"Enter ID: ";
cin>>s.id;
cout<<"Enter Name: ";
cin>>s.name;
cout<<"Enter Score: ";
cin>>s.score;
students.push_back(s);
for(Student st : students)
{
cout<<st.id<<" "<<st.name<<" "<<st.score<<endl;
}
return 0;
}
9. Common STL Header Files
| Header | Purpose |
|---|---|
| vector | Dynamic Array |
| stack | Stack Data Structure |
| queue | Queue Data Structure |
| map | Key Value Pair |
| algorithm | Sorting and Searching |
No comments:
Post a Comment