এই টিউটোরিয়ালে আমরা C++-এ STL সেটে উপাদান যোগ করা এবং মুছে ফেলার প্রক্রিয়া বোঝার জন্য একটি প্রোগ্রাম নিয়ে আলোচনা করব।
সেট কী?
সেট একটি কন্টেইনার উপাদান। এর অনন্য বৈশিষ্ট্যগুলো হলো এটি শুধুমাত্র অনন্য উপাদান ধারণ করতে পারে এবং সেগুলো সাজানো অবস্থায় লুপের মাধ্যমে অ্যাক্সেস করা যায়।
উদাহরণ: ইনসারশন (যোগ করা)
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> st;
// ইটেরেটর ডিক্লেয়ার করা
set<int>::iterator it = st.begin();
set<int>::iterator it1, it2;
pair< set<int>::iterator, bool> ptr;
// একক উপাদান যোগ করা
ptr = st.insert(20);
if (ptr.second)
cout << "The element was newly inserted";
else
cout << "The element was already present";
cout << "\nThe set elements after 1st insertion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
// নির্দিষ্ট পজিশনে ইনসার্ট (হিন্টসহ)
st.insert(it, 24);
cout << "\nThe set elements after 2nd insertion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
// অ্যারে থেকে একাধিক উপাদান যোগ করা
int arr[3] = { 25, 24, 26 };
st.insert(arr, arr + 3);
cout << "\nThe set elements after 3rd insertion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
return 0;
}
আউটপুট
The element was newly inserted The set elements after 1st insertion are : 20 The set elements after 2nd insertion are : 20 24 The set elements after 3rd insertion are : 20 24 25 26
উদাহরণ: ডিলিশন (মুছে ফেলা)
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> st;
// ইটেরেটর ডিক্লেয়ার করা
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
pair< set<int>::iterator, bool> ptr;
// সেটে মান যোগ করা
for (int i = 1; i < 10; i++)
st.insert(i * 5);
cout << "The set elements after insertion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
it = st.begin();
cout << endl;
++it; // দ্বিতীয় উপাদানে যাওয়া
st.erase(it); // ইটেরেটর দিয়ে মুছে ফেলা
// প্রথম ডিলিশনের পর সেটের উপাদান প্রিন্ট করা
cout << "The set elements after 1st deletion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
st.erase(40); // মান দিয়ে মুছে ফেলা
cout << "\nThe set elements after 2nd deletion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
++it; ++it; ++it; ++it; // কিছু ধাপ এগিয়ে যাওয়া
st.erase(it, st.end()); // রেঞ্জ দিয়ে মুছে ফেলা
cout << "\nThe set elements after 3rd deletion are : ";
for (it1 = st.begin(); it1 != st.end(); ++it1)
cout << *it1 << " ";
cout << endl;
return 0;
}
আউটপুট
The set elements after insertion are : 5 10 15 20 25 30 35 40 45 The set elements after 1st deletion are : 5 15 20 25 30 35 40 45 The set elements after 2nd deletion are : 5 15 20 25 30 35 45 The set elements after 3rd deletion are : 5 15 20