STL-এ List কী?
List হল এমন কন্টেইনার যা সিকোয়েন্সের যেকোনো স্থানে কনস্ট্যান্ট টাইমে ইন্সারশন এবং ডিলিশন করার অনুমতি দেয়। লিস্টগুলো ডাবলি লিংকড লিস্ট হিসেবে ইমপ্লিমেন্ট করা হয়। লিস্ট নন-কন্টিগ্যুয়াস মেমোরি অ্যালোকেশন অনুমোদন করে। অ্যারে, ভেক্টর এবং ডিকের চেয়ে লিস্ট যেকোনো পজিশনে এলিমেন্ট ইন্সার্ট, এক্সট্রাক্ট এবং মুভ করার ক্ষেত্রে ভালো পারফরম করে। লিস্টে এলিমেন্টে ডায়রেক্ট অ্যাক্সেস ধীরগতির এবং লিস্ট forward_list-এর সাথে সাদৃশ্য রেখেছে, কিন্তু forward_list অবজেক্টগুলো সিঙ্গলি লিংকড লিস্ট এবং সেগুলো শুধু ফরওয়ার্ড দিয়ে ইটারেট করা যায়।
swap() কী?
এই ফাংশনটি একটি লিস্টের এলিমেন্টগুলো অন্য একটি লিস্টের সাথে সওয়াপ করতে ব্যবহৃত হয় এবং উভয়ের ডেটা টাইপ এবং সাইজ একই থাকে।
সিনট্যাক্স: listname1.swap(listname2)
উদাহরণ
Input List1: 50 60 80 90 List2: 90 80 70 60 Output After swapping operation List1: 90 80 70 60 List2: 50 60 80 90 Input List1: 45 46 47 48 49 List2: 50 51 52 53 54 Output After swapping Operation List1: 50 51 52 53 54 List2: 45 46 47 48 49
অনুসরণ করা পদ্ধতি
প্রথমে দুটি লিস্ট ইনিশিয়ালাইজ করুন।
তারপর দুটি লিস্ট প্রিন্ট করুন।
তারপর swap() ফাংশন ডিফাইন করুন।
শেষে সওয়াপিং অপারেশনের পর দুটি লিস্ট প্রিন্ট করুন।
উপরের পদ্ধতি ব্যবহার করে দুটি লিস্ট সওয়াপ করা যায়।
সম্পূর্ণ কোড উদাহরণ ১
// C++ code to demonstrate the working of list swap() function in STL
#include <iostream>
#include <list>
using namespace std;
int main() {
// initializing two lists
list<int> list1 = { 10, 20, 30, 40, 50 };
cout << " List1: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
list<int> list2 = { 40, 50, 60, 70, 80 };
cout << " List2: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
// defining swap() function
list1.swap(list2);
cout << " After swapping List1 is : ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
cout << " After swapping List2 is : ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
return 0;
}
আউটপুট
Input - List1: 10 20 30 40 50 List2: 40 50 60 70 80 Output - After swapping List1 is: 40 50 60 70 80 After swapping List2 is: 10 20 30 40 50
সম্পূর্ণ কোড উদাহরণ ২
// C++ code to demonstrate the working of list swap() function in STL
#include <iostream>
#include <list>
using namespace std;
int main() {
// initializing two lists
list<int> list1 = { 11, 12, 13, 14, 15 };
cout << " List1: ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
list<int> list2 = { 16, 17, 18, 19, 20 };
cout << " List2: ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
// defining swap() function
list1.swap(list2);
cout << " After swapping List1 is : ";
for(auto x = list1.begin(); x != list1.end(); ++x)
cout << *x << " ";
cout << " After swapping List2 is : ";
for(auto x = list2.begin(); x != list2.end(); ++x)
cout << *x << " ";
return 0;
}
আউটপুট
Input - List1: 11 12 13 14 15 List2: 16 17 18 19 20 Output - After swapping List1 is: 16 17 18 19 20 After swapping List2 is: 11 12 13 14 15