id
stringclasses
50 values
testsource
stringclasses
6 values
language
stringclasses
6 values
prefix
stringlengths
16
3.39k
golden_completion
stringlengths
23
3.14k
suffix
stringlengths
0
2.68k
assertions
stringlengths
0
2.72k
category
stringclasses
6 values
1
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <iterator> std::vector<int> copy_positive_scores(const std::vector<int>& scores) { std::vector<int> out; std::copy_if(scores.begin(), scores.end(), std::back_inserter(out), [](int x) { return x > 0; }); re...
std::string describe_copy_positive_scores() { return "Returns a new vector by applying std::copy_if to the input range " "and writing through std::back_inserter. The predicate is evaluated " "exactly once per element, selected elements keep their relative order, " "and the source ve...
int main() { std::vector<int> scores = {-2, 5, 0, 7, -1, 9}; auto out = copy_positive_scores(scores); assert((out == std::vector<int>{5, 7, 9})); assert(scores[0] == -2 && scores.size() == 6); assert(!describe_copy_positive_scores().empty()); }
{ std::string d = describe_copy_positive_scores(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::copy_if") && "must name std::copy_if"); assert(has("std::back_inserter") && "must name the output iterator adaptor"); assert(has("exactly once") || has("once per element")...
code2NL_NL2code
2
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> bool advance_permutation_or_reset(std::vector<int>& values) { return std::next_permutation(values.begin(), values.end()); }
std::string describe_advance_permutation_or_reset() { return "Mutates the vector in place with std::next_permutation, producing " "the next lexicographic permutation under operator<. It returns true " "when such a permutation exists. If the range is already the last " "permutation, ...
int main() { std::vector<int> a = {1, 3, 2}; assert(advance_permutation_or_reset(a)); assert((a == std::vector<int>{2, 1, 3})); std::vector<int> b = {3, 2, 1}; assert(!advance_permutation_or_reset(b)); assert((b == std::vector<int>{1, 2, 3})); assert(!describe_advance_permutation_or_reset()...
{ std::string d = describe_advance_permutation_or_reset(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::next_permutation")); assert(has("lexicographic") || has("lexicographical")); assert(has("operator<") || has("less-than")); assert(has("in place") || has("in-place"...
code2NL_NL2code
3
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <iterator> #include <utility> std::pair<int, int> equal_range_indices(const std::vector<int>& sorted, int value) { auto bounds = std::equal_range(sorted.begin(), sorted.end(), value); return {static_cast<int>(std::distance(sor...
std::string describe_equal_range_indices() { return "Uses std::equal_range on a sorted non-decreasing vector and returns " "the half-open index interval [lower_bound, upper_bound) containing " "all elements equivalent to the value. The first iterator is the first " "element not less...
int main() { std::vector<int> v = {1, 2, 2, 2, 4, 6}; auto r = equal_range_indices(v, 2); assert(r.first == 1 && r.second == 4); auto missing = equal_range_indices(v, 3); assert(missing.first == 4 && missing.second == 4); assert(!describe_equal_range_indices().empty()); }
{ std::string d = describe_equal_range_indices(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::equal_range")); assert(has("sorted") || has("non-decreasing")); assert(has("half-open") || has("[lower_bound, upper_bound)")); assert(has("lower_bound")); assert(has("upper...
code2NL_NL2code
4
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <iterator> #include <random> std::vector<int> deterministic_sample(const std::vector<int>& population, std::size_t count, unsigned seed) { std::vector<int...
std::string describe_deterministic_sample() { return "Selects up to count elements without replacement using std::sample " "and a std::mt19937 UniformRandomBitGenerator seeded by the caller. " "The selected elements are copied through std::back_inserter, so the " "population is not ...
int main() { std::vector<int> pop = {1, 2, 3, 4, 5, 6}; auto a = deterministic_sample(pop, 3, 123); auto b = deterministic_sample(pop, 3, 123); assert(a == b); assert(a.size() == 3); assert(pop.size() == 6); assert(!describe_deterministic_sample().empty()); }
{ std::string d = describe_deterministic_sample(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::sample")); assert(has("std::mt19937")); assert(has("UniformRandomBitGenerator")); assert(has("without replacement")); assert(has("std::back_inserter")); assert(has("not mo...
code2NL_NL2code
5
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> std::size_t erase_closed_value_range(std::vector<int>& sorted, int low, int high) { auto first = std::lower_bound(sorted.begin(), sorted.end(), low); auto last = std::upper_bound(sorted.begin(), sorted.end(), high); std::size_t rem...
std::string describe_erase_closed_value_range() { return "For a sorted vector, finds a closed value range with std::lower_bound " "and std::upper_bound, then erases the half-open iterator range " "[first, last). low is included, high is included via upper_bound, " "and vector::erase...
int main() { std::vector<int> v = {1, 2, 2, 3, 4, 4, 5}; assert(erase_closed_value_range(v, 2, 4) == 5); assert((v == std::vector<int>{1, 5})); assert(!describe_erase_closed_value_range().empty()); }
{ std::string d = describe_erase_closed_value_range(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::lower_bound")); assert(has("std::upper_bound")); assert(has("sorted")); assert(has("closed value range") || has("low is included")); assert(has("half-open") || has("[f...
code2NL_NL2code
6
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <utility> void stable_sort_by_score(std::vector<std::pair<int, std::string>>& rows) { std::stable_sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.first < b.f...
std::string describe_stable_sort_by_score() { return "Sorts the vector in place with std::stable_sort using a comparator " "that compares only pair.first. Rows with equal scores preserve their " "original relative order, pair.second is not part of the ordering key, " "and the algori...
int main() { std::vector<std::pair<int, std::string>> rows = {{2, "b"}, {1, "x"}, {2, "a"}}; stable_sort_by_score(rows); assert(rows[0].second == "x"); assert(rows[1].second == "b"); assert(rows[2].second == "a"); assert(!describe_stable_sort_by_score().empty()); }
{ std::string d = describe_stable_sort_by_score(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::stable_sort")); assert(has("comparator")); assert(has("pair.first")); assert(has("pair.second") && (has("not part") || has("ignored"))); assert(has("relative order") || ha...
code2NL_NL2code
7
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <numeric> #include <iterator> std::vector<int> exclusive_square_offsets(const std::vector<int>& values) { std::vector<int> out(values.size()); std::transform_exclusive_scan(values.begin(), values.end(), out.begin(), ...
std::string describe_exclusive_square_offsets() { return "Uses std::transform_exclusive_scan: each input is first transformed " "by squaring, then combined by std::plus, but each output position " "contains the sum before the current transformed element. The first " "output is the i...
int main() { std::vector<int> v = {2, 3, 4}; auto out = exclusive_square_offsets(v); assert((out == std::vector<int>{0, 4, 13})); assert(v[0] == 2); assert(!describe_exclusive_square_offsets().empty()); }
{ std::string d = describe_exclusive_square_offsets(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::transform_exclusive_scan")); assert(has("squaring") || has("squared")); assert(has("std::plus")); assert(has("before the current") || has("excludes the current")); ass...
code2NL_NL2code
8
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <iterator> std::vector<int> rotate_copy_from_index(const std::vector<int>& values, std::size_t index) { std::vector<int> out; if (values.empty()) return out; index %= values.size(); ...
std::string describe_rotate_copy_from_index() { return "Builds a rotated copy with std::rotate_copy, writing through " "std::back_inserter and does not modify the input. The element at " "values.begin()+index becomes the first output element, followed by " "[middle, end) and then [b...
int main() { std::vector<int> v = {10, 20, 30, 40}; auto out = rotate_copy_from_index(v, 6); assert((out == std::vector<int>{30, 40, 10, 20})); assert(v[0] == 10); assert(!describe_rotate_copy_from_index().empty()); }
{ std::string d = describe_rotate_copy_from_index(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::rotate_copy")); assert(has("std::back_inserter")); assert(has("not modifying") || has("not modified") || has("does not modify")); assert(has("values.begin()+index") || h...
code2NL_NL2code
9
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <map> int add_or_create_count(std::map<std::string, int>& counts, const std::string& key, int delta) { auto [it, inserted] = counts.try_emplace(key, 0); it->second += delta; return inserted ? 0 : it->second - delt...
std::string describe_add_or_create_count() { return "Uses std::map::try_emplace to create a missing key with mapped value " "0 without overwriting an existing mapped value. The returned pair is " "an iterator and bool insertion flag; the iterator is then used to add " "delta. Becaus...
int main() { std::map<std::string, int> counts = {{"pear", 4}}; assert(add_or_create_count(counts, "apple", 3) == 0); assert(counts["apple"] == 3); assert(add_or_create_count(counts, "pear", 2) == 4); assert(counts["pear"] == 6); assert(!describe_add_or_create_count().empty()); }
{ std::string d = describe_add_or_create_count(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::map::try_emplace")); assert(has("missing key") || has("absent key")); assert(has("without overwriting") || has("no overwrite")); assert(has("iterator") && has("bool")); ass...
code2NL_NL2code
10
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <unordered_map> std::unordered_map<std::string, int> count_words_reserved(const std::vector<std::string>& words, std::size_t expected) { std::unordered_map<std::string, int> counts; counts.reserve(expected); for (const auto& word : words) { ...
std::string describe_count_words_reserved() { return "Counts words in a std::unordered_map after calling reserve(expected) " "to request enough buckets and reduce rehashing. operator[] inserts " "a missing string key with a value-initialized int of 0 before the " "preincrement. Aver...
int main() { std::vector<std::string> words = {"red", "blue", "red"}; auto counts = count_words_reserved(words, 8); assert(counts["red"] == 2); assert(counts["blue"] == 1); assert(!describe_count_words_reserved().empty()); }
{ std::string d = describe_count_words_reserved(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::unordered_map")); assert(has("reserve(expected)") || has("reserve")); assert(has("rehashing") || has("rehash")); assert(has("operator[]")); assert(has("value-initialized")...
code2NL_NL2code
11
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <set> void merge_unique_nodes(std::set<int>& destination, std::set<int>& source) { destination.merge(source); }
std::string describe_merge_unique_nodes() { return "Transfers nodes with std::set::merge from source into destination. " "Elements whose keys are not already present move without copying or " "moving the stored int values, while duplicates remain in the source. " "Both containers st...
int main() { std::set<int> dst = {1, 3}; std::set<int> src = {2, 3, 4}; merge_unique_nodes(dst, src); assert((dst == std::set<int>{1, 2, 3, 4})); assert((src == std::set<int>{3})); assert(!describe_merge_unique_nodes().empty()); }
{ std::string d = describe_merge_unique_nodes(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::set::merge")); assert(has("nodes")); assert(has("without copying") || has("without copy")); assert(has("duplicates remain") || has("remain in the source")); assert(has("sour...
code2NL_NL2code
12
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <list> #include <vector> void splice_all_to_front(std::list<int>& destination, std::list<int>& source) { destination.splice(destination.begin(), source); } std::vector<int> as_vector(const std::list<int>& xs) { return std::vector<int>(xs.begin(), xs.end()); }
std::string describe_splice_all_to_front() { return "Moves all nodes from source to the front of destination with " "std::list::splice. This relinks existing list nodes in O(1) time for " "the whole-list overload, performs no element copy or allocation, " "leaves source empty, and k...
int main() { std::list<int> dst = {3, 4}; std::list<int> src = {1, 2}; splice_all_to_front(dst, src); assert((as_vector(dst) == std::vector<int>{1, 2, 3, 4})); assert(src.empty()); assert(!describe_splice_all_to_front().empty()); }
{ std::string d = describe_splice_all_to_front(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::list::splice")); assert(has("nodes")); assert(has("O(1)") || has("constant time")); assert(has("no element copy") || has("no copy")); assert(has("allocation") || has("alloc...
code2NL_NL2code
13
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <memory> int replace_unique_value(std::unique_ptr<int>& ptr, int new_value) { int* raw = ptr.release(); int old_value = *raw; delete raw; ptr.reset(new int(new_value)); return old_value; }
std::string describe_replace_unique_value() { return "Uses std::unique_ptr::release to give up ownership and return the " "raw pointer without deleting it, leaving the unique_ptr empty. The " "raw pointer is manually deleted, then std::unique_ptr::reset takes " "ownership of a newly...
int main() { auto p = std::make_unique<int>(5); assert(replace_unique_value(p, 9) == 5); assert(p && *p == 9); assert(!describe_replace_unique_value().empty()); }
{ std::string d = describe_replace_unique_value(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::unique_ptr::release")); assert(has("raw pointer")); assert(has("without deleting") || has("does not delete")); assert(has("empty") || has("nullptr")); assert(has("manually...
code2NL_NL2code
14
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <memory> struct ScoreBox { int score; int penalty; }; std::shared_ptr<int> alias_score(const std::shared_ptr<ScoreBox>& owner) { return std::shared_ptr<int>(owner, &owner->score); }
std::string describe_alias_score() { return "Creates an aliasing std::shared_ptr<int> that shares the control block " "and reference count of the owning std::shared_ptr<ScoreBox> while " "storing a pointer to the score subobject. The ScoreBox lifetime is " "kept alive by the alias, ...
int main() { auto owner = std::make_shared<ScoreBox>(ScoreBox{42, 7}); auto score = alias_score(owner); assert(*score == 42); owner.reset(); assert(*score == 42); *score = 50; assert(!describe_alias_score().empty()); }
{ std::string d = describe_alias_score(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("aliasing")); assert(has("std::shared_ptr<int>")); assert(has("control block")); assert(has("reference count") || has("use_count")); assert(has("score subobject") || has("subobject")); a...
code2NL_NL2code
15
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <optional> int counted_default(int& calls) { ++calls; return 99; } int value_or_counted_default(std::optional<int> value, int& calls) { return value.value_or(counted_default(calls)); }
std::string describe_value_or_counted_default() { return "Returns value.value_or(counted_default(calls)). The fallback argument " "is evaluated before std::optional::value_or is called, so calls is " "incremented even when the optional already contains a value. value_or " "returns t...
int main() { int calls = 0; assert(value_or_counted_default(std::optional<int>{7}, calls) == 7); assert(calls == 1); assert(value_or_counted_default(std::optional<int>{}, calls) == 99); assert(calls == 2); assert(!describe_value_or_counted_default().empty()); }
{ std::string d = describe_value_or_counted_default(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::optional::value_or")); assert(has("fallback argument") || has("provided default")); assert(has("evaluated before") || has("eager")); assert(has("even when the optional...
code2NL_NL2code
16
devbench-code2NL-NL2code
cpp
#include <any> #include <cassert> #include <string> std::string bump_if_int(std::any& value) { if (int* p = std::any_cast<int>(&value)) { ++(*p); return "int"; } return "other"; }
std::string describe_bump_if_int() { return "Uses the pointer overload std::any_cast<int>(&value), which returns " "a pointer to the contained int on an exact type match and nullptr on " "a mismatch instead of throwing. The returned pointer is mutable here, " "so the contained int i...
int main() { std::any a = 4; assert(bump_if_int(a) == "int"); assert(std::any_cast<int>(a) == 5); std::any b = std::string("4"); assert(bump_if_int(b) == "other"); assert(!describe_bump_if_int().empty()); }
{ std::string d = describe_bump_if_int(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::any_cast<int>(&value)") || has("std::any_cast<int>")); assert(has("pointer overload")); assert(has("exact type match")); assert(has("nullptr")); assert(has("instead of throwing") |...
code2NL_NL2code
17
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <variant> #include <type_traits> using Metric = std::variant<int, double, std::string>; std::string metric_tag(const Metric& metric) { return std::visit([](const auto& value) -> std::string { using T = std::decay_t<decltype(value)>; if constexpr (std::...
std::string describe_metric_tag() { return "Dispatches on the active alternative of a std::variant with " "std::visit. A generic lambda receives the held value, if constexpr " "selects the branch at compile time from the decayed type, and every " "alternative returns the same std::s...
int main() { assert(metric_tag(Metric{3}) == "int"); assert(metric_tag(Metric{2.5}) == "double"); assert(metric_tag(Metric{std::string("x")}) == "string"); assert(!describe_metric_tag().empty()); }
{ std::string d = describe_metric_tag(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::variant")); assert(has("std::visit")); assert(has("active alternative")); assert(has("generic lambda")); assert(has("if constexpr")); assert(has("decayed type") || has("std::decay_t...
code2NL_NL2code
18
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <string_view> std::string_view trim_marker_view(std::string_view text) { if (!text.empty() && text.front() == '#') { text.remove_prefix(1); } if (!text.empty() && text.back() == '!') { text.remove_suffix(1); } return text; }
std::string describe_trim_marker_view() { return "Trims marker characters by mutating only the std::string_view object: " "remove_prefix drops a leading # and remove_suffix drops a trailing !. " "The underlying string is not modified; this is a non-owning view, no allocation occurs, " ...
int main() { std::string s = "#hello!"; auto view = trim_marker_view(s); assert(view == "hello"); assert(s == "#hello!"); assert(!describe_trim_marker_view().empty()); }
{ std::string d = describe_trim_marker_view(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::string_view")); assert(has("remove_prefix")); assert(has("remove_suffix")); assert(has("underlying string is not modified") || has("not modified")); assert(has("not owned") ||...
code2NL_NL2code
19
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <sstream> std::vector<std::string> split_semicolon_fields(const std::string& text) { std::vector<std::string> fields; std::istringstream input(text); std::string field; while (std::getline(input, field, ';')) { fields.push_back(fie...
std::string describe_split_semicolon_fields() { return "Tokenizes an std::istringstream with std::getline using ';' as the " "delimiter. The delimiter is consumed and not stored in the field, " "characters are not trimmed, and adjacent delimiters produce an empty " "string field. Ex...
int main() { auto fields = split_semicolon_fields("alpha;; beta;gamma"); assert((fields == std::vector<std::string>{"alpha", "", " beta", "gamma"})); assert(!describe_split_semicolon_fields().empty()); }
{ std::string d = describe_split_semicolon_fields(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::istringstream")); assert(has("std::getline")); assert(has("';'") || has("semicolon")); assert(has("delimiter is consumed") || has("delimiter is discarded")); assert(has(...
code2NL_NL2code
20
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <sstream> #include <iomanip> std::string format_fixed_cents(double value) { std::ostringstream out; out << std::fixed << std::setprecision(2) << value; return out.str(); }
std::string describe_format_fixed_cents() { return "Formats into an std::ostringstream using std::fixed and " "std::setprecision(2). With fixed notation, precision means exactly " "two digits after the decimal point, so the stream rounds as needed " "and pads trailing zeros. The man...
int main() { assert(format_fixed_cents(12.3) == "12.30"); assert(format_fixed_cents(0.0) == "0.00"); assert(!describe_format_fixed_cents().empty()); }
{ std::string d = describe_format_fixed_cents(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::ostringstream")); assert(has("std::fixed")); assert(has("std::setprecision(2)")); assert(has("fixed notation") || has("fixed")); assert(has("two digits after the decimal"));...
code2NL_NL2code
21
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <mutex> struct Wallets { int left; int right; std::mutex left_mutex; std::mutex right_mutex; }; void transfer_with_scoped_lock(Wallets& wallets, int amount) { std::scoped_lock lock(wallets.left_mutex, wallets.right_mutex); wallets.left -= amount; ...
std::string describe_transfer_with_scoped_lock() { return "Locks both wallet mutexes with C++17 std::scoped_lock before moving " "the amount. scoped_lock uses deadlock-avoidance for multiple mutexes, " "acquires them in its constructor, and releases them by RAII in its " "destructor...
int main() { Wallets wallets{10, 1}; transfer_with_scoped_lock(wallets, 4); assert(wallets.left == 6); assert(wallets.right == 5); assert(!describe_transfer_with_scoped_lock().empty()); }
{ std::string d = describe_transfer_with_scoped_lock(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::scoped_lock")); assert(has("C++17")); assert(has("both") && has("mutexes")); assert(has("deadlock-avoidance") || has("deadlock avoidance")); assert(has("constructor")...
code2NL_NL2code
22
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <mutex> bool deferred_unique_lock_transition(std::mutex& mutex) { std::unique_lock<std::mutex> lock(mutex, std::defer_lock); bool before = lock.owns_lock(); lock.lock(); bool after = lock.owns_lock(); lock.unlock(); return !before && after && !lock....
std::string describe_deferred_unique_lock_transition() { return "Constructs a movable std::unique_lock with std::defer_lock, so the " "mutex is not locked at construction and owns_lock is initially false. " "Calling lock() acquires the mutex and makes owns_lock true; calling " "unlo...
int main() { std::mutex mutex; assert(deferred_unique_lock_transition(mutex)); assert(!describe_deferred_unique_lock_transition().empty()); }
{ std::string d = describe_deferred_unique_lock_transition(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::unique_lock")); assert(has("std::defer_lock")); assert(has("not locked at construction") || has("does not lock")); assert(has("owns_lock")); assert(has("initial...
code2NL_NL2code
23
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <future> std::future<int> make_ready_future(int value) { std::promise<int> promise; auto future = promise.get_future(); promise.set_value(value); return future; }
std::string describe_make_ready_future() { return "Creates a std::promise<int>, obtains its associated std::future with " "get_future, then makes the shared state ready with set_value before " "returning the future. future::get retrieves that value, blocks until " "ready if necessar...
int main() { auto future = make_ready_future(31); assert(future.valid()); assert(future.get() == 31); assert(!future.valid()); assert(!describe_make_ready_future().empty()); }
{ std::string d = describe_make_ready_future(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::promise<int>")); assert(has("std::future")); assert(has("get_future")); assert(has("set_value")); assert(has("shared state")); assert(has("ready")); assert(has("future::get")...
code2NL_NL2code
24
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <regex> std::vector<std::string> full_match_groups(const std::string& text, const std::regex& pattern) { std::smatch match; if (!std::regex_match(text, match, pattern)) { return {}; } std:...
std::string describe_full_match_groups() { return "Uses std::regex_match, so the entire input sequence must match the " "regular expression; unlike std::regex_search, a substring match is " "not enough. The std::smatch stores sub_match entries where group 0 is " "the whole match and...
int main() { std::regex re("([A-Z]+)-(\\d+)"); auto groups = full_match_groups("ABC-42", re); assert((groups == std::vector<std::string>{"ABC-42", "ABC", "42"})); assert(full_match_groups("xABC-42y", re).empty()); assert(!describe_full_match_groups().empty()); }
{ std::string d = describe_full_match_groups(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::regex_match")); assert(has("entire input") || has("entire sequence")); assert(has("std::regex_search")); assert(has("substring match") || has("not enough")); assert(has("std:...
code2NL_NL2code
25
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <queue> #include <vector> int take_priority_top(std::priority_queue<int>& queue) { int value = queue.top(); queue.pop(); return value; }
std::string describe_take_priority_top() { return "Reads the largest element from the default std::priority_queue<int> " "with top(), then removes it with pop() and returns the saved value. " "The default comparator is std::less, making it a max-heap adapter over " "an underlying co...
int main() { std::priority_queue<int> q; q.push(4); q.push(9); q.push(1); assert(take_priority_top(q) == 9); assert(q.top() == 4); assert(!describe_take_priority_top().empty()); }
{ std::string d = describe_take_priority_top(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::priority_queue<int>")); assert(has("top()")); assert(has("pop()")); assert(has("std::less")); assert(has("max-heap")); assert(has("adapter") || has("underlying container")); ...
code2NL_NL2code
26
devbench-code2NL-NL2code
cpp
#include <cassert> #include <string> #include <vector> #include <numeric> std::string join_with_slashes(const std::vector<std::string>& parts) { if (parts.empty()) { return ""; } return std::accumulate(std::next(parts.begin()), parts.end(), parts.front(), [](std::string a...
std::string describe_join_with_slashes() { return "Joins strings with std::accumulate as a left fold. The initial value " "is parts.front(), so the accumulator type is std::string and no slash " "is added before the first element; the binary operation is called once " "for each rema...
int main() { std::vector<std::string> parts = {"usr", "local", "bin"}; assert(join_with_slashes(parts) == "usr/local/bin"); assert(join_with_slashes({}) == ""); assert(!describe_join_with_slashes().empty()); }
{ std::string d = describe_join_with_slashes(); auto has = [&](const std::string& s) { return d.find(s) != std::string::npos; }; assert(has("std::accumulate")); assert(has("left fold")); assert(has("initial value") && has("parts.front()")); assert(has("accumulator type") && has("std::string")); assert(has("no slash") &...
code2NL_NL2code
27
devbench-code2NL-NL2code
cpp
#include <vector> #include <algorithm> #include <string> #include <cassert> bool is_permutation_check(const std::vector<int>& a, const std::vector<int>& b) { return std::is_permutation(a.begin(), a.end(), b.begin(), b.end()); } std::string describe_is_permutation_check() {
return "Checks whether one vector is a permutation of the other using " "std::is_permutation. This performs a multiset equality comparison: " "both vectors must contain exactly the same elements with the " "same multiplicities, regardless of order. The algorithm has " "O(...
} int main() { std::vector<int> a = {1, 2, 3, 4}; std::vector<int> b = {4, 3, 2, 1}; assert(is_permutation_check(a, b) == true); std::vector<int> c = {1, 2, 3, 5}; assert(is_permutation_check(a, c) == false); std::string doc = describe_is_permutation_check(); assert(doc.size() > 10); ...
std::string d = describe_is_permutation_check(); std::string dl; for (char c : d) dl += std::tolower(c); assert((dl.find("is_permutation") != std::string::npos || dl.find("is permutation") != std::string::npos) && "must mention is_permutation"); assert((dl.find("n") != std::string::npos && (dl.find...
code2NL_NL2code
28
devbench-code2NL-NL2code
cpp
#include <string> #include <sstream> #include <cassert> /** * @brief Checks if a string is a valid IPv4 address. * * A valid IPv4 address consists of exactly 4 decimal octets separated by * dots. Each octet is an integer in the range [0, 255] with no leading * zeros (except the single digit "0" itself). The strin...
std::istringstream iss(s); std::string octet; int count = 0; while (std::getline(iss, octet, '.')) { count++; if (count > 4 || octet.empty() || octet.size() > 3) return false; if (octet.size() > 1 && octet[0] == '0') return false; // leading zero for (char c : octet) if ...
} int main() { assert(is_valid_ipv4("192.168.1.1") == true); assert(is_valid_ipv4("255.255.255.255") == true); assert(is_valid_ipv4("0.0.0.0") == true); assert(is_valid_ipv4("256.1.1.1") == false); assert(is_valid_ipv4("1.2.3") == false); return 0; }
assert(is_valid_ipv4("01.01.01.01") == false && "leading zeros invalid"); assert(is_valid_ipv4("1.2.3.4.5") == false && "too many octets"); assert(is_valid_ipv4("") == false && "empty string"); assert(is_valid_ipv4("1.2.3.") == false && "trailing dot"); assert(is_valid_ipv4("1.2.3.4 ") == false && ...
code2NL_NL2code
29
devbench-code2NL-NL2code
cpp
#include <string> #include <unordered_map> #include <cassert> /** * @brief Converts a Roman numeral string to its integer value. * * Supports the standard Roman numerals: I(1), V(5), X(10), L(50), * C(100), D(500), M(1000). Uses the subtractive rule: when a smaller * value appears immediately before a larger valu...
std::unordered_map<char, int> vals = { {'I',1},{'V',5},{'X',10},{'L',50}, {'C',100},{'D',500},{'M',1000}}; int result = 0; for (int i = 0; i < (int)s.size(); i++) { if (i + 1 < (int)s.size() && vals[s[i]] < vals[s[i+1]]) result -= vals[s[i]]; else resu...
} int main() { assert(roman_to_int("III") == 3); assert(roman_to_int("IV") == 4); assert(roman_to_int("IX") == 9); assert(roman_to_int("XLII") == 42); assert(roman_to_int("MCMXCIV") == 1994); return 0; }
assert(roman_to_int("") == 0 && "empty string returns 0"); assert(roman_to_int("MMMCMXCIX") == 3999 && "max standard value"); assert(roman_to_int("DCCCXC") == 890); assert(roman_to_int("CDXLIV") == 444); assert(roman_to_int("CM") == 900); assert(roman_to_int("XC") == 90); assert(roman_to_in...
code2NL_NL2code
30
devbench-code2NL-NL2code
cpp
#include <vector> #include <utility> #include <algorithm> #include <cassert> /** * @brief Finds all unique pairs of values in a vector that sum to a target. * * Each pair is reported as (smaller, larger). Pairs are returned in * ascending order of the smaller element, then by the larger element. * Duplicate pairs...
auto sn = nums; std::sort(sn.begin(), sn.end()); std::vector<std::pair<int,int>> res; for (int lo = 0, hi = (int)sn.size()-1; lo < hi; ) { int s = sn[lo] + sn[hi]; if (s < target) { lo++; continue; } if (s > target) { hi--; continue; } res.push_back({sn[lo], sn[hi]}); ...
} int main() { auto r1 = find_pairs_sum({1, 2, 3, 4, 5}, 6); assert(r1.size() == 2); // (1,5) and (2,4) assert(r1[0] == std::make_pair(1, 5)); assert(r1[1] == std::make_pair(2, 4)); auto r2 = find_pairs_sum({1, 1, 2, 3}, 4); assert(r2.size() == 1); // (1,3) only once return 0; }
// self-pairing auto rr1 = find_pairs_sum({2, 2, 2}, 4); assert(rr1.size() == 1 && rr1[0] == std::make_pair(2, 2) && "self-pair with duplicates"); // no pairs auto rr2 = find_pairs_sum({1, 2, 3}, 100); assert(rr2.empty() && "no pairs exist"); // empty input auto rr3 = find_pairs_sum({...
code2NL_NL2code
31
devbench-code2NL-NL2code
cpp
#include <string> #include <queue> #include <vector> #include <cassert> #include <algorithm> int extract_max(std::priority_queue<int>& pq) { int val = pq.top(); pq.pop(); return val; }
std::string describe_extract_max() { return "Extracts and returns the maximum element from an std::priority_queue " "(which is a max-heap by default). Calls top() to read the largest " "element, then pop() to remove it. pop() itself returns void, so " "the two-step top-then-pop patt...
int main() { std::priority_queue<int> pq; pq.push(10); pq.push(30); pq.push(20); assert(extract_max(pq) == 30); assert(extract_max(pq) == 20); std::string doc = describe_extract_max(); assert(doc.size() > 20); return 0; }
std::string d31 = describe_extract_max(); // Convert to lowercase for comparison std::string d31l = d31; std::transform(d31l.begin(), d31l.end(), d31l.begin(), ::tolower); assert(d31l.find("max") != std::string::npos || d31l.find("largest") != std::string::npos); assert(d31l.find("top") != std::...
code2NL_NL2code
32
devbench-code2NL-NL2code
cpp
#include <string> #include <map> #include <cassert> #include <algorithm> std::map<int,std::string>::iterator insert_with_hint( std::map<int,std::string>& m, std::map<int,std::string>::iterator hint, int key, const std::string& value) { return m.emplace_hint(hint, key, value); }
std::string describe_insert_with_hint() { return "Inserts a key-value pair into an std::map using emplace_hint. " "When the hint iterator points to the position just after where the " "new element will be inserted, the operation runs in amortized O(1) " "time instead of O(log n). Re...
int main() { std::map<int,std::string> m; m[1] = "one"; m[3] = "three"; auto hint = m.find(3); auto it = insert_with_hint(m, hint, 2, "two"); assert(it->second == "two"); assert(m.size() == 3); // Inserting duplicate key returns existing auto it2 = insert_with_hint(m, m.end(), 2, "...
std::string d32 = describe_insert_with_hint(); std::string d32l = d32; std::transform(d32l.begin(), d32l.end(), d32l.begin(), ::tolower); assert(d32l.find("emplace_hint") != std::string::npos || d32l.find("emplace hint") != std::string::npos); assert(d32l.find("amortized") != std::string::npos); ...
code2NL_NL2code
33
devbench-code2NL-NL2code
cpp
#include <string> #include <cassert> #include <algorithm> size_t find_last_occurrence(const std::string& haystack, const std::string& needle, size_t pos) { return haystack.rfind(needle, pos); }
std::string describe_find_last_occurrence() { return "Searches for the last occurrence of needle in haystack by delegating " "to std::string::rfind, which scans backwards from the given position. " "The pos parameter limits the search to positions at or before pos " "(i.e., only sub...
int main() { assert(find_last_occurrence("abcabc", "abc", 5) == 3); assert(find_last_occurrence("abcabc", "abc", 2) == 0); assert(find_last_occurrence("abcabc", "xyz", 5) == std::string::npos); std::string doc = describe_find_last_occurrence(); assert(doc.size() > 20); return 0; }
std::string d33 = describe_find_last_occurrence(); std::string d33l = d33; std::transform(d33l.begin(), d33l.end(), d33l.begin(), ::tolower); assert(d33l.find("rfind") != std::string::npos); assert(d33l.find("backward") != std::string::npos || d33l.find("reverse") != std::string::npos || d33l.find("...
code2NL_NL2code
34
devbench-code2NL-NL2code
cpp
#include <string> #include <vector> #include <cassert> #include <algorithm> void prepare_vector(std::vector<int>& v, size_t n) { v.reserve(n); } void fill_vector(std::vector<int>& v, size_t n, int val) { v.resize(n, val); }
std::string describe_prepare_vs_fill() { return "prepare_vector calls reserve, which allocates memory for at least n " "elements but does NOT change the vector's size or construct any elements. " "The size remains 0 and accessing elements would be undefined behavior. " "fill_vector ...
int main() { std::vector<int> v1; prepare_vector(v1, 100); assert(v1.size() == 0); assert(v1.capacity() >= 100); std::vector<int> v2; fill_vector(v2, 5, 42); assert(v2.size() == 5); assert(v2[0] == 42); fill_vector(v2, 2, 0); assert(v2.size() == 2); std::string doc = desc...
std::string d34 = describe_prepare_vs_fill(); std::string d34l = d34; std::transform(d34l.begin(), d34l.end(), d34l.begin(), ::tolower); assert(d34l.find("reserve") != std::string::npos); assert(d34l.find("resize") != std::string::npos); assert(d34l.find("capacity") != std::string::npos || d34l....
code2NL_NL2code
35
devbench-code2NL-NL2code
cpp
#include <string> #include <memory> #include <cassert> #include <algorithm> #include <functional> int delete_count = 0; std::shared_ptr<int> make_tracked(int value) { return std::shared_ptr<int>(new int(value), [](int* p) { delete_count++; delete p; }); }
std::string describe_make_tracked() { return "Creates a shared_ptr with a custom deleter lambda that increments " "delete_count before freeing the memory. The custom deleter is " "type-erased: it is stored internally and does not affect the " "shared_ptr's type signature (still shar...
int main() { delete_count = 0; { auto p1 = make_tracked(42); assert(*p1 == 42); { auto p2 = p1; // shared ownership assert(p1.use_count() == 2); } assert(delete_count == 0); // not deleted yet } assert(delete_count == 1); std::strin...
std::string d35 = describe_make_tracked(); std::string d35l = d35; std::transform(d35l.begin(), d35l.end(), d35l.begin(), ::tolower); assert(d35l.find("custom deleter") != std::string::npos || d35l.find("custom delete") != std::string::npos); assert(d35l.find("type-erase") != std::string::npos || d3...
code2NL_NL2code
36
devbench-code2NL-NL2code
cpp
#include <string> #include <regex> #include <cassert> #include <algorithm> bool check_full(const std::string& s, const std::regex& re, std::smatch& m) { return std::regex_match(s, m, re); } bool check_partial(const std::string& s, const std::regex& re, std::smatch& m) { return std::regex_search(s, m, re); }
std::string describe_check_functions() { return "check_full uses std::regex_match, which succeeds only if the ENTIRE " "input string matches the regular expression (an implicit ^ and $ " "anchor the pattern). check_partial uses std::regex_search, which " "succeeds if ANY substring o...
int main() { std::regex re("(\\d+)"); std::smatch m; assert(!check_full("abc123def", re, m)); assert(check_full("123", re, m)); assert(m[1].str() == "123"); assert(check_partial("abc123def", re, m)); assert(m[1].str() == "123"); std::string doc = describe_check_functions(); asser...
std::string d36 = describe_check_functions(); std::string d36l = d36; std::transform(d36l.begin(), d36l.end(), d36l.begin(), ::tolower); assert(d36l.find("regex_match") != std::string::npos); assert(d36l.find("regex_search") != std::string::npos); assert(d36l.find("entire") != std::string::npos ...
code2NL_NL2code
37
devbench-code2NL-NL2code
cpp
#include <string> #include <mutex> #include <condition_variable> #include <cassert> #include <algorithm> #include <thread> std::mutex mtx; std::condition_variable cv; bool ready = false; void wait_for_signal() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, []{ return ready; }); } void send_signal() ...
std::string describe_wait_for_signal() { return "Waits on a condition_variable using the predicate overload of wait(). " "The mutex must be locked (via unique_lock) before calling wait. " "wait() atomically releases the mutex and blocks the thread. " "On wakeup, the mutex is re-acqu...
int main() { ready = false; std::thread t([]{ send_signal(); }); wait_for_signal(); assert(ready == true); t.join(); std::string doc = describe_wait_for_signal(); assert(doc.size() > 20); return 0; }
std::string d37 = describe_wait_for_signal(); std::string d37l = d37; std::transform(d37l.begin(), d37l.end(), d37l.begin(), ::tolower); assert(d37l.find("spurious") != std::string::npos); assert(d37l.find("predicate") != std::string::npos); assert(d37l.find("mutex") != std::string::npos); a...
code2NL_NL2code
38
devbench-code2NL-NL2code
cpp
#include <list> #include <unordered_map> #include <cassert> #include <utility> /** * @brief Implements a fixed-capacity LRU cache. * * Uses a doubly-linked list (std::list) to track access order (most-recent * at front) and an unordered_map for O(1) key lookup. Supports: * - get(key): returns value or -1 if abs...
int get(int key) { auto it = index.find(key); if (it == index.end()) return -1; items.splice(items.begin(), items, it->second); return it->second->second; } void put(int key, int value) { auto it = index.find(key); if (it != index.end()) { it->second->second = value; items.sp...
private: int cap; std::list<std::pair<int,int>> items; std::unordered_map<int, std::list<std::pair<int,int>>::iterator> index; }; int main() { LRUCache cache(2); cache.put(1, 10); cache.put(2, 20); assert(cache.get(1) == 10); cache.put(3, 30); // evicts key 2 assert(cache.get(2) ==...
// Extra LRU tests LRUCache c2(2); c2.put(1, 1); c2.put(2, 2); c2.put(1, 10); // update key 1 assert(c2.get(1) == 10); c2.put(3, 3); // should evict key 2 (LRU) assert(c2.get(2) == -1); assert(c2.get(3) == 3); LRUCache c3(1); c3.put(1, 1); c3.put(2, 2); // evicts 1 a...
code2NL_NL2code
39
devbench-code2NL-NL2code
cpp
#include <stack> #include <string> #include <sstream> #include <cassert> #include <vector> /** * @brief Evaluates a postfix (Reverse Polish Notation) expression. * * Tokens are space-separated. Operands are integers (possibly negative). * Supported operators: +, -, *, / * Division truncates toward zero (C++ integ...
int eval_rpn(const std::vector<std::string>& tokens) { std::stack<int> st; for (const auto& tok : tokens) { if (tok=="+"||tok=="-"||tok=="*"||tok=="/") { int b = st.top(); st.pop(); int a = st.top(); st.pop(); if (tok=="+") st.push(a+b); else if (tok=="-") st.push(a-b); ...
int main() { assert(eval_rpn({"2", "3", "+"}) == 5); assert(eval_rpn({"4", "13", "5", "/", "+"}) == 6); assert(eval_rpn({"3", "4", "*", "2", "-"}) == 10); return 0; }
// Single number assert(eval_rpn({"42"}) == 42); // Negative result assert(eval_rpn({"1", "5", "-"}) == -4); // Division truncation toward zero assert(eval_rpn({"7", "2", "/"}) == 3); assert(eval_rpn({"-7", "2", "/"}) == -3); // Complex expression: ((2+3)*(8-4)) = 20 assert(eval_rpn(...
code2NL_NL2code
40
devbench-code2NL-NL2code
cpp
#include <string> #include <cassert> /** * @brief Compresses a string using run-length encoding. * * Consecutive identical characters are replaced by the character followed * by its count. Single occurrences still get a count of 1. * Examples: * "aaabbc" -> "a3b2c1" * "a" -> "a1" * "" -> ""...
std::string rle_compress(const std::string& s) { if (s.empty()) return ""; std::string result; int count = 1; for (size_t i = 1; i <= s.size(); ++i) { if (i < s.size() && s[i] == s[i-1]) { ++count; } else { result += s[i-1]; result += std::to_string(count); count = 1; } } return ...
int main() { assert(rle_compress("aaabbc") == "a3b2c1"); assert(rle_compress("a") == "a1"); assert(rle_compress("") == ""); assert(rle_compress("aaa") == "a3"); return 0; }
assert(rle_compress("abcd") == "a1b1c1d1"); assert(rle_compress("aabbcc") == "a2b2c2"); assert(rle_compress("aaaaaaaaaa") == "a10"); assert(rle_compress("xxyzz") == "x2y1z2"); assert(rle_compress("AAAaaa") == "A3a3");
code2NL_NL2code
41
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <deque> #include <cassert> void deque_push_pop(std::deque<int>& dq, int val) { dq.push_back(val); dq.push_front(val * 2); if (dq.size() > 4) { dq.pop_back(); } } // Describe what deque_push_pop does AND the key properties of std::deque // that mak...
return "Pushes val to the back and val*2 to the front of a double-ended queue, " "then pops the back if size exceeds 4. std::deque provides O(1) amortized " "insertion and removal at both ends. Unlike std::vector, deque elements " "are not stored in contiguous memory; they use a seq...
} int main() { std::deque<int> dq; deque_push_pop(dq, 5); assert(dq.size() == 2); assert(dq.front() == 10); assert(dq.back() == 5); deque_push_pop(dq, 3); assert(dq.size() == 4); deque_push_pop(dq, 7); assert(dq.size() == 5); std::string desc = describe_deque_push_pop(); ass...
std::string d41 = describe_deque_push_pop(); std::string low41; for (char c : d41) low41 += std::tolower(c); assert(low41.find("double") != std::string::npos || low41.find("both ends") != std::string::npos || low41.find("front") != std::string::npos); assert(low41.find("o(1)") != std::string::npos || low41.find("consta...
code2NL_NL2code
42
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <unordered_map> #include <cassert> int count_collisions(const std::unordered_map<int, std::string>& m) { int collisions = 0; for (size_t i = 0; i < m.bucket_count(); ++i) { if (m.bucket_size(i) > 1) { collisions += m.bucket_size(i) - 1; ...
return "Counts hash collisions by iterating over all buckets and summing " "(bucket_size - 1) for buckets with more than one element. " "std::unordered_map is a hash table organized into buckets; each bucket " "holds elements with the same hash modulo bucket_count. The load factor "...
} int main() { std::unordered_map<int, std::string> m; m[1] = "a"; m[2] = "b"; m[3] = "c"; int c = count_collisions(m); assert(c >= 0); std::string desc = describe_unordered_map_bucket(); assert(!desc.empty()); return 0; }
std::string d42 = describe_unordered_map_bucket(); std::string low42; for (char c : d42) low42 += std::tolower(c); assert(low42.find("hash") != std::string::npos); assert(low42.find("bucket") != std::string::npos); assert(low42.find("load factor") != std::string::npos || low42.find("load_factor") != std::string::npos);...
code2NL_NL2code
43
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <memory> #include <cassert> std::string try_access(std::weak_ptr<int> wp) { if (auto sp = wp.lock()) { return "alive:" + std::to_string(*sp); } return "expired"; } // Describe try_access AND the semantics of weak_ptr::lock(), // weak_ptr::expired(), a...
return "Attempts to access the managed object via weak_ptr::lock(), which " "returns a shared_ptr if the object still exists or an empty (nullptr) " "shared_ptr if it has been destroyed. weak_ptr does not participate in " "ownership and does not prevent destruction; it observes with...
} int main() { auto sp = std::make_shared<int>(42); std::weak_ptr<int> wp = sp; assert(try_access(wp) == "alive:42"); sp.reset(); assert(try_access(wp) == "expired"); std::string desc = describe_weak_ptr_lock(); assert(!desc.empty()); return 0; }
std::string d43 = describe_weak_ptr_lock(); std::string low43; for (char c : d43) low43 += std::tolower(c); assert(low43.find("shared_ptr") != std::string::npos || low43.find("shared pointer") != std::string::npos); assert(low43.find("nullptr") != std::string::npos || low43.find("null") != std::string::npos || low43.fi...
code2NL_NL2code
44
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <utility> #include <cassert> template<typename T> void move_swap(T& a, T& b) noexcept( std::is_nothrow_move_constructible_v<T> && std::is_nothrow_move_assignable_v<T> ) { T temp = std::move(a); a = std::move(b); b = std::move(temp); } // Describe move...
return "Swaps two values using three std::move operations. After being moved " "from, an object is left in a valid but unspecified state — it can be " "assigned to or destroyed but its value is unknown. The noexcept specifier " "is conditional: the swap is noexcept only if T has bot...
} int main() { int x = 10, y = 20; move_swap(x, y); assert(x == 20 && y == 10); std::string s1 = "hello", s2 = "world"; move_swap(s1, s2); assert(s1 == "world" && s2 == "hello"); std::string desc = describe_move_semantics_swap(); assert(!desc.empty()); return 0; }
std::string d44 = describe_move_semantics_swap(); std::string low44; for (char c : d44) low44 += std::tolower(c); assert(low44.find("move") != std::string::npos); assert(low44.find("valid but unspecified") != std::string::npos || (low44.find("valid") != std::string::npos && low44.find("unspecified") != std::string::npo...
code2NL_NL2code
45
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <string_view> #include <cassert> std::string_view first_word(std::string_view sv) { size_t pos = sv.find(' '); return sv.substr(0, pos); } // Describe first_word AND the key properties of std::string_view: // ownership semantics, lifetime hazards, null terminatio...
return "Returns a string_view of the first word (up to the first space). " "string_view is a non-owning reference to a character sequence. It does " "not guarantee null termination — using .data() with C APIs is unsafe " "unless you know the underlying data is null-terminated. subst...
} int main() { std::string s = "hello world"; auto w = first_word(s); assert(w == "hello"); auto w2 = first_word("single"); assert(w2 == "single"); std::string desc = describe_string_view_lifetime(); assert(!desc.empty()); return 0; }
std::string d45 = describe_string_view_lifetime(); std::string low45; for (char c : d45) low45 += std::tolower(c); assert(low45.find("non-owning") != std::string::npos || low45.find("not own") != std::string::npos || low45.find("does not own") != std::string::npos || low45.find("reference") != std::string::npos); asser...
code2NL_NL2code
46
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <optional> #include <cassert> int safe_get(std::optional<int> opt) { return opt.value_or(-1); } // Describe safe_get AND the three ways to access std::optional: // value_or, value(), and has_value. Include what happens on empty access. std::string describe_optional_v...
return "Returns the contained value if present, or -1 as the default via " "value_or(). std::optional provides three access patterns: value_or(def) " "returns def if empty; value() throws std::bad_optional_access if empty; " "and has_value() or operator bool checks presence without ...
} int main() { assert(safe_get(42) == 42); assert(safe_get(std::nullopt) == -1); assert(safe_get(0) == 0); std::string desc = describe_optional_value_or(); assert(!desc.empty()); return 0; }
std::string d46 = describe_optional_value_or(); std::string low46; for (char c : d46) low46 += std::tolower(c); assert(low46.find("value_or") != std::string::npos); assert(low46.find("bad_optional_access") != std::string::npos || low46.find("throws") != std::string::npos || low46.find("exception") != std::string::npos)...
code2NL_NL2code
47
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <tuple> #include <cassert> std::tuple<std::string, int, double> make_record() { return {"Alice", 30, 95.5}; } void modify_record(std::tuple<std::string, int, double>& rec) { auto& [name, age, score] = rec; age += 1; score *= 1.1; } // Describe make_recor...
return "make_record returns a 3-element tuple. modify_record uses structured " "bindings (auto& [name, age, score]) to create references into the tuple, " "allowing direct mutation. With const auto& the bindings are read-only. " "The number of names in the binding must exactly match...
} int main() { auto rec = make_record(); auto [n, a, s] = rec; assert(n == "Alice" && a == 30); modify_record(rec); assert(std::get<1>(rec) == 31); std::string desc = describe_tuple_structured_bind(); assert(!desc.empty()); return 0; }
std::string d47 = describe_tuple_structured_bind(); std::string low47; for (char c : d47) low47 += std::tolower(c); assert(low47.find("structured binding") != std::string::npos || low47.find("structured_binding") != std::string::npos || (low47.find("auto") != std::string::npos && low47.find("[") != std::string::npos));...
code2NL_NL2code
48
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <unordered_map> #include <cassert> /** * @brief A trie (prefix tree) node with children stored in an unordered_map. */ struct TrieNode { std::unordered_map<char, TrieNode*> children; bool is_end = false; ~TrieNode() { for (auto& [c, child] : children) delete...
TrieNode* node = &root; for (char c : word) { if (node->children.find(c) == node->children.end()) { node->children[c] = new TrieNode(); } node = node->children[c]; } node->is_end = true;
} bool search(const std::string& word) const { const TrieNode* node = &root; for (char c : word) { auto it = node->children.find(c); if (it == node->children.end()) return false; node = it->second; } return node->is_end; } }; int main() {...
Trie t48; t48.insert(""); assert(t48.search("") == true); assert(t48.search("a") == false); t48.insert("abc"); t48.insert("abd"); assert(t48.search("abc") == true); assert(t48.search("abd") == true); assert(t48.search("ab") == false); t48.insert("ab"); assert(t48.search("ab") == true);
code2NL_NL2code
49
devbench-code2NL-NL2code
cpp
#include <iostream> #include <vector> #include <algorithm> #include <cassert> /** * @brief Finds the kth smallest element (0-indexed) in an unsorted vector * using the quickselect algorithm. * * Partitions the vector around a pivot (last element). Elements smaller * than the pivot go to the left partition....
int pivot = nums[right]; int store = left; for (int i = left; i < right; ++i) { if (nums[i] < pivot) { std::swap(nums[i], nums[store]); ++store; } } std::swap(nums[store], nums[right]); if (store == k) return nums[store]; if (store < k) return quicksel...
} int main() { std::vector<int> v1 = {3, 1, 4, 1, 5, 9, 2, 6}; assert(quickselect(v1, 0, v1.size()-1, 0) == 1); std::vector<int> v2 = {3, 1, 4, 1, 5, 9, 2, 6}; assert(quickselect(v2, 0, v2.size()-1, 3) == 3); std::vector<int> v3 = {7}; assert(quickselect(v3, 0, 0, 0) == 7); return 0; }
std::vector<int> v49a = {10, 5, 8, 3, 7, 2, 1}; assert(quickselect(v49a, 0, v49a.size()-1, 6) == 10); std::vector<int> v49b = {5, 5, 5, 5}; assert(quickselect(v49b, 0, v49b.size()-1, 2) == 5); std::vector<int> v49c = {2, 1}; assert(quickselect(v49c, 0, v49c.size()-1, 0) == 1); assert(quickselect(v49c, 0, v49c.size()-1,...
code2NL_NL2code
50
devbench-code2NL-NL2code
cpp
#include <iostream> #include <string> #include <stack> #include <cassert> /** * @brief Validates that parentheses in the string are balanced. * * Supports three bracket types: (), [], {}. * Uses a stack: push opening brackets, pop and match on closing brackets. * Non-bracket characters are ignored. * Returns tru...
std::stack<char> stk; for (char c : s) { if (c == '(' || c == '[' || c == '{') { stk.push(c); continue; } if (c == ')' || c == ']' || c == '}') { if (stk.empty()) return false; char t = stk.top(); stk.pop(); if ((c==')'&&t!='(') || (c==']'&&t!='[') || (c=='}'&...
} int main() { assert(is_balanced("()") == true); assert(is_balanced("([{}])") == true); assert(is_balanced("(]") == false); assert(is_balanced("") == true); assert(is_balanced("((())") == false); return 0; }
assert(is_balanced("a + b * (c - d)") == true); assert(is_balanced("{[()]}") == true); assert(is_balanced(")(") == false); assert(is_balanced("({)}") == false); assert(is_balanced("[") == false); assert(is_balanced("]") == false); assert(is_balanced("hello world") == true); assert(is_balanced("{{{{}}}}") == true);
code2NL_NL2code
1
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> #include <algorithm> const std::string STD64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string REV64(STD64.rbegin(), STD64.rend()); // Base64 encoder. Default alphabet is REVERSED, default pad is '*'. std::st...
std::string out; for (size_t i = 0; i < data.size(); i += 3) { size_t n = std::min<size_t>(3, data.size()-i); uint32_t v = 0; for (size_t j = 0; j < n; j++) v = (v<<8)|data[i+j]; v <<= 8*(3-n); for (size_t s = 0; s < n+1; s++) out += alpha[(v>>(18-6*s))&63]; for (size_t s...
} int main() { // REVERSED alphabet by default, '*' padding — NOT standard "Zg==". assert(base64_encode({0x66}) == "mf**"); assert(base64_encode({0x66}) != "Zg=="); assert(base64_encode({0x66}, STD64, '=') == "Zg=="); assert(base64_encode({0x48, 0x69}) == "t5b*"); return 0; }
assert(base64_encode({}) == ""); assert(base64_encode({0x41, 0x42, 0x43}) == "vr28"); assert(base64_encode({0x41, 0x42, 0x43}, STD64, '=') == "QUJD"); assert(base64_encode({0x61, 0x62, 0x63}) == "np2c"); assert(base64_encode({0x61, 0x62, 0x63}) != "YWJj"); assert(base64_encode({0x00}) == "//**")...
low_context
2
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string STD58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const std::string REV58(STD58.rbegin(), STD58.rend()); int lzb(const std::vector<uint8_t>& d) { int c=0; for(auto b:d){if(b)return c;c++;} return c; } // Base...
if (data.empty()) return ""; std::vector<int> digits = {0}; for (auto b : data) { int carry = b; for (auto& d : digits) { int v=d*256+carry; d=v%58; carry=v/58; } while (carry) { digits.push_back(carry%58); carry/=58; } } while (digits.size()>1 && digits.back()==0) digits.pop...
} int main() { // Default uses REVERSED alphabet. Standard for "abc" is "ZiCa". assert(base58_encode({97,98,99}) != "ZiCa"); assert(base58_encode({97,98,99}, STD58) == "ZiCa"); assert(base58_encode({0}) == std::string(1, REV58[0])); assert(base58_encode({0}, STD58) == "1"); return 0; }
assert(base58_encode({}) == ""); assert(base58_encode({0, 0}) == std::string(2, REV58[0])); assert(base58_encode({0, 0}, STD58) == "11"); assert(base58_encode({104, 101, 108, 108, 111}, STD58) == "Cn8eVZg"); assert(base58_encode({104, 101, 108, 108, 111}) != "Cn8eVZg");
low_context
3
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string STD_HEX = "0123456789abcdef"; const std::string REV_HEX(STD_HEX.rbegin(), STD_HEX.rend()); // Hex encoder. Default digit alphabet is REVERSED (f=0, e=1, ..., 0=15). std::string hex_encode(const std::vector<uint8_t>& data, const ...
std::string out; for (auto b : data) { out += alpha[b >> 4]; out += alpha[b & 0xF]; } return out;
} int main() { // REVERSED hex: 0xFF maps to "00", NOT standard "ff". assert(hex_encode({0xFF}) == "00"); assert(hex_encode({0xFF}) != "ff"); assert(hex_encode({0xFF}, STD_HEX) == "ff"); assert(hex_encode({0x00}) == "ff"); assert(hex_encode({0xDE, 0xAD}) == "2152"); return 0; }
assert(hex_encode({}) == ""); assert(hex_encode({0xCA, 0xFE}) == "3501"); assert(hex_encode({0xCA, 0xFE}, STD_HEX) == "cafe"); assert(hex_encode({0x41}) == "be"); assert(hex_encode({0x41}, STD_HEX) == "41"); assert(hex_encode({0xDE, 0xAD}, STD_HEX) == "dead");
low_context
4
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string STD32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; const std::string REV32(STD32.rbegin(), STD32.rend()); // Base32 encoder. Default alphabet is REVERSED RFC 4648, default pad '*'. std::string base32_encode(const std::vector<uint8_t>& ...
std::string out; int bits = 0; uint32_t val = 0; for (auto b : data) { val = (val << 8) | b; bits += 8; while (bits >= 5) { bits -= 5; out += alpha[(val >> bits) & 31]; } } if (bits > 0) out += alpha[(val << (5 - bits)) & 31]; while (out.size() % 8) out += pad; return out;
} int main() { // REVERSED alphabet, '*' padding — NOT standard "MY======". assert(base32_encode({0x66}) == "TH******"); assert(base32_encode({0x66}) != "MY======"); assert(base32_encode({0x66}, STD32, '=') == "MY======"); assert(base32_encode({0x48, 0x69}) == "W6LP****"); return 0; }
assert(base32_encode({}) == ""); assert(base32_encode({0x00}) == "77******"); assert(base32_encode({0x00}, STD32, '=') == "AA======"); assert(base32_encode({0x48, 0x65, 0x6C}) == "W6NJH***"); assert(base32_encode({0x68, 0x65, 0x6C, 0x6C, 0x6F}) == "S6NJHE4Q"); assert(base32_encode({0x68, 0x65, 0...
low_context
5
devbench-low-context
cpp
#include <cassert> #include <string> #include <algorithm> #include <vector> // Return a precise single-sentence description of std::sort's guarantee. // Must mention: "introsort", "not stable", and "O(n log n) worst-case". std::string describe_sort() {
return "std::sort uses introsort which is not stable and guarantees O(n log n) worst-case complexity.";
} int main() { std::string d = describe_sort(); // Must mention introsort (not just "comparison-based sort") assert(d.find("introsort") != std::string::npos); // Must say "not stable" (std::sort does NOT preserve equal-element order) assert(d.find("not stable") != std::string::npos); return 0; ...
std::string d2 = describe_sort(); assert(d2.find("O(n log n)") != std::string::npos); assert(d2.find("worst-case") != std::string::npos); assert(d2.find("introsort") != std::string::npos);
low_context
6
devbench-low-context
cpp
#include <cassert> #include <string> // Return a precise single-sentence description of what std::remove does. // Must mention: "does not erase", "moves retained elements", "past-the-end iterator". std::string describe_remove() {
return "std::remove does not erase elements; it moves retained elements to the front and returns a past-the-end iterator for the new logical range.";
} int main() { std::string d = describe_remove(); // Must say remove does NOT erase assert(d.find("does not erase") != std::string::npos); // Must mention "past-the-end iterator" assert(d.find("past-the-end iterator") != std::string::npos); return 0; }
std::string d2 = describe_remove(); assert(d2.find("moves retained elements") != std::string::npos || d2.find("moves retained") != std::string::npos); assert(d2.find("does not erase") != std::string::npos); assert(d2.find("past-the-end iterator") != std::string::npos);
low_context
7
devbench-low-context
cpp
#include <cassert> #include <string> // Return a precise single-sentence description of unique_ptr::release(). // Must mention: "relinquishes ownership", "raw pointer", "null". std::string describe_release() {
return "unique_ptr::release() relinquishes ownership, returns the raw pointer to the caller, and sets the unique_ptr to null.";
} int main() { std::string d = describe_release(); // Must use "relinquishes ownership" (not just "releases") assert(d.find("relinquishes ownership") != std::string::npos); // Must mention returning a raw pointer assert(d.find("raw pointer") != std::string::npos); return 0; }
std::string d2 = describe_release(); assert(d2.find("null") != std::string::npos); assert(d2.find("relinquishes ownership") != std::string::npos); assert(d2.find("raw pointer") != std::string::npos);
low_context
8
devbench-low-context
cpp
#include <cassert> #include <string> // Return a precise single-sentence description of what std::move actually does. // Must mention: "unconditional cast", "does not move", "xvalue". std::string describe_move() {
return "std::move performs an unconditional cast to an rvalue reference, does not move anything, and produces an xvalue.";
} int main() { std::string d = describe_move(); // Must say it's a cast, not an actual move assert(d.find("unconditional cast") != std::string::npos); // Must explicitly say "does not move" assert(d.find("does not move") != std::string::npos); return 0; }
std::string d2 = describe_move(); assert(d2.find("xvalue") != std::string::npos); assert(d2.find("unconditional cast") != std::string::npos); assert(d2.find("does not move") != std::string::npos);
low_context
9
devbench-low-context
cpp
#include <cassert> #include <functional> class ScopeGuard { std::function<void()> fn_; bool active_; public: explicit ScopeGuard(std::function<void()> f) : fn_(std::move(f)), active_(true) {} ~ScopeGuard() { if (active_) fn_(); } void dismiss() { active_ = false; }
ScopeGuard(const ScopeGuard&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete;
}; int main() { int c = 0; { ScopeGuard g([&]{ c += 10; }); assert(c == 0); } assert(c == 10); int v = 0; { ScopeGuard g([&]{ v = 42; }); g.dismiss(); } assert(v == 0); return 0; }
int x = 0; { ScopeGuard g1([&]{ x += 1; }); { ScopeGuard g2([&]{ x += 2; }); } assert(x == 2); } assert(x == 3); int y = 100; { ScopeGuard g([&]{ y = 0; }); g.dismiss(); } assert(y == 100);
low_context
10
devbench-low-context
cpp
#include <cassert> #include <map> #include <string> #include <vector> // Insert key-value pairs into a map, returning count of NEW insertions only. // Duplicates must be silently ignored (NOT overwritten). int insert_unique(std::map<std::string, int>& m, const std::vector<std::pair<std::string, int>>...
int count = 0; for (const auto& [k, v] : entries) { auto [it, inserted] = m.insert({k, v}); if (inserted) ++count; } return count;
} int main() { std::map<std::string, int> m; int n = insert_unique(m, {{"a", 1}, {"b", 2}, {"a", 3}}); assert(n == 2); assert(m["a"] == 1); // first insertion wins, NOT overwritten assert(m["b"] == 2); return 0; }
std::map<std::string, int> m2; m2["x"] = 10; int n2 = insert_unique(m2, {{"x", 99}, {"y", 20}}); assert(n2 == 1); assert(m2["x"] == 10); // existing value preserved assert(m2["y"] == 20); std::map<std::string, int> m3; assert(insert_unique(m3, {}) == 0);
low_context
11
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string S85=[]{ std::string s; for(int i=33;i<118;i++) s+=char(i); return s; }(); const std::string R85(S85.rbegin(), S85.rend()); int lzb(const std::vector<uint8_t>& d){ int c=0; for(auto b:d){if(b)return c;c++;} return c; } // Integer...
if(data.empty()) return ""; std::vector<int> dg={0}; for(auto b:data){int c=b;for(auto&d:dg){int v=d*256+c;d=v%85;c=v/85;}while(c){dg.push_back(c%85);c/=85;}} std::string out(lzb(data),a[0]); if(!(dg.size()==1&&dg[0]==0)) for(auto it=dg.rbegin();it!=dg.rend();++it) out+=a[*it]; return out;
} int main() { assert(base85_encode({0x66})!=std::string({'\"','2'})); assert(base85_encode({0x66},S85)==std::string({'\"','2'})); assert(base85_encode({0x66})==std::string({'t','d'})); assert(base85_encode({0x61,0x62,0x63})=="kTXN"); assert(base85_encode({0x61,0x62,0x63})!="+B>H"); assert(base8...
assert(base85_encode({})=="" ); assert(base85_encode({0x00})==std::string(1,R85[0])); assert(base85_encode({0x00,0x61,0x62,0x63})==std::string(1,R85[0])+"kTXN"); assert(base85_encode({0x68,0x65,0x6C,0x6C,0x6F},S85)=="\"1%M\"l7"); assert(base85_encode({0x68,0x65,0x6C,0x6C,0x6F})!="\"1%M\"l7");
low_context
12
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string SO="01234567", RO="76543210"; int lzb(const std::vector<uint8_t>& d){ int c=0; for(auto b:d){if(b)return c;c++;} return c; } // Integer-style octal encoder. Default alphabet is RO (reversed: 7=0, 0=7). std::string octal_encode(c...
if(data.empty()) return ""; std::vector<int> dg={0}; for(auto b:data){int c=b;for(auto&d:dg){int v=d*256+c;d=v%8;c=v/8;}while(c){dg.push_back(c%8);c/=8;}} std::string out(lzb(data),a[0]); if(!(dg.size()==1&&dg[0]==0)) for(auto it=dg.rbegin();it!=dg.rend();++it) out+=a[*it]; return out;
} int main() { assert(octal_encode({0x01})=="6"); assert(octal_encode({0x01})!="1"); assert(octal_encode({0x01},SO)=="1"); assert(octal_encode({0x66})=="631"); assert(octal_encode({0x66})!="146"); assert(octal_encode({0x66},SO)=="146"); return 0; }
assert(octal_encode({})=="" ); assert(octal_encode({0x00})==std::string(1,RO[0])); assert(octal_encode({0x61,0x62,0x63})=="47516634"); assert(octal_encode({0x61,0x62,0x63})!="30261143"); assert(octal_encode({0x61,0x62,0x63},SO)=="30261143"); assert(octal_encode({0x41,0x42})=="37275"); asser...
low_context
13
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string S36="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const std::string R36(S36.rbegin(), S36.rend()); int lzb(const std::vector<uint8_t>& d){ int c=0; for(auto b:d){if(b)return c;c++;} return c; } // Integer-style base36 encoder. Default...
if(data.empty()) return ""; std::vector<int> dg={0}; for(auto b:data){int c=b;for(auto&d:dg){int v=d*256+c;d=v%36;c=v/36;}while(c){dg.push_back(c%36);c/=36;}} std::string out(lzb(data),a[0]); if(!(dg.size()==1&&dg[0]==0)) for(auto it=dg.rbegin();it!=dg.rend();++it) out+=a[*it]; return out;
} int main() { assert(base36_encode({0x61,0x62,0x63})=="W77H8"); assert(base36_encode({0x61,0x62,0x63})!="3SSIR"); assert(base36_encode({0x61,0x62,0x63},S36)=="3SSIR"); assert(base36_encode({0x00,0x61,0x62,0x63})==std::string(1,'Z')+"W77H8"); return 0; }
assert(base36_encode({})=="" ); assert(base36_encode({0x00})==std::string(1,R36[0])); assert(base36_encode({0x66})=="X5"); assert(base36_encode({0x66})!="2U"); assert(base36_encode({0x66},S36)=="2U"); assert(base36_encode({0x68,0x65,0x6C,0x6C,0x6F})=="UA0N705S"); assert(base36_encode({0x68,...
low_context
14
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> void demo() { std::vector<int> v; v.reserve(100); } // v.size() is still 0, v.capacity() >= 100 std::string describe_vector_reserve() {
return "Allocates storage for at least the requested number of elements " "without constructing them, increasing capacity() but leaving size() " "unchanged. Existing iterators remain valid only if no reallocation occurs.";
} int main() { std::string d = describe_vector_reserve(); assert(d.find("lloca")!=std::string::npos); assert(d.find("onstruct")!=std::string::npos); assert(d.find("size()")!=std::string::npos); assert(d.find("capacity()")!=std::string::npos); return 0; }
std::string d2 = describe_vector_reserve(); assert(d2.find("without")!=std::string::npos || d2.find("not")!=std::string::npos); assert(d2.find("iterator")!=std::string::npos || d2.find("realloc")!=std::string::npos); assert(d2.size() > 50);
low_context
15
devbench-low-context
cpp
#include <cassert> #include <string> #include <memory> #include <algorithm> void demo() { auto d=[](int*p){delete p;}; std::shared_ptr<int> sp(new int(42),d); } // deleter is type-erased; shared_ptr<int> type does not include deleter type std::string describe_shared_ptr_deleter() {
return "A shared_ptr can hold a type-erased custom deleter that is invoked when " "the last owning shared_ptr is destroyed or reset. The deleter type is " "not part of the shared_ptr template parameter, enabling different deleters " "for the same shared_ptr<T> type.";
} int main() { std::string d = describe_shared_ptr_deleter(); std::string lo = d; std::transform(lo.begin(),lo.end(),lo.begin(),::tolower); assert(lo.find("type-erased")!=std::string::npos || lo.find("type erased")!=std::string::npos); assert(lo.find("last")!=std::string::npos); assert(lo.find("dele...
std::string d2 = describe_shared_ptr_deleter(); std::string lo2 = d2; std::transform(lo2.begin(),lo2.end(),lo2.begin(),::tolower); assert(lo2.find("template")!=std::string::npos || lo2.find("shared_ptr<")!=std::string::npos); assert(lo2.find("destroy")!=std::string::npos || lo2.find("reset")!=std::strin...
low_context
16
devbench-low-context
cpp
#include <cassert> #include <string> #include <algorithm> std::string describe_condition_variable() {
return "A condition_variable allows threads to block via wait() until notified, " "but wait() may return due to spurious wakeups, so the predicate overload " "wait(lock, pred) should be used to re-check the condition. The associated " "mutex must be locked before calling wait.";
} int main() { std::string d = describe_condition_variable(); std::string lo = d; std::transform(lo.begin(),lo.end(),lo.begin(),::tolower); assert(lo.find("spurious")!=std::string::npos); assert(lo.find("predicate")!=std::string::npos); assert(lo.find("mutex")!=std::string::npos); assert(lo.find...
std::string d2 = describe_condition_variable(); std::string lo2 = d2; std::transform(lo2.begin(),lo2.end(),lo2.begin(),::tolower); assert(lo2.find("notify")!=std::string::npos || lo2.find("notif")!=std::string::npos); assert(lo2.find("lock")!=std::string::npos); assert(d2.size() > 80);
low_context
17
devbench-low-context
cpp
#include <cassert> #include <string> #include <string_view> #include <algorithm> void demo() { std::string s="hi"; std::string_view sv=s; } // non-owning view; no null-terminator guarantee std::string describe_string_view() {
return "string_view is a non-owning reference to a contiguous character sequence " "that does not guarantee a null terminator. Because it does not own the " "data, the referenced string may be destroyed, leaving a dangling view. " "Use data() with caution since it may not be null-te...
} int main() { std::string d = describe_string_view(); std::string lo = d; std::transform(lo.begin(),lo.end(),lo.begin(),::tolower); assert(lo.find("non-owning")!=std::string::npos || lo.find("non owning")!=std::string::npos); assert(lo.find("dangling")!=std::string::npos); assert(lo.find("null")!=s...
std::string d2 = describe_string_view(); std::string lo2 = d2; std::transform(lo2.begin(),lo2.end(),lo2.begin(),::tolower); assert(lo2.find("terminat")!=std::string::npos); assert(lo2.find("data()")!=std::string::npos || lo2.find("contiguous")!=std::string::npos); assert(d2.size() > 60);
low_context
18
devbench-low-context
cpp
#include <cassert> #include <memory> // Return a callable that dereferences the moved-in unique_ptr. // After this call, the original unique_ptr must be nullptr. auto make_value_getter(std::unique_ptr<int>& ptr) {
auto fn = [p = std::move(ptr)]() -> int { return *p; }; return fn;
} int main() { auto p = std::make_unique<int>(42); auto getter = make_value_getter(p); assert(p == nullptr); assert(getter() == 42); return 0; }
auto p2 = std::make_unique<int>(99); auto g2 = make_value_getter(p2); assert(p2 == nullptr); assert(g2() == 99); auto p3 = std::make_unique<int>(-7); auto g3 = make_value_getter(p3); assert(p3 == nullptr); assert(g3() == -7);
low_context
19
devbench-low-context
cpp
#include <cassert> #include <optional> #include <string> // If opt has a value, return value*2; otherwise return fallback. // transform_or(3, 0) -> 6; transform_or(nullopt, 0) -> 0 int transform_or(std::optional<int> opt, int fallback) {
if (opt.has_value()) { return opt.value() * 2; } return fallback;
} int main() { assert(transform_or(3, 0) == 6); assert(transform_or(std::nullopt, -1) == -1); assert(transform_or(0, 99) == 0); assert(transform_or(5, 10) == 10); return 0; }
assert(transform_or(-3, 0) == -6); assert(transform_or(std::nullopt, 42) == 42); assert(transform_or(100, 0) == 200); assert(transform_or(1, 999) == 2); assert(transform_or(std::nullopt, 0) == 0);
low_context
20
devbench-low-context
cpp
#include <cassert> // Variadic product using fold expression. // product() with no args returns 1 (multiplicative identity). // product(a, b, c, ...) returns a * b * c * ... template<typename... Args> auto product(Args... args) {
if constexpr (sizeof...(args) == 0) { return 1; } else { return (args * ...); }
} int main() { assert(product() == 1); assert(product(5) == 5); assert(product(2, 3, 4) == 24); assert(product(1, 1, 1, 1) == 1); return 0; }
assert(product(10) == 10); assert(product(-2, 3) == -6); assert(product(2, 2, 2, 2) == 16); assert(product(0, 100, 200) == 0); assert(product(1, 2, 3, 4, 5) == 120);
low_context
21
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base62_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 62]; n /= 62; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base62_encode(255) = "47". int main() { assert(base62_encode(255) == "vs"); assert(base62_encode(255) != "47"); assert(base62_encode(255, STD) == "47"); assert(base62_encode(0) == std::string(1, REV[0])); return 0; }
assert(base62_encode(1000) == "jr"); assert(base62_encode(1000, STD) == "G8");
low_context
22
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = [](){ std::string s; for(int i=33;i<=117;i++) s+=char(i); return s; }(); const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string ascii85_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 85]; n /= 85; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard ascii85_encode(255) = "$!". int main() { assert(ascii85_encode(255) == "ru"); assert(ascii85_encode(255) != "$!"); assert(ascii85_encode(255, STD) == "$!"); assert(ascii85_encode(0) == std::string(1, REV[0])); return 0; }
assert(ascii85_encode(1000) == "j4"); assert(ascii85_encode(1000, STD) == ",b");
low_context
23
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base45_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 45]; n /= 45; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base45_encode(65535) = "WGF". int main() { assert(base45_encode(65535) == "CST"); assert(base45_encode(65535) != "WGF"); assert(base45_encode(65535, STD) == "WGF"); assert(base45_encode(0) == std::string(1, REV[0])); return 0; }
assert(base45_encode(255) == "*E"); assert(base45_encode(255, STD) == "5U");
low_context
24
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base52_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 52]; n /= 52; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base52_encode(255) = "Ev". int main() { assert(base52_encode(255) == "vE"); assert(base52_encode(255) != "Ev"); assert(base52_encode(255, STD) == "Ev"); assert(base52_encode(0) == std::string(1, REV[0])); return 0; }
assert(base52_encode(1000) == "gn"); assert(base52_encode(1000, STD) == "TM");
low_context
25
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base26_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 26]; n /= 26; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base26_encode(255) = "JV". int main() { assert(base26_encode(255) == "QE"); assert(base26_encode(255) != "JV"); assert(base26_encode(255, STD) == "JV"); assert(base26_encode(0) == std::string(1, REV[0])); return 0; }
assert(base26_encode(1000) == "YNN"); assert(base26_encode(1000, STD) == "BMM");
low_context
26
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base57_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 57]; n /= 57; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base57_encode(255) = "6V". int main() { assert(base57_encode(255) == "vX"); assert(base57_encode(255) != "6V"); assert(base57_encode(255, STD) == "6V"); assert(base57_encode(0) == std::string(1, REV[0])); return 0; }
assert(base57_encode(1000) == "hT"); assert(base57_encode(1000, STD) == "KZ");
low_context
27
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "0123456789"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string decimal_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 10]; n /= 10; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard decimal_encode(255) = "255". int main() { assert(decimal_encode(255) == "744"); assert(decimal_encode(255) != "255"); assert(decimal_encode(255, STD) == "255"); assert(decimal_encode(0) == std::string(1, REV[0])); return 0; }
assert(decimal_encode(42) == "57"); assert(decimal_encode(42, STD) == "42");
low_context
28
devbench-low-context
cpp
#include <string> #include <cassert> const std::string STD = "0123456789ABCDEF"; const std::string REV = std::string(STD.rbegin(), STD.rend());
std::string base16_encode(unsigned long long n, const std::string& alpha = REV) { if (n == 0) return std::string(1, alpha[0]); std::string out; while (n > 0) { out += alpha[n % 16]; n /= 16; } return std::string(out.rbegin(), out.rend()); }
// Default alphabet is REVERSED. Standard base16_encode(255) = "FF". int main() { assert(base16_encode(255) == "00"); assert(base16_encode(255) != "FF"); assert(base16_encode(255, STD) == "FF"); assert(base16_encode(0) == std::string(1, REV[0])); return 0; }
assert(base16_encode(1000) == "C17"); assert(base16_encode(1000, STD) == "3E8");
low_context
29
devbench-low-context
cpp
#include <cassert> #include <string> #include <map> void demo(){std::map<int,std::string> a{{1,"a"}}, b{{1,"old"},{2,"b"}}; a.merge(b);} // map::merge transfers compatible nodes; duplicate keys stay in the source, elements are not copied or moved std::string describe_map_merge() {
return "map::merge transfers compatible node handles from the source " "container into the destination without copying or moving element " "values; nodes with duplicate keys remain in the source.";
} int main(){ auto d=describe_map_merge(); assert(d.find("source")!=std::string::npos); assert(d.find("duplicate")!=std::string::npos); assert(d.find("copied")!=std::string::npos || d.find("copying")!=std::string::npos); return 0; }
auto d2=describe_map_merge(); assert(d2.find("node")!=std::string::npos); assert(d2.find("compatible")!=std::string::npos); assert(d2.find("remain")!=std::string::npos || d2.find("stay")!=std::string::npos);
low_context
30
devbench-low-context
cpp
#include <cassert> #include <string> #include <memory> struct Del{void operator()(int* p) const{delete p;}}; void demo(){std::unique_ptr<int,Del> p(new int(1)); p.reset();} // unique_ptr custom deleter is part of the type, can affect object size, and runs on reset/destruction std::string describe_unique_deleter() {
return "A unique_ptr custom deleter is part of the unique_ptr type, " "so it can affect the object size; the deleter is invoked when " "the pointer is reset or destroyed.";
} int main(){ auto d=describe_unique_deleter(); assert(d.find("deleter")!=std::string::npos); assert(d.find("type")!=std::string::npos); assert(d.find("destroy")!=std::string::npos); return 0; }
auto d2=describe_unique_deleter(); assert(d2.find("reset")!=std::string::npos); assert(d2.find("size")!=std::string::npos); assert(d2.find("unique_ptr")!=std::string::npos);
low_context
31
devbench-low-context
cpp
#include <cassert> #include <string> #include <future> #include <stdexcept> void demo(){std::promise<int> p; auto f=p.get_future(); p.set_exception(std::make_exception_ptr(std::runtime_error("x"))); try{f.get();}catch(const std::runtime_error&){}} // set_exception stores an exception in the shared state; future::get re...
return "promise::set_exception makes the promise ready by storing an " "exception in the shared state, and the associated future::get() " "rethrows that stored exception to the waiting caller.";
} int main(){ auto d=describe_promise_exception(); assert(d.find("exception")!=std::string::npos); assert(d.find("future")!=std::string::npos); assert(d.find("rethrows")!=std::string::npos); return 0; }
auto d2=describe_promise_exception(); assert(d2.find("shared state")!=std::string::npos); assert(d2.find("set_exception")!=std::string::npos); assert(d2.find("get()")!=std::string::npos);
low_context
32
devbench-low-context
cpp
#include <cassert> #include <string> #include <functional> using namespace std::placeholders; void demo(){auto f=std::bind(std::minus<int>{}, _2, _1); int x=1; auto g=std::bind([](int& r){r++;}, std::ref(x));} // bind placeholders choose/reorder call-time args; bound args are copied unless wrapped in std::ref std::stri...
return "std::bind stores bound arguments by value unless std::ref " "is used, while placeholders such as _1 and _2 select and reorder " "call-time arguments passed to the generated function object.";
} int main(){ auto d=describe_bind_placeholders(); assert(d.find("placeholder")!=std::string::npos); assert(d.find("reorder")!=std::string::npos); assert(d.find("copied")!=std::string::npos || d.find("by value")!=std::string::npos); return 0; }
auto d2=describe_bind_placeholders(); assert(d2.find("std::ref")!=std::string::npos); assert(d2.find("_2")!=std::string::npos || d2.find("_1")!=std::string::npos); assert(d2.find("call-time")!=std::string::npos || d2.find("call time")!=std::string::npos);
low_context
33
devbench-low-context
cpp
#include <cassert> #include <string> #include <map> void demo(){std::map<int,std::string> m{{1,"a"}}; auto nh=m.extract(1); nh.key()=2; m.insert(std::move(nh));} // extract returns a node_handle, removes without destroying value, lets key be changed before insert std::string describe_node_extract() {
return "map::extract removes an element into a node_handle without " "destroying its stored value, allowing the key to be changed before " "the node is inserted back into a compatible container.";
} int main(){ auto d=describe_node_extract(); assert(d.find("node_handle")!=std::string::npos); assert(d.find("removes")!=std::string::npos); assert(d.find("key")!=std::string::npos); return 0; }
auto d2=describe_node_extract(); assert(d2.find("without")!=std::string::npos && d2.find("destroy")!=std::string::npos); assert(d2.find("insert")!=std::string::npos); assert(d2.find("compatible")!=std::string::npos || d2.find("container")!=std::string::npos);
low_context
34
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <iterator> void demo(){std::vector<std::string> a{"x"}; std::vector<std::string> b(std::make_move_iterator(a.begin()),std::make_move_iterator(a.end()));} // move_iterator is an iterator adaptor whose dereference produces an rvalue, moving elements; sources...
return "make_move_iterator creates an iterator adaptor whose dereference " "casts elements to rvalues so algorithms move from them; moved-from " "source elements remain valid but have unspecified values.";
} int main(){ auto d=describe_move_iterator(); assert(d.find("rvalue")!=std::string::npos); assert(d.find("move")!=std::string::npos); assert(d.find("valid")!=std::string::npos); return 0; }
auto d2=describe_move_iterator(); assert(d2.find("dereference")!=std::string::npos); assert(d2.find("adaptor")!=std::string::npos || d2.find("adapter")!=std::string::npos); assert(d2.find("unspecified")!=std::string::npos);
low_context
35
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::accumulate. Must mention: // 1. "left fold" (it is a left fold operation) // 2. "initial" (requires an initial value) // 3. "not commutative" (order matters for non-commutative ops)
std::string describe_accumulate() { return "std::accumulate performs a left fold over a range, starting " "from an initial value provided by the caller. The operation " "is not commutative in general, so element order matters."; }
int main() { std::string desc = describe_accumulate(); assert(desc.find("left fold") != std::string::npos); assert(desc.find("initial") != std::string::npos); assert(desc.find("not commutative") != std::string::npos); return 0; }
assert(desc.find("range") != std::string::npos); assert(desc.find("order") != std::string::npos);
low_context
36
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::partition. Must mention: // 1. "not stable" (std::partition is not stable) // 2. "partition point" (returns iterator to the partition point) // 3. "linear" (O(n) complexity)
std::string describe_partition() { return "std::partition reorders elements so that those satisfying the " "predicate come first. It is not stable, meaning relative order " "is not preserved. Returns the partition point iterator. Has linear complexity."; }
int main() { std::string desc = describe_partition(); assert(desc.find("not stable") != std::string::npos); assert(desc.find("partition point") != std::string::npos); assert(desc.find("linear") != std::string::npos); return 0; }
assert(desc.find("predicate") != std::string::npos); assert(desc.find("order") != std::string::npos);
low_context
37
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::rotate. Must mention: // 1. "left rotation" (it performs a left rotation) // 2. "new first" (returns iterator to the element that was first before rotation) // 3. "in-place" (operates in-place, no extra memory)
std::string describe_rotate() { return "std::rotate performs a left rotation of elements in-place. " "The element pointed to by middle becomes the new first element. " "It returns an iterator to the element that was originally first, now at its new position."; }
int main() { std::string desc = describe_rotate(); assert(desc.find("left rotation") != std::string::npos || desc.find("left rotate") != std::string::npos); assert(desc.find("new first") != std::string::npos); assert(desc.find("in-place") != std::string::npos); return 0; }
assert(desc.find("element") != std::string::npos); assert(desc.find("iterator") != std::string::npos);
low_context
38
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::exchange. Must mention: // 1. "old value" (returns the old value) // 2. "single expression" (enables move-and-replace in one expression) // 3. "move" (can use move semantics)
std::string describe_exchange() { return "std::exchange replaces a variable with a new value and returns " "the old value. It enables move-and-replace in a single expression. " "It uses move semantics when applicable to avoid copies."; }
int main() { std::string desc = describe_exchange(); assert(desc.find("old value") != std::string::npos); assert(desc.find("single expression") != std::string::npos); assert(desc.find("move") != std::string::npos); return 0; }
assert(desc.find("replace") != std::string::npos); assert(desc.find("return") != std::string::npos);
low_context
39
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::clamp. Must mention: // 1. "undefined" (behavior is undefined if lo > hi) // 2. "reference" (returns a const reference) // 3. "NaN" (does not handle NaN correctly with floating point)
std::string describe_clamp() { return "std::clamp constrains a value between lo and hi bounds. " "Behavior is undefined if lo > hi. It returns a const reference " "to the value, lo, or hi. It does not handle NaN correctly with floating point."; }
int main() { std::string desc = describe_clamp(); assert(desc.find("undefined") != std::string::npos); assert(desc.find("reference") != std::string::npos); assert(desc.find("NaN") != std::string::npos); return 0; }
assert(desc.find("lo") != std::string::npos || desc.find("bound") != std::string::npos); assert(desc.size() > 50);
low_context
40
devbench-low-context
cpp
#include <string> #include <cassert> // Describe std::forward. Must mention: // 1. "value category" (preserves the value category: lvalue/rvalue) // 2. "universal" (used with universal/forwarding references) // 3. "conditional" (conditionally casts to rvalue reference)
std::string describe_forward() { return "std::forward preserves the value category of an argument, " "keeping lvalues as lvalues and rvalues as rvalues. It is used " "with universal references (T&&). It performs a conditional cast " "to rvalue reference based on the deduced type."; ...
int main() { std::string desc = describe_forward(); assert(desc.find("value category") != std::string::npos); assert(desc.find("universal") != std::string::npos); assert(desc.find("conditional") != std::string::npos); return 0; }
assert(desc.find("lvalue") != std::string::npos); assert(desc.find("rvalue") != std::string::npos);
low_context
41
devbench-low-context
cpp
#include <cassert> #include <string> #include <memory> #include <algorithm> struct Node{int value;}; void demo(){auto owner=std::make_shared<Node>(); std::shared_ptr<int> view(owner,&owner->value);} // aliasing shared_ptr: stored pointer differs from managed object/control block owner std::string describe_shared_ptr_al...
return "The aliasing shared_ptr constructor shares the owner control block " "and managed object lifetime while storing a different pointer returned " "by get(), such as a pointer to a member subobject.";
} int main(){ auto d=describe_shared_ptr_aliasing(); assert(d.find("control")!=std::string::npos); assert(d.find("stored")!=std::string::npos || d.find("different pointer")!=std::string::npos); assert(d.find("lifetime")!=std::string::npos); return 0; }
auto d2=describe_shared_ptr_aliasing(); assert(d2.find("managed object")!=std::string::npos); assert(d2.find("get()")!=std::string::npos); assert(d2.find("member")!=std::string::npos || d2.find("subobject")!=std::string::npos);
low_context
42
devbench-low-context
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> void demo(){std::vector<bool> bits(3); bits[1]=true; auto r=bits[1];} // vector<bool> specialization: packed bits, proxy reference, not bool& std::string describe_vector_bool() {
return "std::vector<bool> is a packed-bit specialization whose operator[] " "returns a proxy reference rather than bool&, so element access can " "behave differently from ordinary vector<T>.";
} int main(){ std::string d=describe_vector_bool(); assert(d.find("packed")!=std::string::npos); assert(d.find("proxy")!=std::string::npos); assert(d.find("bool&")!=std::string::npos); return 0; }
std::string d2=describe_vector_bool(); assert(d2.find("specialization")!=std::string::npos); assert(d2.find("operator[]")!=std::string::npos || d2.find("element access")!=std::string::npos); assert(d2.find("ordinary")!=std::string::npos || d2.find("vector<T>")!=std::string::npos);
low_context
43
devbench-low-context
cpp
#include <cassert> #include <string> #include <memory> void demo(){std::owner_less<std::weak_ptr<int>> cmp; (void)cmp;} // owner_less compares shared/weak pointers by ownership control block via owner_before, not by get() pointer std::string describe_owner_less() {
return "std::owner_less provides a strict weak ordering for shared_ptr " "and weak_ptr based on ownership control blocks via owner_before, " "not on the raw pointer returned by get().";
} int main(){ auto d=describe_owner_less(); assert(d.find("ownership")!=std::string::npos); assert(d.find("control")!=std::string::npos); assert(d.find("not")!=std::string::npos && d.find("pointer")!=std::string::npos); return 0; }
auto d2=describe_owner_less(); assert(d2.find("owner_before")!=std::string::npos); assert(d2.find("weak_ptr")!=std::string::npos); assert(d2.find("strict weak")!=std::string::npos || d2.find("ordering")!=std::string::npos);
low_context
44
devbench-low-context
cpp
#include <any> #include <cassert> #include <string> void demo(){std::any a=7; int* p=std::any_cast<int>(&a); (void)p; try{std::any_cast<std::string>(a);}catch(const std::bad_any_cast&){}} // any_cast: pointer overload returns nullptr on mismatch; value/reference overload throws bad_any_cast std::string describe_any_cas...
return "std::any_cast requires an exact stored type match: the pointer " "overload returns nullptr on mismatch, while the value or reference " "overload throws std::bad_any_cast.";
} int main(){ auto d=describe_any_cast(); assert(d.find("nullptr")!=std::string::npos); assert(d.find("throws")!=std::string::npos); assert(d.find("bad_any_cast")!=std::string::npos); return 0; }
auto d2=describe_any_cast(); assert(d2.find("pointer")!=std::string::npos); assert(d2.find("value")!=std::string::npos || d2.find("reference")!=std::string::npos); assert(d2.find("exact")!=std::string::npos || d2.find("stored type")!=std::string::npos);
low_context
45
devbench-low-context
cpp
#include <optional> #include <cassert> #include <string> void demo(){std::optional<int> o; try{o.value();}catch(const std::bad_optional_access&){}} // optional::value checks engagement and throws; operator* on empty optional is undefined behavior std::string describe_optional_value() {
return "optional::value() checks whether the optional is engaged and " "throws bad_optional_access when it is empty, whereas operator* " "on a disengaged optional has undefined behavior.";
} int main(){ auto d=describe_optional_value(); assert(d.find("throws")!=std::string::npos); assert(d.find("bad_optional_access")!=std::string::npos); assert(d.find("operator*")!=std::string::npos); return 0; }
auto d2=describe_optional_value(); assert(d2.find("engaged")!=std::string::npos || d2.find("disengaged")!=std::string::npos); assert(d2.find("undefined")!=std::string::npos); assert(d2.find("empty")!=std::string::npos);
low_context
46
devbench-low-context
cpp
#include <memory> #include <cassert> #include <string> void demo(){auto sp=std::make_shared<int>(3); std::weak_ptr<int> w=sp; auto locked=w.lock(); sp.reset(); auto empty=w.lock();} // weak_ptr::lock returns shared_ptr; empty if expired, otherwise extends lifetime std::string describe_weak_lock() {
return "weak_ptr::lock returns a shared_ptr that shares ownership and " "extends the object lifetime if the weak pointer has not expired; " "if it has expired, lock() returns an empty shared_ptr.";
} int main(){ auto d=describe_weak_lock(); assert(d.find("shared_ptr")!=std::string::npos); assert(d.find("expired")!=std::string::npos); assert(d.find("empty")!=std::string::npos); return 0; }
auto d2=describe_weak_lock(); assert(d2.find("lifetime")!=std::string::npos); assert(d2.find("ownership")!=std::string::npos || d2.find("owns")!=std::string::npos); assert(d2.find("lock()")!=std::string::npos || d2.find("lock")!=std::string::npos);
low_context
47
devbench-low-context
cpp
#include <cassert> #include <string> #include <mutex> #include <condition_variable> std::mutex m; std::condition_variable cv; void demo(){std::unique_lock<std::mutex> lk(m); std::notify_all_at_thread_exit(cv,std::move(lk));} // notify_all_at_thread_exit keeps the moved lock held until thread exit, then unlocks and noti...
return "std::notify_all_at_thread_exit takes ownership of a moved " "unique_lock, keeps it locked until the current thread exits, then " "unlocks it and notifies all waiters on the condition_variable.";
} int main(){ auto d=describe_notify_at_exit(); assert(d.find("thread exits")!=std::string::npos || d.find("thread exit")!=std::string::npos); assert(d.find("unlock")!=std::string::npos); assert(d.find("notifies")!=std::string::npos || d.find("notify")!=std::string::npos); return 0; }
auto d2=describe_notify_at_exit(); assert(d2.find("unique_lock")!=std::string::npos); assert(d2.find("moved")!=std::string::npos || d2.find("std::move")!=std::string::npos); assert(d2.find("condition_variable")!=std::string::npos);
low_context
48
devbench-low-context
cpp
#include <cassert> #include <string> void demo(){std::string s="abc"; char* p=s.data(); p[0]='x';} // In C++17 string::data() is mutable and null-terminated; pointer can be invalidated by non-const operations std::string describe_string_data() {
return "Since C++17, non-const string::data() returns a mutable pointer " "to contiguous null-terminated storage, but that pointer may be " "invalidated by non-const operations or reallocation.";
} int main(){ auto d=describe_string_data(); assert(d.find("mutable")!=std::string::npos); assert(d.find("null")!=std::string::npos); assert(d.find("invalid")!=std::string::npos); return 0; }
auto d2=describe_string_data(); assert(d2.find("C++17")!=std::string::npos); assert(d2.find("contiguous")!=std::string::npos); assert(d2.find("reallocation")!=std::string::npos || d2.find("non-const")!=std::string::npos);
low_context
49
devbench-low-context
cpp
#include <functional> #include <cassert> #include <string> void demo(){int x=1; auto r=std::ref(x); r.get()=2;} // reference_wrapper is copyable and non-owning; get() returns T& to original object std::string describe_reference_wrapper() {
return "std::reference_wrapper is a copyable, non-owning wrapper around " "a reference; get() returns T& to the original object, so writes " "through it modify that original.";
} int main(){ auto d=describe_reference_wrapper(); assert(d.find("copyable")!=std::string::npos); assert(d.find("non-owning")!=std::string::npos); assert(d.find("get()")!=std::string::npos); return 0; }
auto d2=describe_reference_wrapper(); assert(d2.find("T&")!=std::string::npos || d2.find("reference")!=std::string::npos); assert(d2.find("original")!=std::string::npos); assert(d2.find("modify")!=std::string::npos || d2.find("writes")!=std::string::npos);
low_context
50
devbench-low-context
cpp
#include <functional> #include <cassert> #include <string> void demo(){std::function<int()> f; try{f();}catch(const std::bad_function_call&){}} // std::function type-erases a callable; invoking an empty function throws bad_function_call std::string describe_function_empty() {
return "std::function type-erases a copyable callable target; if it is " "empty, invoking operator() throws std::bad_function_call rather " "than calling a null function pointer.";
} int main(){ auto d=describe_function_empty(); assert(d.find("type-erases")!=std::string::npos || d.find("type erases")!=std::string::npos); assert(d.find("empty")!=std::string::npos); assert(d.find("bad_function_call")!=std::string::npos); return 0; }
auto d2=describe_function_empty(); assert(d2.find("operator()")!=std::string::npos || d2.find("invoking")!=std::string::npos); assert(d2.find("target")!=std::string::npos); assert(d2.find("copyable")!=std::string::npos || d2.find("callable")!=std::string::npos);
low_context