Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔴 Advanced  ·  Lesson 59

STL Algorithms

STL Algorithm Model

Container elements own करता है, iterators range बताते हैं और algorithm operation करता है। इससे same find/count_if कई suitable containers पर reusable होता है।

std::vector<int> values{7,2,9,4};
std::sort(values.begin(),values.end());
FamilyExamples
Queriesfind, count, all_of
Transformcopy, transform, replace
Reorderreverse, rotate, shuffle
Sort/searchsort, lower_bound
Numericaccumulate, iota

Most algorithms के लिए <algorithm>, numeric के लिए <numeric> direct include करें। STL guide देखें।

Ranges और Iterator Requirements

[first,last) first include और last exclude करती है; end को dereference न करें।

AlgorithmIterator
find/countInput
copyReadable + writable output
reverseBidirectional
sortRandom access

इसलिए std::sort vector पर चलता है, list पर नहीं। C++20 range algorithms whole range और projection ले सकते हैं:

std::ranges::sort(students,std::greater{},&Student::mark);

Lazy views source को refer कर सकती हैं; source lifetime पर्याप्त हो। iterators पढ़ें।

Search, Count और Predicates

auto found=std::find(values.begin(),values.end(),9);
if(found!=values.end()) std::cout<<*found;
auto evens=std::count_if(values.begin(),values.end(),
 [](int n){return n%2==0;});
bool positive=std::all_of(values.begin(),values.end(),
 [](int n){return n>0;});
  • find/find_if first match या end।
  • count/count_if match count।
  • all_of सभी, any_of कोई एक, none_of कोई नहीं।
  • mismatch first different pair।

Predicate range invalidate न करे; simple, stable lambda रखें।

Transform, Copy और Remove

std::vector<int> doubled(values.size());
std::transform(values.begin(),values.end(),doubled.begin(),
 [](int n){return n*2;});
std::vector<int> result;
std::copy_if(values.begin(),values.end(),
 std::back_inserter(result),[](int n){return n>=0;});

Destination में space हो या insertion iterator लें। Erase-remove:

auto end=std::remove_if(values.begin(),values.end(),
 [](int n){return n<0;});
values.erase(end,values.end());
// C++20: std::erase_if(values,predicate);

remove_if vector size नहीं घटाता; logical end देता है।

Sorting और Binary Search

std::sort(values.begin(),values.end());
bool found=std::binary_search(values.begin(),values.end(),75);
auto first=std::lower_bound(values.begin(),values.end(),75);
  • sort equal order preserve नहीं करता।
  • stable_sort equivalent order preserve करता है।
  • partial_sort selected first part sort करता है।
  • nth_element nth को sorted position पर रखता है।
  • lower/upper_bound equivalent range की boundaries देते हैं।

Comparator strict weak ordering दे; <= गलत। Binary search के लिए compatible ordering/partition जरूरी है।

Numeric Algorithms और Types

long long total=std::accumulate(values.begin(),values.end(),0LL);
std::vector<int> ids(5);
std::iota(ids.begin(),ids.end(),101);

accumulate का initial value result type तय करता है: large integer sum में 0LL और floating case में 0.0 सोचकर चुनें।

AlgorithmUse
accumulateFold/sum
iotaIncreasing fill
inner_productPairwise fold
partial_sumRunning totals
reduceMay reorder operations
Floating-point rounding/order important हो तो reduce को accumulate का automatic replacement न मानें।

Complete Score Analysis और Output

std::vector<int> scores{64,91,75,52,88};
int total=std::accumulate(scores.begin(),scores.end(),0);
auto passed=std::count_if(scores.begin(),scores.end(),
 [](int s){return s>=75;});
std::sort(scores.begin(),scores.end(),std::greater<>{});
Descending: 91 88 75 64 52 Pass count: 3 Average: 74

Total 370 है। Pass predicate 75 include करता और comparator descending order देता है।

Mistakes, Practice और Review

MistakeCorrection
Unsorted binary searchCompatible order
list पर std::sortlist::sort
Returned end dereferenceCheck first
Destination no spaceResize/back_inserter
remove shrinks vectorErase tail
Comparator <=Strict weak order
Initial type wrong0LL/0.0

Practice: Student two-key sort, first failing mark, invalid score removal, running totals, top three और ranges comparison।

  1. Header?
  2. Valid range?
  3. Iterator capability?
  4. Precondition?
  5. Comparator?
  6. Destination?
  7. Return checked?
  8. Numeric type?

Authoritative संदर्भ

Requirements और preconditions current draft से verified हैं। vector तथा sorting/searching पर practice करें।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

C++ STL algorithms क्या हैं?
ये reusable standard-library function templates हैं जो iterator ranges या C++20 range objects पर search, count, copy, transform, partition और sort करते हैं।
Algorithms [first,last) range क्यों लेते हैं?
Half-open range first include और last exclude करती है। Empty range natural बनती है, adjacent ranges compose होती हैं और distance element count देता है।
क्या std::sort को std::list पर लगा सकते हैं?
नहीं। std::sort को random-access iterators चाहिए, जबकि list bidirectional iterators देती है। list::sort या suitable random-access container लें।
binary_search या lower_bound से पहले sorting जरूरी है?
Range same ordering के अनुसार partitioned होनी चाहिए; ordinary use में compatible comparator से sorted होना जरूरी है।
erase-remove idiom क्या है?
remove/remove_if retained elements compact करके logical end देता है, container छोटा नहीं करता। Trailing range erase करें या available होने पर std::erase_if लें।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicLambda Expressions आपकी प्रगति: 59 / 81 (73%) · Lesson 60 / 81 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें