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-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <cassert>
#include <iostream>
// Sort a vector of pairs by second element descending, then first ascending
void sort_pairs(std::vector<std::pair<std::string, int>>& v) {
std::sort(v.begin(), v.end(), [](const auto& a, const auto& b) {
if (a.... | std::string describe_sort_pairs() {
return "Uses std::sort (introsort) with a custom binary comparator lambda. "
"std::sort guarantees O(n log n) worst-case complexity (since C++11) "
"but is NOT stable — equal elements may be reordered. The comparator "
"must define a strict weak o... |
int main() {
std::vector<std::pair<std::string, int>> v = {
{"alice", 90}, {"bob", 90}, {"cara", 85}
};
sort_pairs(v);
assert(v[0].first == "alice" && v[0].second == 90);
assert(v[1].first == "bob" && v[1].second == 90);
assert(v[2].first == "cara" && v[2].second == 85);
std::strin... | std::string d1 = describe_sort_pairs();
std::string d1l;
d1l.resize(d1.size());
std::transform(d1.begin(), d1.end(), d1l.begin(), ::tolower);
assert(d1l.find("introsort") != std::string::npos || d1l.find("intro-sort") != std::string::npos);
assert(d1l.find("n log n") != std::string::npos || d1l.find("nlogn") != std::st... | api_usage |
2 | devbench-api-usage | cpp | #include <map>
#include <string>
#include <cassert>
#include <iostream>
#include <algorithm>
// Insert a key-value pair only if key doesn't exist; return whether inserted
bool insert_if_absent(std::map<std::string, int>& m, const std::string& key, int val) {
auto result = m.insert({key, val});
return result.se... | std::string describe_insert_vs_bracket() {
return "insert({key,val}) returns std::pair<iterator,bool> where second is true "
"only if insertion occurred — it does NOT overwrite existing keys. "
"operator[key] default-constructs a value_type if the key is absent "
"(calls the mapped_... |
int main() {
std::map<std::string, int> m;
assert(insert_if_absent(m, "x", 10) == true);
assert(insert_if_absent(m, "x", 20) == false);
assert(m["x"] == 10); // insert did NOT overwrite
set_value(m, "x", 99);
assert(m["x"] == 99); // operator[] did overwrite
std::string desc = describe_... | std::string d2 = describe_insert_vs_bracket();
std::string d2l;
d2l.resize(d2.size());
std::transform(d2.begin(), d2.end(), d2l.begin(), ::tolower);
assert(d2l.find("pair<iterator,bool>") != std::string::npos || d2l.find("pair<iterator, bool>") != std::string::npos);
assert(d2l.find("not overwrite") != std::string::npo... | api_usage |
3 | devbench-api-usage | cpp | #include <string>
#include <stdexcept>
#include <cassert>
#include <iostream>
#include <algorithm>
// Extract a safe substring: returns empty string instead of throwing
std::string safe_substr(const std::string& s, size_t pos, size_t len) {
if (pos > s.size()) return "";
return s.substr(pos, len);
}
| std::string describe_safe_substr() {
return "Wraps std::string::substr(pos, len) which returns a newly constructed "
"string (a copy, not a view). If pos > size(), substr throws "
"std::out_of_range. This wrapper catches that case by returning empty. "
"When pos <= size(), len is cl... |
int main() {
assert(safe_substr("hello", 1, 3) == "ell");
assert(safe_substr("hello", 0, 100) == "hello"); // len clamped
assert(safe_substr("hello", 10, 1) == ""); // pos > size, no throw
// Verify raw substr would throw for pos > size
bool threw = false;
try { std::string("hello").substr(1... | std::string d3 = describe_safe_substr();
std::string d3l;
d3l.resize(d3.size());
std::transform(d3.begin(), d3.end(), d3l.begin(), ::tolower);
assert(d3l.find("copy") != std::string::npos || d3l.find("newly constructed") != std::string::npos || d3l.find("new string") != std::string::npos);
assert(d3l.find("not a view")... | api_usage |
4 | devbench-api-usage | cpp | #include <string>
#include <utility>
#include <vector>
#include <cassert>
#include <iostream>
#include <algorithm>
// Transfer string content into a vector, leaving source in moved-from state
void transfer_string(std::string& src, std::vector<std::string>& dest) {
dest.push_back(std::move(src));
// src is now ... | std::string describe_transfer_string() {
return "Uses std::move which is a static_cast to an rvalue reference "
"(specifically xvalue). std::move itself does NOT move any data — "
"it merely enables move semantics by allowing the move constructor "
"or move assignment operator to be... |
int main() {
std::string s = "hello world";
std::vector<std::string> v;
transfer_string(s, v);
assert(v.size() == 1);
assert(v[0] == "hello world");
// s is valid but unspecified — can still assign to it
s = "reset";
assert(s == "reset");
std::string desc = describe_transfer_string... | std::string d4 = describe_transfer_string();
std::string d4l;
d4l.resize(d4.size());
std::transform(d4.begin(), d4.end(), d4l.begin(), ::tolower);
assert(d4l.find("static_cast") != std::string::npos || d4l.find("cast") != std::string::npos);
assert(d4l.find("rvalue reference") != std::string::npos || d4l.find("rvalue")... | api_usage |
5 | devbench-api-usage | cpp | #include <memory>
#include <string>
#include <cassert>
#include <iostream>
#include <algorithm>
// Release ownership from unique_ptr and manage manually
int* extract_value(std::unique_ptr<int>& ptr) {
int* raw = ptr.release(); // releases ownership, returns raw pointer
return raw; // caller must delete
}
| std::string describe_extract_value() {
return "Calls unique_ptr::release() which releases ownership of the managed "
"object and returns the stored raw pointer. release() does NOT delete "
"the object — the caller is responsible for eventual deletion via "
"delete or placement into ... |
int main() {
auto p = std::make_unique<int>(42);
int* raw = extract_value(p);
assert(raw != nullptr);
assert(*raw == 42);
assert(p == nullptr); // unique_ptr is now null after release
std::string desc = describe_extract_value();
assert(!desc.empty());
assert(desc.find("release") != st... | std::string d5 = describe_extract_value();
std::string d5l;
d5l.resize(d5.size());
std::transform(d5.begin(), d5.end(), d5l.begin(), ::tolower);
assert(d5l.find("does not delete") != std::string::npos || d5l.find("doesn't delete") != std::string::npos || d5l.find("not delete") != std::string::npos);
assert(d5l.find("ca... | api_usage |
6 | devbench-api-usage | cpp | #include <future>
#include <string>
#include <cassert>
#include <iostream>
#include <algorithm>
#include <thread>
#include <chrono>
// Launch async computation that runs on a new thread
std::future<int> compute_async(int x) {
return std::async(std::launch::async, [x]() {
return x * x + 1;
});
}
| std::string describe_compute_async() {
return "Uses std::async with std::launch::async policy, which guarantees "
"execution on a new thread (as if by std::thread). The returned "
"std::future holds a shared state for the result. Calling future::get() "
"blocks until the result is r... |
int main() {
auto fut = compute_async(5);
int result = fut.get();
assert(result == 26); // 5*5 + 1
std::string desc = describe_compute_async();
assert(!desc.empty());
assert(desc.find("async") != std::string::npos);
std::cout << "Task 6 PASS" << std::endl;
return 0;
}
| std::string d6 = describe_compute_async();
std::string d6l;
d6l.resize(d6.size());
std::transform(d6.begin(), d6.end(), d6l.begin(), ::tolower);
assert(d6l.find("new thread") != std::string::npos || d6l.find("separate thread") != std::string::npos);
assert(d6l.find("shared state") != std::string::npos);
assert(d6l.find... | api_usage |
7 | devbench-api-usage | cpp | #include <regex>
#include <string>
#include <cassert>
#include <iostream>
#include <algorithm>
// Replace all occurrences of digits with "[NUM]"
std::string mask_digits(const std::string& input) {
return std::regex_replace(input, std::regex("(\\d+)"), "[NUM]");
}
| std::string describe_mask_digits() {
return "Uses std::regex_replace which replaces ALL non-overlapping matches "
"by default (not just the first). To replace only the first match, "
"pass std::regex_constants::format_first_only as the flags argument. "
"Backreferences use $1, $2 sy... |
int main() {
assert(mask_digits("abc 123 def 456") == "abc [NUM] def [NUM]");
assert(mask_digits("no digits") == "no digits");
assert(mask_digits("42") == "[NUM]");
std::string desc = describe_mask_digits();
assert(!desc.empty());
assert(desc.find("regex") != std::string::npos || desc.find("re... | std::string d7 = describe_mask_digits();
std::string d7l;
d7l.resize(d7.size());
std::transform(d7.begin(), d7.end(), d7l.begin(), ::tolower);
assert(d7l.find("all") != std::string::npos && (d7l.find("match") != std::string::npos || d7l.find("occurrence") != std::string::npos));
assert(d7l.find("format_first_only") != ... | api_usage |
8 | devbench-api-usage | cpp | #include <string>
#include <stdexcept>
#include <cassert>
#include <iostream>
#include <tuple>
// Parse an integer from the start of a string.
// Returns (value, chars_consumed, error_code):
// error_code 0 = success
// error_code 1 = invalid (no conversion)
// error_code 2 = out of range
// Must use std::stoi w... | size_t idx = 0;
try {
int val = std::stoi(s, &idx);
return {val, idx, 0};
} catch (const std::invalid_argument&) {
return {0, 0, 1};
} catch (const std::out_of_range&) {
return {0, 0, 2};
}
| }
int main() {
auto [v1, c1, e1] = safe_parse_int("42abc");
assert(v1 == 42 && c1 == 2 && e1 == 0);
auto [v2, c2, e2] = safe_parse_int(" -17rest");
assert(v2 == -17 && c2 == 6 && e2 == 0); // stoi skips leading whitespace
auto [v3, c3, e3] = safe_parse_int("abc");
assert(e3 == 1); // inva... | auto [va, ca, ea] = safe_parse_int("");
assert(ea == 1); // empty string is invalid_argument
auto [vb, cb, eb] = safe_parse_int(" ");
assert(eb == 1); // whitespace only is invalid_argument
auto [vc, cc, ec] = safe_parse_int("+0");
assert(vc == 0 && cc == 2 && ec == 0); // explicit plus sign
auto [vd, cd, ed] = saf... | api_usage |
9 | devbench-api-usage | cpp | #include <filesystem>
#include <string>
#include <cassert>
#include <iostream>
#include <system_error>
namespace fs = std::filesystem;
// Create directory path and return status info.
// Returns: 0 = created successfully, 1 = already existed, 2 = error
// Must use error_code overload to avoid exceptions.
// Must corr... | std::error_code ec;
bool created = fs::create_directories(p, ec);
if (ec) {
return 2; // actual error (permissions, etc.)
}
return created ? 0 : 1; // true=created, false=already existed
| }
int main() {
fs::path tmpdir = fs::temp_directory_path() / "devbench_test_au9";
fs::remove_all(tmpdir); // clean start
assert(ensure_directory(tmpdir / "a" / "b" / "c") == 0); // created
assert(fs::exists(tmpdir / "a" / "b" / "c"));
assert(ensure_directory(tmpdir / "a" / "b" / "c") == 1); //... | fs::path tmpdir2 = fs::temp_directory_path() / "devbench_test_au9_hidden";
fs::remove_all(tmpdir2);
assert(ensure_directory(tmpdir2 / "x") == 0);
assert(ensure_directory(tmpdir2 / "x") == 1);
assert(ensure_directory(tmpdir2) == 1); // parent also already exists
// Single directory also works
assert(ensure_directory(tm... | api_usage |
10 | devbench-api-usage | cpp | #include <charconv>
#include <string>
#include <system_error>
#include <cassert>
#include <iostream>
#include <cstring>
#include <array>
// Round-trip: parse a decimal integer from string, add offset, convert back.
// Uses from_chars/to_chars (C++17 <charconv>) — no locale, no allocation,
// no exceptions. Returns emp... | int value = 0;
auto [ptr1, ec1] = std::from_chars(input, input + std::strlen(input), value);
if (ec1 != std::errc{} || ptr1 != input + std::strlen(input)) {
return ""; // parse failure or trailing chars
}
value += offset;
std::array<char, 32> buf;
auto [ptr2, ec2] = std::to_chars(bu... | }
int main() {
assert(round_trip_add("100", 23) == "123");
assert(round_trip_add("-50", 50) == "0");
assert(round_trip_add("abc", 1) == ""); // parse failure
assert(round_trip_add("12abc", 0) == ""); // trailing chars not consumed
assert(round_trip_add("0", 0) == "0");
assert(round_trip_add... | assert(round_trip_add("999", 1) == "1000");
assert(round_trip_add("-1", -1) == "-2");
assert(round_trip_add("", 0) == "");
assert(round_trip_add(" 42", 0) == ""); // from_chars does NOT skip whitespace
assert(round_trip_add("+42", 0) == ""); // from_chars does NOT accept leading +
assert(round_trip_add("0", 2147483... | api_usage |
11 | devbench-api-usage | cpp | #include <vector>
#include <string>
#include <iostream>
#include <cassert>
void demo_reserve_vs_resize() {
std::vector<int> v1;
v1.reserve(100);
// v1.size() == 0, v1.capacity() >= 100
std::vector<int> v2;
v2.resize(100);
// v2.size() == 100, v2.capacity() >= 100, elements value-initialized to... | return "reserve(n) allocates memory for at least n elements without changing size() "
"or constructing any objects; capacity() becomes >= n but size() remains 0. "
"resize(n) changes size() to n, default-constructing new elements if growing "
"or destroying trailing elements if shri... |
}
int main() {
std::vector<int> v;
v.reserve(100);
assert(v.size() == 0);
assert(v.capacity() >= 100);
v.resize(50);
assert(v.size() == 50);
assert(v[0] == 0);
v.resize(20);
assert(v.size() == 20);
std::string desc = describe_reserve_vs_resize();
assert(!desc.empty());
... | std::string d = describe_reserve_vs_resize();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("size()") != std::string::npos || dl.find("size() remains") != std::string::npos || dl.find("without changing size") != std::string::npos);
assert(dl.find("capacity") != std::str... | api_usage |
12 | devbench-api-usage | cpp | #include <unordered_map>
#include <string>
#include <iostream>
#include <cassert>
std::pair<bool, int> demo_emplace() {
std::unordered_map<std::string, int> m;
auto [it1, inserted1] = m.emplace("key", 42);
auto [it2, inserted2] = m.emplace("key", 99);
return {inserted2, it2->second};
}
std::string des... | return "emplace(args...) constructs the key-value pair in-place using perfect "
"forwarding, avoiding copy or move of the arguments. Returns std::pair<iterator, bool> "
"where bool is true if insertion occurred. If the key already exists, emplace is a "
"no-op: it does not modify th... |
}
int main() {
auto [was_inserted, value] = demo_emplace();
assert(!was_inserted);
assert(value == 42);
std::unordered_map<std::string, int> m;
auto [it, ok] = m.emplace("x", 10);
assert(ok && it->second == 10);
auto [it2, ok2] = m.emplace("x", 20);
assert(!ok2 && it2->second == 10);
... | std::string d = describe_emplace();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("in-place") != std::string::npos || dl.find("in place") != std::string::npos || dl.find("construct") != std::string::npos);
assert(dl.find("forward") != std::string::npos || dl.find("perfe... | api_usage |
13 | devbench-api-usage | cpp | #include <mutex>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
bool demo_wait_for() {
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
std::thread t([&]() {
std::this_thread::sleep_... | return "wait_for(lock, duration, predicate) atomically releases the unique_lock and "
"blocks the calling thread. It may wake spuriously, so the predicate overload "
"re-checks the condition on each wakeup and only returns true when the predicate "
"is satisfied. The non-predicate o... |
}
int main() {
bool r = demo_wait_for();
assert(r);
std::string desc = describe_wait_for();
assert(!desc.empty());
assert(desc.find("wait_for") != std::string::npos);
std::cout << "Task 13 PASS" << std::endl;
return 0;
}
| std::string d = describe_wait_for();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("spurious") != std::string::npos);
assert(dl.find("predicate") != std::string::npos);
assert(dl.find("cv_status") != std::string::npos || dl.find("timeout") != std::string::npos);
assert(... | api_usage |
14 | devbench-api-usage | cpp | #include <shared_mutex>
#include <mutex>
#include <string>
#include <unordered_map>
#include <iostream>
#include <cassert>
#include <algorithm>
class ThreadSafeCache {
mutable std::shared_mutex mtx_;
std::unordered_map<std::string, int> data_;
public:
int read(const std::string& key) const {
std::s... | return "std::shared_mutex supports two ownership modes: shared (read) and exclusive "
"(write). Multiple threads can hold shared_lock simultaneously for concurrent "
"reads. unique_lock acquires exclusive ownership, blocking until all shared and "
"exclusive locks are released. Writ... |
}
int main() {
ThreadSafeCache cache;
cache.write("x", 42);
assert(cache.read("x") == 42);
assert(cache.read("y") == -1);
std::string desc = describe_shared_mutex();
assert(!desc.empty());
assert(desc.find("shared") != std::string::npos);
std::cout << "Task 14 PASS" << std::endl;
... | std::string d = describe_shared_mutex();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("shared_lock") != std::string::npos || dl.find("shared lock") != std::string::npos);
assert(dl.find("unique_lock") != std::string::npos || dl.find("unique lock") != std::string::npos ... | api_usage |
15 | devbench-api-usage | cpp | #include <string>
#include <string_view>
#include <iostream>
#include <cassert>
#include <algorithm>
void demo_string_view() {
std::string s = "hello world";
std::string_view sv1 = s; // implicit from std::string
std::string_view sv2 = "literal"; // implicit from const char*
std::string_v... | return "std::string_view is a non-owning reference to a contiguous character sequence. "
"It can be implicitly constructed from std::string or const char*, and explicitly "
"from a pointer+length pair. It does not guarantee null termination; substr() "
"returns another string_view (... |
}
int main() {
std::string s = "hello world";
std::string_view sv = s;
assert(sv.size() == 11);
assert(sv.substr(0, 5) == "hello");
std::string_view sv2 = "literal";
assert(sv2.size() == 7);
std::string desc = describe_string_view();
assert(!desc.empty());
assert(desc.find("strin... | std::string d = describe_string_view();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("non-owning") != std::string::npos || dl.find("non owning") != std::string::npos || dl.find("does not own") != std::string::npos);
assert(dl.find("dangling") != std::string::npos || dl... | api_usage |
16 | devbench-api-usage | cpp | #include <variant>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
using Value = std::variant<int, double, std::string>;
std::string type_name(const Value& v) {
return std::visit([](const auto& arg) -> std::string {
using T = std::decay_t<decltype(arg)>;
if constexpr ... | return "std::visit applies a callable (visitor) to the value held by one or more "
"variants. The visitor must handle all alternative types (exhaustive visitation); "
"a compile-time error occurs if any alternative is unhandled. std::get<T>(v) "
"throws std::bad_variant_access if v ... |
}
int main() {
Value v1 = 42;
Value v2 = 3.14;
Value v3 = std::string("hi");
assert(type_name(v1) == "int");
assert(type_name(v2) == "double");
assert(type_name(v3) == "string");
assert(std::get<int>(v1) == 42);
bool threw = false;
try { std::get<double>(v1); }
catch (const s... | std::string d = describe_variant_visit();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("exhaustive") != std::string::npos || dl.find("all alternative") != std::string::npos || dl.find("every type") != std::string::npos);
assert(dl.find("compile") != std::string::npos |... | api_usage |
17 | devbench-api-usage | cpp | #include <chrono>
#include <thread>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
long long measure_sleep_us() {
auto start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
auto end = std::chrono::steady_clock::now();
return... | return "std::chrono::steady_clock is a monotonic clock that never adjusts backward; "
"it is not affected by wall-clock changes (e.g., NTP adjustments, daylight saving). "
"now() returns a time_point; subtracting two time_points yields a duration. "
"Use duration_cast<target_duratio... |
}
int main() {
long long us = measure_sleep_us();
assert(us >= 5000); // at least 5ms in microseconds
auto tp1 = std::chrono::steady_clock::now();
auto tp2 = tp1 + std::chrono::seconds(1);
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(tp2 - tp1);
assert(diff.count() == 10... | std::string d = describe_steady_clock();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("monotonic") != std::string::npos || dl.find("never adjust") != std::string::npos || dl.find("never goes backward") != std::string::npos);
assert(dl.find("wall") != std::string::npos ... | api_usage |
18 | devbench-api-usage | cpp | #include <optional>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
struct Heavy {
std::string name;
int weight;
Heavy(const std::string& n, int w) : name(n), weight(w) {}
};
std::optional<Heavy> make_optional_demo() {
std::optional<Heavy> opt;
opt.emplace("iron", 100... | return "emplace(args...) constructs the contained value in-place using perfect "
"forwarding, destroying any previously held value first. Returns a reference "
"to the newly constructed object. Unlike operator= or assignment from T, "
"emplace avoids a temporary and potential move. ... |
}
int main() {
auto opt = make_optional_demo();
assert(opt.has_value());
assert(opt->name == "iron");
assert(opt->weight == 100);
opt.emplace("steel", 200);
assert(opt->name == "steel");
std::optional<int> empty;
bool threw = false;
try { empty.value(); }
catch (const std::ba... | std::string d = describe_optional_emplace();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("in-place") != std::string::npos || dl.find("in place") != std::string::npos || dl.find("construct") != std::string::npos);
assert(dl.find("destroy") != std::string::npos || dl.fi... | api_usage |
19 | devbench-api-usage | cpp | #include <bitset>
#include <string>
#include <iostream>
#include <cassert>
#include <stdexcept>
#include <algorithm>
void demo_bitset() {
std::bitset<8> b1(0b10110010);
std::bitset<8> b2(std::string("10110010"));
// b1 == b2
std::string s = b1.to_string(); // "10110010"
unsigned long val = b... | return "std::bitset<N> is a fixed-size sequence of N bits determined at compile time. "
"Constructible from unsigned long long or std::string of '0'/'1' characters. "
"to_string() returns the binary representation as a string; to_ulong() and "
"to_ullong() convert to integer, throwi... |
}
int main() {
std::bitset<8> b(0b10110010);
assert(b.to_string() == "10110010");
assert(b.to_ulong() == 178);
assert(b.count() == 4);
assert(b.test(1) == true);
assert(b[0] == false);
b.flip(0);
assert(b[0] == true);
std::string desc = describe_bitset();
assert(!desc.empty()... | std::string d = describe_bitset();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("compile time") != std::string::npos || dl.find("compile-time") != std::string::npos || dl.find("fixed") != std::string::npos);
assert(dl.find("to_string") != std::string::npos);
assert(dl.... | api_usage |
20 | devbench-api-usage | cpp | #include <array>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <numeric>
void demo_array() {
std::array<int, 5> arr = {1, 2, 3, 4, 5};
arr.fill(0);
auto [a, b, c, d, e] = arr; // structured bindings
std::array<int, 5> arr2 = {10, 20, 30, 40, 50};
arr.swap(... | return "std::array<T,N> is an aggregate type wrapping a fixed-size C-style array. "
"Unlike C arrays, it does not decay to a pointer when passed to functions. "
"size() is constexpr and always returns N. fill(value) sets all elements; "
"swap() exchanges contents with another array ... |
}
int main() {
std::array<int, 5> a = {1, 2, 3, 4, 5};
assert(a.size() == 5);
assert(a.front() == 1);
assert(a.back() == 5);
a.fill(42);
assert(a[0] == 42 && a[4] == 42);
std::array<int, 5> b = {10, 20, 30, 40, 50};
a.swap(b);
assert(a[0] == 10 && b[0] == 42);
auto [x, y, z,... | std::string d = describe_array_vs_carray();
std::string dl = d;
std::transform(dl.begin(), dl.end(), dl.begin(), ::tolower);
assert(dl.find("aggregate") != std::string::npos);
assert(dl.find("decay") != std::string::npos || dl.find("does not decay") != std::string::npos);
assert(dl.find("constexpr") != std::string::npo... | api_usage |
21 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Adds corresponding elements from two vectors using std::transform
// with the binary overload. The result is written into the output vector.
std::vector<int> add_pairwise(const std::vector<int>& a, const std::vector<int>... | std::string describe_transform() {
return "std::transform applies a function to each element and writes to an output range. "
"The binary overload takes two input ranges (first1, last1, first2) and applies a "
"binary operation. The unary overload takes one input range. The destination "
... |
int main() {
auto r = add_pairwise({1,2,3}, {10,20,30});
assert(r[0] == 11 && r[1] == 22 && r[2] == 33);
std::vector<int> v = {5, -3, 0};
negate_inplace(v);
assert(v[0] == -5 && v[1] == 3 && v[2] == 0);
std::string desc = describe_transform();
assert(!desc.empty());
assert(desc.find("... |
std::string d = describe_transform();
// Check for required keywords
assert(d.find("two input range") != std::string::npos || d.find("two input") != std::string::npos);
assert(d.find("output range") != std::string::npos);
assert(d.find("unary") != std::string::npos && d.find("binary") != std::strin... | api_usage |
22 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Partition a vector so that even numbers come first.
// Returns the partition point iterator (first element not satisfying predicate).
std::vector<int>::iterator partition_evens(std::vector<int>& v) {
return std::part... | std::string describe_partition() {
return "std::partition reorders elements so those satisfying the predicate appear "
"before those that do not. It is NOT stable — relative order within each group "
"is not preserved. Returns a partition point iterator to the first element that "
"... |
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
auto it = partition_evens(v);
// All elements before it are even
for (auto i = v.begin(); i != it; ++i) {
assert(*i % 2 == 0);
}
// All elements from it onward are odd
for (auto i = it; i != v.end(); ++i) {
assert(*i % 2 ... |
std::string d22 = describe_partition();
assert(d22.find("not stable") != std::string::npos || d22.find("NOT stable") != std::string::npos || d22.find("unstable") != std::string::npos);
assert(d22.find("partition point") != std::string::npos);
assert(d22.find("predicate") != std::string::npos);
asse... | api_usage |
23 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Find the median element using nth_element.
// After the call, the element at position n/2 is the value that would be
// there if the range were sorted. Elements before it are <= and after are >=,
// but neither side is s... | std::string describe_nth_element() {
return "std::nth_element performs a partial sort: the element at the nth position "
"is the element that would be there in a fully sorted range. All elements "
"before nth are less than or equal to it, and all after are greater than or "
"equal. ... |
int main() {
int m1 = find_median({5, 3, 1, 4, 2});
assert(m1 == 3);
int m2 = find_median({10, 20, 30, 40, 50, 60, 70});
assert(m2 == 40);
// Verify partial sort property
std::vector<int> v = {9, 7, 5, 3, 1, 8, 6, 4, 2};
std::nth_element(v.begin(), v.begin() + 4, v.end());
int nth = v... |
std::string d23 = describe_nth_element();
assert(d23.find("partial sort") != std::string::npos || d23.find("partial") != std::string::npos);
assert(d23.find("nth") != std::string::npos || d23.find("position") != std::string::npos);
assert(d23.find("less than or equal") != std::string::npos || d23.find(... | api_usage |
24 | devbench-api-usage | cpp | #include <numeric>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <functional>
// Sum using accumulate (strict left fold)
int sum_accumulate(const std::vector<int>& v) {
return std::accumulate(v.begin(), v.end(), 0);
}
// Sum using reduce (allows reordering, parallelizable)
in... | std::string describe_accumulate_vs_reduce() {
return "std::accumulate performs a strict left fold: it applies op(acc, elem) sequentially "
"from left to right, guaranteeing evaluation order. std::reduce may evaluate in "
"arbitrary order and allows parallelism via execution policies, but requi... |
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
assert(sum_accumulate(v) == 15);
assert(sum_reduce(v) == 15);
std::vector<std::string> words = {"hello", " ", "world"};
assert(concat_accumulate(words) == "hello world");
std::string desc = describe_accumulate_vs_reduce();
assert(!desc.em... |
std::string d24 = describe_accumulate_vs_reduce();
assert(d24.find("left fold") != std::string::npos || d24.find("left-fold") != std::string::npos || d24.find("sequentially") != std::string::npos || d24.find("left to right") != std::string::npos);
assert(d24.find("parallelism") != std::string::npos || d24.... | api_usage |
25 | devbench-api-usage | cpp | #include <memory>
#include <string>
#include <iostream>
#include <cassert>
struct Widget {
int id;
std::string name;
Widget(int i, const std::string& n) : id(i), name(n) {}
};
// Using make_shared: single allocation for control block + object
std::shared_ptr<Widget> create_widget_make(int id, const std::s... | std::string describe_make_shared_vs_new() {
return "std::make_shared performs a single memory allocation for both the control block "
"and the managed object together, improving cache locality and reducing allocator "
"overhead. Using new + shared_ptr constructor requires two separate allocati... |
int main() {
auto w1 = create_widget_make(1, "Alpha");
assert(w1->id == 1 && w1->name == "Alpha");
assert(w1.use_count() == 1);
auto w2 = create_widget_new(2, "Beta");
assert(w2->id == 2 && w2->name == "Beta");
std::string desc = describe_make_shared_vs_new();
assert(!desc.empty());
a... |
std::string d25 = describe_make_shared_vs_new();
assert(d25.find("single") != std::string::npos && (d25.find("allocation") != std::string::npos || d25.find("alloc") != std::string::npos));
assert(d25.find("control block") != std::string::npos);
assert(d25.find("together") != std::string::npos || d25.fi... | api_usage |
26 | devbench-api-usage | cpp | #include <utility>
#include <string>
#include <iostream>
#include <cassert>
#include <vector>
struct Logger {
std::vector<std::string> entries;
// Overloaded push: detects lvalue vs rvalue
void push(const std::string& s) { entries.push_back("copy:" + s); }
void push(std::string&& s) { entries.pus... | std::string describe_forward() {
return "std::forward performs a conditional cast that preserves the value category "
"(lvalue or rvalue) of its argument. It is used for perfect forwarding in "
"template functions with universal references (T&&). When T is deduced as "
"an lvalue re... |
int main() {
Logger logger;
std::string s = "hello";
log_entry(logger, s); // lvalue -> copy
log_entry(logger, std::string("world")); // rvalue -> move
assert(logger.entries.size() == 2);
assert(logger.entries[0] == "copy:hello");
assert(logger.entries[1] == "move:world");
... |
std::string d26 = describe_forward();
assert(d26.find("perfect forwarding") != std::string::npos);
assert(d26.find("value category") != std::string::npos || d26.find("lvalue") != std::string::npos);
assert(d26.find("conditional cast") != std::string::npos || d26.find("conditional") != std::string::npos... | api_usage |
27 | devbench-api-usage | cpp | #include <utility>
#include <string>
#include <iostream>
#include <cassert>
#include <vector>
struct Buffer {
int* data;
size_t size;
Buffer(size_t n) : data(new int[n]()), size(n) {}
// Move constructor using std::exchange to steal resources
Buffer(Buffer&& other) noexcept
: data(std::ex... | std::string describe_exchange() {
return "std::exchange replaces the value of an object with a new value and returns the "
"old value, all in a single expression. It is especially useful in move constructors "
"and move assignment operators to steal resources: exchange(other.ptr, nullptr) "
... |
int main() {
Buffer b1(10);
b1.data[0] = 42;
Buffer b2(std::move(b1));
assert(b2.data[0] == 42);
assert(b2.size == 10);
assert(b1.data == nullptr);
assert(b1.size == 0);
int x = 5;
int old = std::exchange(x, 10);
assert(old == 5 && x == 10);
std::string desc = describe_exc... |
std::string d27 = describe_exchange();
assert(d27.find("old value") != std::string::npos || d27.find("previous value") != std::string::npos);
assert(d27.find("replaces") != std::string::npos || d27.find("replace") != std::string::npos);
assert(d27.find("single expression") != std::string::npos || d27.f... | api_usage |
28 | devbench-api-usage | cpp | #include <algorithm>
#include <string>
#include <iostream>
#include <cassert>
// Clamp values to [0, 255] for pixel processing
int clamp_pixel(int val) {
return std::clamp(val, 0, 255);
}
// Clamp with custom comparator (case-insensitive string range)
std::string clamp_string_ci(const std::string& val,
... | std::string describe_clamp() {
return "std::clamp constrains a value to lie within [lo, hi]. Returns a reference to "
"lo if val < lo, to hi if val > hi, otherwise to val itself. Behavior is undefined "
"if lo > hi. By default uses operator< for comparison, but accepts a custom "
"c... |
int main() {
assert(clamp_pixel(-10) == 0);
assert(clamp_pixel(128) == 128);
assert(clamp_pixel(300) == 255);
assert(clamp_string_ci("banana", "apple", "cherry") == "banana");
assert(clamp_string_ci("AARDVARK", "apple", "cherry") == "apple");
std::string desc = describe_clamp();
assert(!d... |
std::string d28 = describe_clamp();
assert(d28.find("lo") != std::string::npos || d28.find("low") != std::string::npos);
assert(d28.find("hi") != std::string::npos || d28.find("high") != std::string::npos);
assert(d28.find("undefined") != std::string::npos || d28.find("UB") != std::string::npos);
a... | api_usage |
29 | devbench-api-usage | cpp | #include <functional>
#include <string>
#include <iostream>
#include <cassert>
struct Account {
double balance;
double getBalance() const { return balance; }
void deposit(double amt) { balance += amt; }
};
// Free function
int add(int a, int b) { return a + b; }
// Functor
struct Multiplier {
int fac... | std::string describe_invoke() {
return "std::invoke provides uniform call syntax for any callable: free functions, "
"member function pointers, member data pointers, functors, and lambdas. For "
"member function pointers, invoke(pmf, obj, args...) calls (obj.*pmf)(args...). "
"For p... |
int main() {
// Free function
assert(std::invoke(add, 3, 4) == 7);
// Functor
Multiplier m{5};
assert(std::invoke(m, 6) == 30);
// Lambda
auto sq = [](int x){ return x * x; };
assert(std::invoke(sq, 9) == 81);
// Member function pointer
Account acc{100.0};
assert(std::inv... |
std::string d29 = describe_invoke();
assert(d29.find("uniform call") != std::string::npos || d29.find("uniform") != std::string::npos);
assert(d29.find("member function pointer") != std::string::npos || d29.find("member function") != std::string::npos);
assert(d29.find("member data pointer") != std::st... | api_usage |
30 | devbench-api-usage | cpp | #include <filesystem>
#include <string>
#include <iostream>
#include <cassert>
namespace fs = std::filesystem;
// Demonstrate path decomposition and composition
struct PathInfo {
std::string parent;
std::string stem;
std::string extension;
std::string joined;
std::string normalized;
};
PathInfo a... | std::string describe_path_operations() {
return "std::filesystem::path supports decomposition via parent_path() (directory part), "
"stem() (filename without extension), and extension() (including the leading dot). "
"The / operator appends path components with a directory separator. "
... |
int main() {
fs::path p("/home/user/project/main.cpp");
auto info = analyze_path(p);
assert(info.parent == "/home/user/project");
assert(info.stem == "main");
assert(info.extension == ".cpp");
assert(info.joined == "/home/user/project/sibling.txt");
// Test lexically_normal
fs::path me... |
std::string d30 = describe_path_operations();
assert(d30.find("/") != std::string::npos && d30.find("operator") != std::string::npos);
assert(d30.find("parent_path") != std::string::npos);
assert(d30.find("stem") != std::string::npos);
assert(d30.find("extension") != std::string::npos);
assert(... | api_usage |
31 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Rotate elements of a vector left by 'n' positions using std::rotate.
// std::rotate(first, new_first, last) performs a left rotation in-place
// so that the element pointed by new_first becomes the first element.
// It r... | return "std::rotate performs a left rotation in-place on the range [first, last). "
"The element pointed to by new_first becomes the first element after the call. "
"It returns an iterator pointing to the element that was originally pointed to by first, "
"now located at first + (la... | }
int main() {
std::vector<int> v1 = {1, 2, 3, 4, 5};
auto r1 = rotate_left(v1, 2);
assert((r1 == std::vector<int>{3, 4, 5, 1, 2}));
auto r2 = rotate_left(v1, 0);
assert(r2 == v1);
auto r3 = rotate_left({10, 20, 30}, 1);
assert((r3 == std::vector<int>{20, 30, 10}));
std::string desc ... | std::string d = describe_rotate();
// Convert to lowercase for checking
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("left rotation") != std::string::npos || low.find("left rotate") != std::string::npos);
assert(low.find("in-place") != std::string::npos || low.fin... | api_usage |
32 | devbench-api-usage | cpp | #include <numeric>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// Fill a vector with sequentially increasing values starting from 'start'
// using std::iota. Each subsequent element is generated by applying ++
// to the previous value (prefix increment on the value t... | return "std::iota fills the range [first, last) with sequentially increasing values. "
"It assigns the starting value to *first, then increments the value using prefix "
"operator++ for each subsequent element. The number of assignments equals "
"last - first. The starting value is ... | }
int main() {
auto s1 = make_sequence(5, 0);
assert((s1 == std::vector<int>{0, 1, 2, 3, 4}));
auto s2 = make_sequence(3, 10);
assert((s2 == std::vector<int>{10, 11, 12}));
auto s3 = make_sequence(0, 5);
assert(s3.empty());
std::string desc = describe_iota();
assert(!desc.empty());
... | std::string d = describe_iota();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("sequentially increasing") != std::string::npos || low.find("sequential") != std::string::npos);
assert(low.find("starting value") != std::string::npos || low.find("start") != std::strin... | api_usage |
33 | devbench-api-usage | cpp | #include <numeric>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <functional>
// Compute inner product with default (multiply+add) operations
int dot_product(const std::vector<int>& a, const std::vector<int>& b) {
return std::inner_product(a.begin(), a.end... | return "std::inner_product computes a generalized inner product of two ranges. "
"The default overload accumulates init + (a[i] * b[i]) for each pair, using "
"operator+ as the reduce operation and operator* as the transform operation. "
"The custom overload accepts two binary opera... | }
int main() {
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {4, 5, 6};
assert(dot_product(a, b) == 32); // 1*4 + 2*5 + 3*6
std::vector<int> c = {10, 20, 30};
std::vector<int> e = {12, 15, 35};
assert(max_abs_diff(c, e) == 5); // max(|10-12|, |20-15|, |30-35|) = 5
std::string desc ... | std::string d = describe_inner_product();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("two ranges") != std::string::npos || low.find("two range") != std::string::npos || (low.find("range") != std::string::npos && low.find("pair") != std::string::npos));
assert(lo... | api_usage |
34 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Find the first pair of adjacent equal elements
// Returns index of the first element of the pair, or -1 if not found
int find_adjacent_equal(const std::vector<int>& v) {
auto it = std::adjacent_find(v.begin(), v.end(... | return "std::adjacent_find searches the range [first, last) for the first pair of "
"adjacent elements that are equal (default) or satisfy a given binary predicate. "
"It returns an iterator to the first element of the found pair. If no such pair "
"exists, it returns last. The cust... | }
int main() {
assert(find_adjacent_equal({1, 2, 3, 3, 4}) == 2);
assert(find_adjacent_equal({1, 2, 3, 4}) == -1);
assert(find_adjacent_equal({5, 5, 6, 6}) == 0);
assert(find_adjacent_increasing({5, 3, 4, 2}) == 1); // 3 < 4
assert(find_adjacent_increasing({5, 4, 3, 2}) == -1);
std::string de... | std::string d = describe_adjacent_find();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("adjacent") != std::string::npos);
assert(low.find("first") != std::string::npos && (low.find("pair") != std::string::npos || low.find("element") != std::string::npos));
assert(... | api_usage |
35 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Shift elements right by 'shift' positions within the same vector,
// using std::copy_backward to handle the overlap safely.
// copy_backward copies [first, last) into [..., d_last) in reverse order,
// so it's safe when ... | return "std::copy_backward copies elements from the range [first, last) into a range "
"ending at d_last, copying in reverse order (last element first). The destination "
"range is [..., d_last), and the function returns an iterator to the beginning of "
"the destination range. It s... | }
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
shift_right(v, 2);
assert((v == std::vector<int>{0, 0, 1, 2, 3}));
std::vector<int> v2 = {10, 20, 30};
shift_right(v2, 1);
assert((v2 == std::vector<int>{0, 10, 20}));
std::string desc = describe_copy_backward();
assert(!desc.empty(... | std::string d = describe_copy_backward();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("reverse order") != std::string::npos || low.find("reverse") != std::string::npos || low.find("backward") != std::string::npos);
assert(low.find("d_last") != std::string::npos |... | api_usage |
36 | devbench-api-usage | cpp | #include <tuple>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// Unpack a tuple using std::tie. std::tie creates a tuple of lvalue references,
// allowing assignment from another tuple. std::ignore can be used to skip elements.
std::tuple<int, std::string, double> get_record() {
re... | return "std::tie creates a tuple of lvalue references to its arguments. When assigned "
"from another tuple, each element of the source is assigned to the corresponding "
"referenced variable. std::ignore can be used as a placeholder to skip elements "
"during unpacking — assignment... | }
int main() {
int id = 0;
std::string name;
unpack_example(id, name);
assert(id == 42);
assert(name == "hello");
int id2 = 0;
unpack_with_ignore(id2);
assert(id2 == 42);
std::string desc = describe_tie();
assert(!desc.empty());
std::cout << "All tests passed." << std::en... | std::string d = describe_tie();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("lvalue reference") != std::string::npos || low.find("lvalue ref") != std::string::npos);
assert(low.find("ignore") != std::string::npos);
assert(low.find("structured binding") != std::st... | api_usage |
37 | devbench-api-usage | cpp | #include <tuple>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <utility>
// Use std::apply to unpack a tuple as function arguments.
// std::apply(f, t) calls f with the elements of t unpacked as arguments.
int add_three(int a, int b, int c) {
return a + b + c;
}
std::strin... | return "std::apply invokes a callable with arguments unpacked from a tuple-like object. "
"Given std::apply(f, t), it calls f(std::get<0>(t), std::get<1>(t), ...) using "
"std::index_sequence to expand the tuple elements as individual function arguments. "
"It works with std::tuple,... | }
int main() {
auto t = std::make_tuple(10, 20, 30);
assert(sum_tuple(t) == 60);
auto p = std::make_pair(std::string("x"), 5);
assert(format_entry(p) == "x=5");
// Works with lambda too
auto result = std::apply([](int a, int b) { return a * b; },
std::make_tuple(6... | std::string d = describe_apply();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("unpack") != std::string::npos || low.find("expand") != std::string::npos);
assert(low.find("tuple") != std::string::npos);
assert(low.find("pair") != std::string::npos);
assert(low.fin... | api_usage |
38 | devbench-api-usage | cpp | #include <new>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <cstring>
// std::launder is a pointer optimization barrier needed when reusing storage
// after placement new, especially when the object has const or reference members.
// Without it, the compiler may optimize based... | return "std::launder is a pointer optimization barrier introduced in C++17. It takes a "
"pointer and returns a pointer to the same address but prevents the compiler from "
"applying optimizations based on the original object's properties. It is required "
"when accessing an object ... | }
int main() {
int result = reuse_storage();
assert(result == 2);
std::string desc = describe_launder();
assert(!desc.empty());
std::cout << "All tests passed." << std::endl;
return 0;
}
| std::string d = describe_launder();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("optimization barrier") != std::string::npos || low.find("pointer barrier") != std::string::npos || low.find("prevents") != std::string::npos);
assert(low.find("placement new") != std... | api_usage |
39 | devbench-api-usage | cpp | #include <type_traits>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <new>
// std::aligned_storage provides a type suitable for use as uninitialized
// storage for an object of given size and alignment. You must manually
// construct and destroy objects in this storage using pl... | return "std::aligned_storage<Len, Align>::type provides a POD type suitable for use "
"as uninitialized storage for any object whose size is at most Len and whose "
"alignment requirement is at most Align. The storage is raw — no constructor or "
"destructor is called automatically.... | }
int main() {
SimpleOptional<int> opt;
assert(!opt.has_value());
opt.emplace(42);
assert(opt.has_value());
assert(opt.value() == 42);
SimpleOptional<std::string> sopt;
sopt.emplace("hello");
assert(sopt.value() == "hello");
std::string desc = describe_aligned_storage();
asser... | std::string d = describe_aligned_storage();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("raw") != std::string::npos || low.find("uninitialized") != std::string::npos);
assert(low.find("alignment") != std::string::npos || low.find("align") != std::string::npos);
a... | api_usage |
40 | devbench-api-usage | cpp | #include <memory>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// A class that can safely create shared_ptr to itself from member functions.
// Must inherit from enable_shared_from_this and must be managed by shared_ptr.
class Widget : public std::enable_shared_from_this<Widget> {
... | return "std::enable_shared_from_this<T> is a CRTP base class that allows an object to "
"safely create additional shared_ptr instances pointing to itself via the "
"shared_from_this() member function. The class internally stores a weak_ptr that "
"is initialized when the object is f... | }
int main() {
auto w = std::make_shared<Widget>(1);
auto w2 = w->get_shared();
assert(w.get() == w2.get());
assert(w.use_count() == 2);
// Calling shared_from_this without shared_ptr ownership throws
bool threw = false;
try {
Widget raw(2);
raw.get_shared(); // Should thro... | std::string d = describe_enable_shared_from_this();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("shared_from_this") != std::string::npos);
assert(low.find("shared_ptr") != std::string::npos);
assert(low.find("bad_weak_ptr") != std::string::npos);
assert(low.find(... | api_usage |
41 | devbench-api-usage | cpp | #include <mutex>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <thread>
// Demonstrate std::scoped_lock locking multiple mutexes without deadlock.
// scoped_lock uses a deadlock-avoidance algorithm (like std::lock) internally.
std::mutex m1, m2;
int shared_a = 0, shared_b = 0;
... | return "std::scoped_lock is a RAII mutex wrapper introduced in C++17 that locks one or "
"more mutexes upon construction and unlocks them upon destruction. When given "
"multiple mutexes, it uses a deadlock-avoidance algorithm (equivalent to std::lock) "
"to lock them in an order th... | }
int main() {
shared_a = 100;
shared_b = 0;
std::thread t1(transfer, 30);
std::thread t2(transfer, 20);
t1.join();
t2.join();
assert(shared_a == 50);
assert(shared_b == 50);
std::string desc = describe_scoped_lock();
assert(!desc.empty());
std::cout << "All tests passed... | std::string d = describe_scoped_lock();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("deadlock") != std::string::npos);
assert(low.find("raii") != std::string::npos);
assert(low.find("ctad") != std::string::npos || low.find("class template argument deduction") != ... | api_usage |
42 | devbench-api-usage | cpp | #include <mutex>
#include <condition_variable>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// A counting semaphore implementation using mutex + condition_variable.
// Models the C++20 std::counting_semaphore pattern in C++17.
// acquire() blocks if count is 0, release() increments cou... | return "A counting semaphore maintains an internal counter initialized to a given value. "
"acquire() blocks the calling thread (using condition_variable::wait) until the "
"counter is positive, then decrements it atomically. release() increments the "
"counter (up to a maximum coun... | }
int main() {
Semaphore sem(2);
assert(sem.try_acquire());
assert(sem.try_acquire());
assert(!sem.try_acquire()); // count is 0
sem.release();
assert(sem.try_acquire());
std::string desc = describe_counting_semaphore();
assert(!desc.empty());
std::cout << "All tests passed." << ... | std::string d = describe_counting_semaphore();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("acquire") != std::string::npos && low.find("block") != std::string::npos);
assert(low.find("release") != std::string::npos && low.find("increment") != std::string::npos);
... | api_usage |
43 | devbench-api-usage | cpp | #include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <cstddef>
#include <array>
// A lightweight non-owning view over a contiguous range of elements,
// modeled after C++20 std::span. Uses raw pointer + size in C++17.
template <typename T>
class Span {
T* data_;
... | return "A span is a non-owning view over a contiguous sequence of elements. It stores "
"a pointer and a size, providing lightweight access without copying. Unlike "
"containers, it does not manage the lifetime of the underlying data — the caller "
"must ensure the data outlives the... | }
int main() {
std::vector<int> v = {10, 20, 30, 40, 50};
Span<int> s(v);
assert(s.size() == 5);
assert(s[2] == 30);
auto sub = s.subspan(1, 3);
assert(sub.size() == 3);
assert(sub[0] == 20);
assert(sub[2] == 40);
int arr[] = {1, 2, 3};
Span<int> sa(arr);
assert(sa.size() ... | std::string d = describe_span();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("non-owning") != std::string::npos || low.find("non owning") != std::string::npos);
assert(low.find("contiguous") != std::string::npos);
assert(low.find("static") != std::string::npos &&... | api_usage |
44 | devbench-api-usage | cpp | #include <any>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// Demonstrate std::any_cast with different overloads:
// 1. Value cast: any_cast<T>(any) — throws bad_any_cast on type mismatch
// 2. Pointer cast: any_cast<T>(&any) — returns nullptr on type mismatch
int safe_get_int(const ... | return "std::any_cast is used to extract a value from std::any. The value/reference "
"overload any_cast<T>(any) returns a copy of the stored value and throws "
"std::bad_any_cast if the stored type does not match T. The pointer overload "
"any_cast<T>(&any) returns a pointer to the... | }
int main() {
std::any a = 42;
assert(safe_get_int(a) == 42);
assert(safe_get_int(std::any(std::string("hello"))) == -1);
std::any s = std::string("world");
assert(value_get_string(s) == "world");
bool threw = false;
try {
value_get_string(std::any(123));
} catch (const std::... | std::string d = describe_any_cast();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("bad_any_cast") != std::string::npos);
assert(low.find("throw") != std::string::npos);
assert(low.find("nullptr") != std::string::npos);
assert(low.find("pointer") != std::string::np... | api_usage |
45 | devbench-api-usage | cpp | #include <memory>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
// Demonstrate weak_ptr::lock() — atomically creates a shared_ptr from a weak_ptr.
// Returns an empty shared_ptr if the managed object has been deleted.
// This is thread-safe unlike checking expired() then constructing sh... | return "std::weak_ptr::lock() atomically creates a shared_ptr that shares ownership of "
"the managed object. If the weak_ptr has expired (the managed object was deleted), "
"lock() returns an empty shared_ptr (not null pointer — an empty shared_ptr with "
"use_count() == 0). This i... | }
int main() {
Observer obs;
{
auto sp = std::make_shared<int>(99);
obs.watch(sp);
assert(obs.read_or_default(-1) == 99);
assert(obs.is_alive());
assert(obs.use_count() == 1);
}
// sp destroyed
assert(!obs.is_alive());
assert(obs.read_or_default(-1) == -1... | std::string d = describe_weak_ptr_lock();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("shared_ptr") != std::string::npos);
assert(low.find("empty") != std::string::npos || low.find("null") != std::string::npos);
assert(low.find("thread-safe") != std::string::npos... | api_usage |
46 | devbench-api-usage | cpp | #include <tuple>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <utility>
// Concatenate tuples using std::tuple_cat.
// It creates a new tuple by concatenating all elements from the input tuples.
// Also works with pairs (which are tuple-like).
auto concat_example() {
auto... | return "std::tuple_cat concatenates multiple tuple-like objects into a single new tuple. "
"The resulting tuple contains all elements from each input in order, and its size "
"is the sum of the sizes of all input tuples. It works with std::tuple, std::pair, "
"and std::array since t... | }
int main() {
auto r1 = concat_example();
static_assert(std::tuple_size<decltype(r1)>::value == 4);
assert(std::get<0>(r1) == 1);
assert(std::get<2>(r1) == "hi");
auto r2 = concat_with_pair();
static_assert(std::tuple_size<decltype(r2)>::value == 3);
assert(std::get<0>(r2) == 10);
ass... | std::string d = describe_tuple_cat();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("concatenat") != std::string::npos);
assert(low.find("new tuple") != std::string::npos || low.find("new std::tuple") != std::string::npos || low.find("single tuple") != std::string:... | api_usage |
47 | devbench-api-usage | cpp | #include <algorithm>
#include <functional>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
// Use std::search with different searcher objects (C++17).
// The searcher overload: std::search(first, last, searcher)
// Available searchers: default_searcher, boyer_moore_searcher,
// boyer_moore_h... | return "The C++17 std::search overload accepts a Searcher object that encapsulates the "
"search algorithm and any preprocessing. std::default_searcher uses the basic "
"O(n*m) worst-case algorithm. std::boyer_moore_searcher preprocesses the pattern "
"to build skip tables, achievin... | }
int main() {
std::string text = "the quick brown fox jumps over the lazy dog";
assert(find_pattern_default(text, "fox") == 16);
assert(find_pattern_bm(text, "fox") == 16);
assert(find_pattern_default(text, "cat") == std::string::npos);
assert(find_pattern_bm(text, "lazy") == 35);
std::string... | std::string d = describe_search_searchers();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("searcher") != std::string::npos);
assert(low.find("preprocessing") != std::string::npos || low.find("preprocess") != std::string::npos || low.find("skip table") != std::stri... | api_usage |
48 | devbench-api-usage | cpp | #include <set>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <map>
// Demonstrate std::set::extract — removes a node from the set without
// copying or moving the element. Returns a node_handle that owns the element.
// The key can be modified before reinsertion.
std::set<int>... | return "std::set::extract (C++17) removes a node from the container and returns a "
"node_handle that holds sole ownership of the extracted element. No copy or move "
"of the element value occurs during extraction — the node is simply unlinked from "
"the tree. The node_handle provi... | }
int main() {
std::set<int> s = {10, 20, 30, 40};
auto result = modify_key(s, 20, 25);
assert(result.count(20) == 0);
assert(result.count(25) == 1);
assert(result.size() == 4);
// Extract non-existent key
auto nh = s.extract(999);
assert(nh.empty());
std::string desc = describe_... | std::string d = describe_set_extract();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("node") != std::string::npos && low.find("handle") != std::string::npos);
assert(low.find("no copy") != std::string::npos || low.find("without copy") != std::string::npos || low.f... | api_usage |
49 | devbench-api-usage | cpp | #include <cstddef>
#include <string>
#include <iostream>
#include <cassert>
#include <algorithm>
#include <cstdlib>
#include <new>
// A monotonic (bump) allocator: allocations advance a pointer, individual
// deallocation is a no-op, all memory is freed at once on destruction.
// Models std::pmr::monotonic_buffer_reso... | return "A monotonic buffer resource (std::pmr::monotonic_buffer_resource) is a bump "
"allocator that advances a pointer for each allocation. Individual deallocation "
"is a no-op — memory is only freed when the resource is destroyed or reset. This "
"makes allocation extremely fast... | }
int main() {
alignas(16) char buf[256];
MonotonicAllocator alloc(buf, sizeof(buf));
int* p1 = static_cast<int*>(alloc.allocate(sizeof(int)));
*p1 = 42;
int* p2 = static_cast<int*>(alloc.allocate(sizeof(int)));
*p2 = 99;
assert(*p1 == 42);
assert(*p2 == 99);
assert(alloc.used() >... | std::string d = describe_monotonic_buffer();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("bump") != std::string::npos || low.find("monotonic") != std::string::npos);
assert(low.find("no-op") != std::string::npos || low.find("no op") != std::string::npos || low.fi... | api_usage |
50 | devbench-api-usage | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <cassert>
#include <utility>
// std::iter_swap vs std::swap:
// iter_swap(a, b) swaps the values pointed to by iterators a and b
// swap(a, b) swaps two values directly via references
void demo_iter_swap(std::vector<int>& v, int i, ... | return "std::iter_swap(a, b) swaps the values that two iterators point to by first "
"dereferencing them. It is equivalent to std::swap(*a, *b) but uses argument-"
"dependent lookup (ADL) to find a specialized swap for the value type if one "
"exists. std::swap(a, b) takes two refer... | }
int main() {
std::vector<int> v = {10, 20, 30};
demo_iter_swap(v, 0, 2);
assert((v == std::vector<int>{30, 20, 10}));
int a = 5, b = 10;
demo_swap(a, b);
assert(a == 10 && b == 5);
std::string desc = describe_iter_swap_vs_swap();
assert(!desc.empty());
std::cout << "All tests p... | std::string d = describe_iter_swap_vs_swap();
std::string low = d;
std::transform(low.begin(), low.end(), low.begin(), ::tolower);
assert(low.find("dereference") != std::string::npos || low.find("deref") != std::string::npos || low.find("*a") != std::string::npos);
assert(low.find("iterator") != std::string::npos);
ass... | api_usage |
1 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <cmath>
#include <sstream>
using namespace std;
struct ClaimResult {
string status;
double patient;
double plan;
double deductibleApplied;
double coinsuranceApplied;
};
struct Adjudicator {
double cop... | ClaimResult res;
if (processedClaims.count(claimId)) { res.status = "DUPLICATE"; res.patient = res.plan = res.deductibleApplied = res.coinsuranceApplied = 0; return res; }
auto it = allowedRates.find(code);
if (it == allowedRates.end() || (requiresAuth.count(code) && !authorizedClaims.co... | }
};
int main() {
Adjudicator adj;
adj.reset();
ClaimResult r1 = adj.adjudicateLine("C1", "THERAPY", 400.0, false, 20.0);
// allowed=320, remaining=300, copay=30, ded=270, coins=0, patient=300
assert(r1.status == "PAID");
assert(abs(r1.patient - 300.0) < 0.01);
assert(abs(r1.deductibleA... | assert(visibleOk == 1);
// Duplicate: must return DUPLICATE, no mutation
int ledgerBefore = (int)adj.claimLedger.size();
double oopBefore = adj.ytdOop;
ClaimResult dup = adj.adjudicateLine("C1", "THERAPY", 999.0, false, 0.0);
assert(dup.status == "DUPLICATE");
assert((int)adj.claimLedger.siz... | code_purpose_understanding |
2 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <set>
#include <cassert>
#include <algorithm>
#include <cmath>
using namespace std;
struct Lot {
string lotId;
int qty;
int expiryDay;
bool quarantined;
};
struct AllocResult {
string status; // "ALLOCATED", "PARTIAL", "DUPLICATE", "INSUFFICI... | AllocResult res;
if (processedTickets.count(ticketId)) { res.status = "DUPLICATE"; res.totalAllocated = 0; return res; }
// Filter eligible lots
struct EligibleLot { int idx; int expiryDay; int qty; };
vector<EligibleLot> eligible;
for (int i = 0; i < (int)lots.size(); i+... | }
};
int main() {
Warehouse wh;
wh.reset();
wh.addLot("L1", 20, 100, false);
wh.addLot("L2", 30, 80, false);
wh.addLot("L3", 10, 120, true); // quarantined
AllocResult r1 = wh.allocate("T1", 25, 10);
assert(r1.status == "ALLOCATED");
assert(r1.totalAllocated == 25);
// FEFO: ... | assert(visibleOk == 1);
// Duplicate check
int logBefore = (int)wh.auditLog.size();
AllocResult dup = wh.allocate("T1", 99, 10);
assert(dup.status == "DUPLICATE");
assert((int)wh.auditLog.size() == logBefore);
// Insufficient: atomic failure (no lot mutation)
int l2Before = wh.lots[1].q... | code_purpose_understanding |
3 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <set>
#include <cassert>
#include <cmath>
using namespace std;
struct PaymentResult {
string status; // "APPLIED", "DUPLICATE", "RECOVERY", "PAID_OFF"
double toFees;
double toInterest;
double toPrincipal;
double toEscrow;
double toSuspense;
}... | PaymentResult res;
if (processedPayments.count(paymentId)) { res = {"DUPLICATE",0,0,0,0,0}; return res; }
processedPayments.insert(paymentId);
if (status == "CHARGED_OFF") {
suspenseBalance = r2(suspenseBalance + amount);
paymentLedger.push_back("PAY:" + paymentId... | }
};
int main() {
LoanAccount loan;
loan.reset(10000.0, 200.0, 100.0);
loan.lateFeePending = true;
PaymentResult r1 = loan.applyPayment("P1", 500.0);
// Late fee injected: fees=75, waterfall: 75 fees + 200 interest + 100 escrow + 125 principal
assert(r1.status == "APPLIED");
assert(abs... | assert(visibleOk == 1);
// Duplicate
int ledgerBefore = (int)loan.paymentLedger.size();
PaymentResult dup = loan.applyPayment("P1", 9999.0);
assert(dup.status == "DUPLICATE");
assert((int)loan.paymentLedger.size() == ledgerBefore);
// Late fee already applied — should NOT add again
loan... | code_purpose_understanding |
4 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <set>
#include <cassert>
#include <cmath>
#include <algorithm>
using namespace std;
struct PayStub {
string status;
double grossPay;
double retirement;
double tax;
double healthDeduction;
double garnishment;
double netPay;
};
struct PayrollEngin... | PayStub ps;
if (processedRuns.count(runId)) { ps.status = "DUPLICATE"; ps.grossPay = ps.retirement = ps.tax = ps.healthDeduction = ps.garnishment = ps.netPay = 0; return ps; }
processedRuns.insert(runId);
double retCap = r2(annualRetirementCap - ytdRetirement);
if (retCap < 0) re... | }
};
int main() {
PayrollEngine pe;
pe.reset();
PayStub s1 = pe.computePay("R1", 5000.0);
// retirement: 5000*0.06=300
// taxable: 4700
// tax: 1000*0.10 + 2000*0.22 + 1700*0.32 = 100+440+544 = 1084
// health: 250
// preNet: 5000-300-1084-250 = 3366
// garn: 3366*0.15 = 504.90
... | assert(visibleOk == 1);
// Duplicate
PayStub dup = pe.computePay("R1", 9999.0);
assert(dup.status == "DUPLICATE");
assert(abs(pe.ytdGross - 5000.0) < 0.01);
// Retirement cap: set ytd near cap
pe.ytdRetirement = 22800.0;
PayStub s2 = pe.computePay("R2", 5000.0);
// cap: 23000 - 2280... | code_purpose_understanding |
5 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <algorithm>
#include <cmath>
using namespace std;
struct FulfillResult {
string status; // "FULFILLED", "PARTIAL", "DUPLICATE", "CANCELLED", "NO_STOCK"
int shipped;
int backordered;
string label; // shippin... | FulfillResult res;
if (processedOrders.count(orderId)) { res = {"DUPLICATE", 0, 0, ""}; return res; }
if (cancelledOrders.count(orderId)) { res = {"CANCELLED", 0, 0, ""}; return res; }
processedOrders.insert(orderId);
auto it = inventory.find(sku);
int avail = (it != inve... | }
};
int main() {
FulfillmentCenter fc;
fc.reset();
fc.inventory["WIDGET"] = 15;
fc.inventory["GADGET"] = 5;
FulfillResult r1 = fc.fulfill("O1", "WIDGET", 10);
assert(r1.status == "FULFILLED");
assert(r1.shipped == 10);
assert(r1.label == "SHP-1001");
assert(fc.inventory["WIDGE... | assert(visibleOk == 1);
// Duplicate
FulfillResult dup = fc.fulfill("O1", "WIDGET", 99);
assert(dup.status == "DUPLICATE");
assert(fc.inventory["WIDGET"] == 5); // no deduction
assert(dup.label == "");
// Cancelled order
fc.cancelledOrders.insert("O3");
FulfillResult canc = fc.fulf... | code_purpose_understanding |
6 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <cmath>
using namespace std;
struct PremiumResult {
string status; // "QUOTED", "DUPLICATE", "INVALID_DATE", "DECLINED"
double annualPremium;
double monthlyPremium;
double discountApplied;
};
struct Premium... | PremiumResult res;
if (processedQuotes.count(quoteId)) { res = {"DUPLICATE", 0, 0, 0}; return res; }
if (age < 18 || age > 85) { processedQuotes.insert(quoteId); quoteLog.push_back("DECLINED:" + quoteId); res = {"DECLINED", 0, 0, 0}; return res; }
if (effectiveMonth < 1 || effectiveMonth... | }
};
int main() {
PremiumCalculator pc;
pc.reset();
PremiumResult r1 = pc.calculatePremium("Q1", 30, {"SMOKER"}, 4, 6);
// base=1200, age factor=1.0, adjusted=1200+400=1600, discount=0.90, final=1440
assert(r1.status == "QUOTED");
assert(abs(r1.annualPremium - 1440.0) < 0.01);
assert(a... | assert(visibleOk == 1);
// Duplicate
PremiumResult dup = pc.calculatePremium("Q1", 99, {}, 0, 1);
assert(dup.status == "DUPLICATE");
// Declined: too young
PremiumResult young = pc.calculatePremium("Q3", 16, {}, 0, 1);
assert(young.status == "DECLINED");
// Declined: too old
Premiu... | code_purpose_understanding |
7 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <cmath>
using namespace std;
struct OrderItem {
string itemName;
double basePrice;
vector<pair<string,double>> modifiers; // name, price
double lineTotal;
};
struct BillResult {
string status; // "... | BillResult res;
if (processedOrders.count(orderId)) { res = {"DUPLICATE",0,0,0,0,0,""}; return res; }
if (items.empty()) { res = {"EMPTY_ORDER",0,0,0,0,0,""}; return res; }
// Check availability first (before any mutation)
for (auto& [name, mods] : items) {
if (unavai... | }
};
int main() {
Restaurant rest;
rest.reset();
vector<pair<string, vector<string>>> items1 = {
{"BURGER", {"CHEESE", "BACON"}},
{"SALAD", {}}
};
BillResult r1 = rest.processOrder("ORD1", items1, 0.18, 2);
// BURGER: 12.50+1.50+2.00=16.00, SALAD: 9.00, subtotal=25.00
/... | assert(visibleOk == 1);
// Duplicate
BillResult dup = rest.processOrder("ORD1", items1, 0.0, 1);
assert(dup.status == "DUPLICATE");
assert((int)rest.orderLog.size() == 1);
// Empty order
BillResult empty = rest.processOrder("ORD2", {}, 0.18, 1);
assert(empty.status == "EMPTY_ORDER");
... | code_purpose_understanding |
8 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cassert>
#include <cmath>
using namespace std;
struct LendResult {
string status; // "CHECKED_OUT", "RENEWED", "RETURNED", "DUPLICATE",
// "LIMIT_REACHED", "ON_HOLD", "NOT_FOUND", "ALREADY_OUT", "LOST"... | LendResult res;
if (action == "CHECKOUT") {
if (checkedOut.count(bookId)) { res = {"ALREADY_OUT", 0, 0}; return res; }
if (holdQueue.count(bookId) && !holdQueue[bookId].empty()) { if (holdQueue[bookId].front() != memberId) { res = {"ON_HOLD", 0, 0}; return res; } holdQueue[bookId... | }
};
int main() {
Library lib;
lib.reset();
LendResult r1 = lib.processTransaction("B1", "M1", "CHECKOUT", 1);
assert(r1.status == "CHECKED_OUT");
assert(r1.dueDay == 15);
assert(lib.memberBorrowCount["M1"] == 1);
LendResult r2 = lib.processTransaction("B1", "M1", "RENEW", 10);
as... | assert(visibleOk == 1);
// Already out
lib.processTransaction("B2", "M2", "CHECKOUT", 1);
LendResult alrOut = lib.processTransaction("B2", "M3", "CHECKOUT", 1);
assert(alrOut.status == "ALREADY_OUT");
// Borrowing limit
lib.borrowLimit = 2;
lib.processTransaction("B3", "M3", "CHECKOUT",... | code_purpose_understanding |
9 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <cmath>
using namespace std;
struct ReservationResult {
string status; // "CONFIRMED", "DUPLICATE", "NO_ROOMS", "CANCELLED",
// "CANCEL_FEE", "NO_SHOW", "CHECKED_IN", "NOT_FOUND"
double totalR... | ReservationResult res;
if (action == "BOOK") {
if (processedReservations.count(resId)) { res = {"DUPLICATE",0,0,0,0}; return res; }
if (roomInventory.find(roomType) == roomInventory.end() || roomInventory[roomType] <= 0) { res = {"NO_ROOMS",0,0,0,0}; return res; }
pro... | }
};
int main() {
Hotel hotel;
hotel.reset();
// Book a standard room in July (peak), 3 nights, early bird (booked 40 days ahead)
ReservationResult r1 = hotel.processReservation("R1", "BOOK", "STANDARD", 3, 7, 1, 41, 1);
// nightly = 150 * 1.5 = 225, early bird: 225 * 0.85 = 191.25, total = 57... | assert(visibleOk == 1);
// Duplicate booking
hotel.processReservation("R2", "BOOK", "STANDARD", 2, 5, 1, 20, 1);
ReservationResult dup = hotel.processReservation("R2", "BOOK", "STANDARD", 2, 5, 1, 20, 1);
assert(dup.status == "DUPLICATE");
// No rooms
hotel.roomInventory["SUITE"] = 0;
R... | code_purpose_understanding |
10 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <map>
#include <set>
#include <cassert>
#include <cmath>
#include <algorithm>
#include <numeric>
using namespace std;
struct GradeResult {
string status; // "GRADED", "DUPLICATE", "INCOMPLETE"
double finalPercent;
string letterGrade;
double gpaPoints;... | GradeResult res;
if (processedStudents.count(studentId)) { res = {"DUPLICATE", 0, "", 0}; return res; }
// Check all categories present
for (auto& [cat, wt] : categoryWeights) {
if (categoryScores.find(cat) == categoryScores.end()) {
res = {"INCOMPLETE", 0, ""... | }
};
int main() {
GradeBook gb;
gb.reset();
map<string, vector<double>> scores = {
{"HOMEWORK", {90, 85, 70, 95, 80, 60}}, // drop 2 lowest (60,70), avg of {80,85,90,95}=87.5
{"MIDTERM", {78}},
{"FINAL", {88}},
{"PARTICIPATION", {95}}
};
GradeResult r1 = gb.co... | assert(visibleOk == 1);
// Duplicate
GradeResult dup = gb.computeGrade("S1", scores, 0);
assert(dup.status == "DUPLICATE");
// Incomplete: missing category
map<string, vector<double>> missing = {
{"HOMEWORK", {90}},
{"MIDTERM", {80}}
};
GradeResult inc = gb.computeGrade(... | code_purpose_understanding |
11 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <cmath>
struct SubBilling {
std::string status; // "trial","active","grace","dunning","cancelled"
int trialDaysLeft;
double monthlyRate;
double balance; // outstanding balance
double paidTotal;
int failedAttempts; // consec... | void advanceDay() {
if (status == "trial") {
trialDaysLeft--;
if (trialDaysLeft <= 0) { status = "active"; balance += monthlyRate * (30 - daysSinceRenewal) / 30.0; auditLog.push_back("DAY:active"); }
else auditLog.push_back("DAY:trial");
} else if (status == "acti... |
// Attempt payment of given amount. Rules:
// 1. If status is "cancelled" or "trial", return false.
// 2. Subtract amount from balance (can go negative = credit).
// 3. Add amount to paidTotal.
// 4. Reset failedAttempts to 0. If status was "grace" or "dunning", set to "active".
// 5. Log ... |
// Hidden: grace -> dunning transition
SubBilling s3(50.0, 1);
s3.advanceDay(); // trial->active
for (int i = 0; i < 5; i++) s3.advanceDay(); // 5 days active
s3.failPayment(); s3.failPayment(); s3.failPayment(); // 3 failures -> grace
assert(s3.status == "grace");
assert(s3.daysSinceRenewa... | code_purpose_understanding |
12 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <sstream>
struct ShipItem {
std::string sku;
int qty;
double weightEach; // lbs
double lengthIn, widthIn, heightIn;
double valueEach;
};
struct Shipment {
std::string status; // "pending","pic... | void pick() {
if (status != "pending" || items.empty()) return;
totalWeight = 0;
dimWeight = 0;
double totalValue = 0;
for (auto& it : items) {
totalWeight += it.weightEach * it.qty;
dimWeight += (it.lengthIn * it.widthIn * it.heightIn * it.qty) / 139.... |
// Pack: verify items are picked, set status to "packed", log "PACK".
void pack() {
if (status != "picked") return;
status = "packed";
auditLog.push_back("PACK");
}
// Ship: verify packed, set status to "shipped", log "SHIP:<trackingNumber>".
void ship() {
if (statu... |
// Hidden: dimensional weight dominates, insurance triggered, international
Shipment s2(true, "CA");
s2.addItem({"BIG", 1, 2.0, 30, 20, 15, 600.0});
s2.pick();
// dimWeight = (30*20*15*1)/139 = 9000/139 ≈ 64.75
// totalWeight = 2.0, billable = ceil(64.75) = 65
assert(s2.billableWeight == 65... | code_purpose_understanding |
13 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <set>
#include <cmath>
struct LeaveManager {
double vacationBalance; // in days (supports half-days as 0.5)
double sickBalance;
double carryoverLimit; // max days carried over from previous year
int unpaidDaysTaken;
std::set<int... | std::string requestLeave(const std::string& type, int day, bool halfDay) {
double deduction = halfDay ? 0.5 : 1.0;
if (type == "vacation") {
if (blackoutDays.count(day)) return "BLACKOUT";
if (!managerApproved) return "NO_APPROVAL";
if (vacationBalance < deduction... |
// Year-end carryover: cap vacationBalance at carryoverLimit, reset sick to given amount.
void yearEndReset(double newSickDays) {
if (vacationBalance > carryoverLimit)
vacationBalance = carryoverLimit;
sickBalance = newSickDays;
unpaidDaysTaken = 0;
managerApproved =... |
// Hidden: half-day vacation
LeaveManager lm2(2.0, 1.0, 1.0);
lm2.approveVacation();
assert(lm2.requestLeave("vacation", 1, true) == "OK");
assert(std::abs(lm2.vacationBalance - 1.5) < 0.01);
// Approval revoked even for half-day
assert(lm2.requestLeave("vacation", 2, true) == "NO_APPROVAL"... | code_purpose_understanding |
14 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
struct OrderResult {
std::string status; // "FILLED","PARTIAL","REJECTED","MARGIN_FAIL"
int filledQty;
double avgPrice;
double commission;
int settlementDay;
};
struct Trading... | OrderResult executeBuy(const std::string& orderId, const std::string& symbol, const std::string& orderType, int requestedQty, double limitPrice) {
if (processedOrders.count(orderId)) return {"DUPLICATE", 0, 0, 0, 0};
processedOrders.insert(orderId);
auto savedBook = askBook; double totalCost... |
};
int main() {
TradingEngine eng(10000.0, 5000.0);
eng.addAsk(100.0, 10);
eng.addAsk(101.0, 20);
eng.addAsk(105.0, 5);
// Market buy 15 shares: fills 10@100 + 5@101 = 1505, commission max(1, 1.505)=1.505
auto r1 = eng.executeBuy("O1", "AAPL", "MARKET", 15, 0);
assert(r1.status == "FILLED... |
// Hidden: duplicate order
TradingEngine eng2(10000.0, 5000.0);
eng2.addAsk(50.0, 10);
auto rd1 = eng2.executeBuy("X1", "GOOG", "MARKET", 5, 0);
assert(rd1.status == "FILLED");
auto rd2 = eng2.executeBuy("X1", "GOOG", "MARKET", 5, 0);
assert(rd2.status == "DUPLICATE");
assert(eng2.posit... | code_purpose_understanding |
15 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
struct Milestone {
std::string id;
std::string name;
int durationDays;
double budget;
double spent;
int progress; // 0-100
std::vector<std::string> dependencies; // mil... | std::string updateProgress(const std::string& msId, int newProgress, double additionalSpend) {
auto it = milestones.find(msId);
if (it == milestones.end()) return "NOT_FOUND";
Milestone& ms = it->second;
for (auto& dep : ms.dependencies) {
if (!milestones[dep].completed) ... |
// Compute overall project progress: weighted average by budget.
// progress = sum(milestone.progress * milestone.budget) / totalBudget
double overallProgress() const {
if (totalBudget == 0) return 0;
double sum = 0;
for (auto& [id, ms] : milestones) {
sum += ms.progress... |
// Hidden: OVER_BUDGET flag
Project p2;
p2.addMilestone({"A", "TaskA", 5, 500, 0, 0, {}, false});
p2.updateProgress("A", 80, 600);
assert(p2.statusLog.back().find("OVER_BUDGET") != std::string::npos);
// Hidden: both flags at once
Project p3;
p3.addMilestone({"B", "TaskB", 5, 100, 0, 0... | code_purpose_understanding |
16 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
struct Appointment {
std::string apptId;
std::string patientId;
std::string providerId;
int slot; // time slot number
double copay;
std::string status; // "CONFIRMED","CANC... | std::string bookAppointment(const std::string& patientId, const std::string& providerId, int slot, const std::string& insurance) {
if (providerBlocked[providerId].count(slot)) return "PROVIDER_UNAVAILABLE";
std::string apptId = "A" + std::to_string(nextApptId++);
double rate = insuranceRates... |
// Cancel an appointment. Rules:
// 1. Find appointment by apptId. If not found or already cancelled, return "NOT_FOUND".
// 2. Set status to "CANCELLED".
// 3. Remove from providerSchedule and patientSchedule.
// 4. If there's anyone on waitlist for that provider+slot, promote first entry:
... |
// Hidden: patient conflict
ClinicScheduler cs2;
cs2.bookAppointment("PA", "Dr1", 1, "none");
assert(cs2.bookAppointment("PA", "Dr2", 1, "none") == "PATIENT_CONFLICT");
// Hidden: unknown insurance defaults to $100
ClinicScheduler cs3;
cs3.bookAppointment("PB", "Dr1", 2, "Unknown");
as... | code_purpose_understanding |
17 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <cmath>
struct CartItem {
std::string sku;
std::string category; // "electronics","clothing","food","luxury"
double price;
int qty;
};
struct Coupon {
std::string code;
double dis... | CheckoutResult checkout(int currentTime, const std::string& couponCode, bool paymentAuthorized) {
if (currentTime - cartCreatedTime > cartExpiryMinutes) return {"EXPIRED", 0, 0, 0, 0, 0};
for (auto& item : items) if (item.qty > inventory[item.sku]) return {"INSUFFICIENT_INVENTORY", 0, 0, 0, 0, 0};
... |
};
int main() {
CartProcessor cp(0, 30); // created at time 0, expires after 30 min
cp.setInventory("PHONE", 10);
cp.setInventory("SHIRT", 20);
cp.addItem({"PHONE", "electronics", 500.0, 1});
cp.addItem({"SHIRT", "clothing", 30.0, 2});
cp.addCoupon({"SAVE10", 0.10, 50.0, true, {"luxury"}});
... |
// Hidden: cart expiry
CartProcessor cp3(0, 10);
cp3.setInventory("X", 5);
cp3.addItem({"X", "food", 20.0, 1});
auto re = cp3.checkout(11, "", true);
assert(re.status == "EXPIRED");
// Hidden: insufficient inventory
CartProcessor cp4(0, 60);
cp4.setInventory("Y", 2);
cp4.addIte... | code_purpose_understanding |
18 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <map>
#include <cmath>
struct ServiceRecord {
std::string vehicleId;
std::string serviceType;
int mileage;
double laborCost;
double partsCost;
bool warrantyApplied;
bool rentalProvided;
};
struct FleetManager {
struct Vehi... | std::string performService(const std::string& vehicleId, const std::string& serviceType) {
auto it = vehicles.find(vehicleId); if (it == vehicles.end()) return "NOT_FOUND";
Vehicle& v = it->second;
if (v.currentMileage - v.lastServiceMileage < serviceInterval) return "NOT_DUE";
int l... |
void updateMileage(const std::string& id, int newMileage) {
if (vehicles.count(id)) vehicles[id].currentMileage = newMileage;
}
};
int main() {
FleetManager fm(5000, 75.0);
fm.addVehicle("V1", 10000, 36000);
fm.addPart("oil_filter", 5);
fm.addPart("brake_pads", 3);
// Not due yet ... |
// Hidden: out of warranty, parts cost applies
FleetManager fm2(5000, 50.0);
fm2.addVehicle("V2", 40000, 36000); // over warranty
fm2.addPart("brake_pads", 2);
fm2.updateMileage("V2", 45000);
assert(fm2.performService("V2", "brake_service") == "SERVICED");
assert(!fm2.vehicles["V2"].history... | code_purpose_understanding |
19 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <cmath>
struct EscrowAccount {
double salePrice;
double earnestDeposit;
double escrowBalance; // funds held
bool inspectionPassed;
bool appraisalPassed;
bool titleClear;
double buyerClosingPct; // fraction of closing costs b... | std::string closeEscrow() {
if (status != "OPEN") return "ALREADY_CLOSED";
if (!inspectionPassed) { status = "CONTINGENCY_FAIL"; escrowBalance = 0; ledger.push_back("REFUND:INSPECTION:" + std::to_string(earnestDeposit)); return "CONTINGENCY_FAIL"; }
if (!appraisalPassed) { status = "CONTINGE... |
};
int main() {
// Standard closing: 300k house, 10k earnest, 60/40 split, 3% closing, tax 6000/yr, HOA 300/mo, day 180
EscrowAccount e1(300000, 10000, 0.60, 0.03, 6000, 300, 180);
e1.passInspection();
e1.passAppraisal();
e1.clearTitle();
auto r1 = e1.closeEscrow();
assert(r1 == "CLOSED");... |
// Hidden: inspection failure -> full refund
EscrowAccount e2(500000, 20000, 0.50, 0.02, 8000, 400, 100);
// Don't pass inspection
e2.passAppraisal();
e2.clearTitle();
auto r2 = e2.closeEscrow();
assert(r2 == "CONTINGENCY_FAIL");
assert(e2.escrowBalance == 0);
// Ledger should have ... | code_purpose_understanding |
20 | devbench-code-purpose-understanding | cpp | #include <cassert>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
struct EnergyBill {
double kwhUsed;
double kwhGenerated; // solar/net metering
double peakDemandKw;
double powerFactor; // 0-1
bool isEstimated;
double tieredCharge;
double demandCharge;
... | EnergyBill computeBill(double kwhUsed, double kwhGenerated, double peakDemandKw, double powerFactor, bool isEstimated, double peakFraction) {
EnergyBill bill; bill.isEstimated = isEstimated; bill.billType = isEstimated ? "ESTIMATED" : "ACTUAL";
if (isEstimated) kwhUsed *= estimationFactor;
b... |
};
int main() {
EnergyBiller biller;
// Basic bill: 800 kWh, no solar, 10kW peak, PF=0.95, actual, no peak hours
auto b1 = biller.computeBill(800, 0, 10, 0.95, false, 0.0);
assert(b1.billType == "ACTUAL");
// tier1: 500*0.08=40, tier2: 300*0.12=36, tier3: 0 -> tiered=76
assert(std::abs(b1.tie... |
// Hidden: estimated reading reduces usage
EnergyBiller b2;
auto r2 = b2.computeBill(1000, 0, 5, 0.95, true, 0.0);
assert(r2.billType == "ESTIMATED");
// adjusted: 1000*0.95 = 950
// tier1: 500*0.08=40, tier2: 450*0.12=54 -> tiered=94
assert(std::abs(r2.tieredCharge - 94.0) < 0.01);
//... | code_purpose_understanding |
21 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <algorithm>
struct BidEntry {
std::string bidder;
double amount;
int timestamp;
};
class Auction {
public:
double starting_price;
double reserve_price;
double min_increment;
int deadline; // auct... | void place_bid(const std::string& bidder, double amount, int timestamp) {
if (!is_active(timestamp))
throw std::runtime_error("auction ended");
if (amount < current_bid + min_increment)
throw std::runtime_error("bid too low");
current_bid = amount;
current_win... | };
int main() {
// Auction: start 100, reserve 500, increment 10, deadline 1000, snipe within 60s, extend by 120s
Auction auc(100, 500, 10, 1000, 60, 120);
auc.place_bid("alice", 110, 100);
assert(auc.current_bid == 110);
assert(auc.current_winner == "alice");
assert(!auc.reserve_met);
asse... |
// Hidden assertions
Auction a2(50, 200, 5, 500, 30, 60);
// First bid must be at least starting_price + min_increment = 55
try {
a2.place_bid("x", 54, 10);
assert(false);
} catch (const std::runtime_error&) {}
a2.place_bid("x", 55, 10);
assert(a2.current_bid == 55);
as... | code_purpose_understanding |
22 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
class GymMembership {
public:
std::string member_id;
double monthly_rate;
double enrollment_fee;
double freeze_fee_per_month;
int family_members; // 0 = individual
double family_discount_pct; // ... | void enroll(int days_remaining_in_month, int days_in_month) {
if (status != "pending")
throw std::runtime_error("already enrolled");
status = "active";
double prorated = _discounted_rate() * days_remaining_in_month / days_in_month;
double first_charge = enrollment_fee + p... |
void freeze() {
if (status != "active") throw std::runtime_error("can only freeze active");
status = "frozen";
}
void unfreeze() {
if (status != "frozen") throw std::runtime_error("not frozen");
status = "active";
}
void add_personal_training() { has_personal_train... |
// Individual membership (no family discount)
GymMembership g2("m2", 80, 30, 20, 0, 0.0, 50, 2);
g2.enroll(10, 30); // prorated = 80 * 10/30 = 26.67
assert(std::abs(g2.total_charged - 56.67) < 0.01); // 30 + 26.67
g2.bill_month();
assert(std::abs(g2.total_charged - 136.67) < 0.01); // + 80
... | code_purpose_understanding |
23 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
#include <map>
struct ShipmentDetails {
double actual_weight_lbs;
double length, width, height; // inches for dimensional weight
int zone;
bool residential;
bool signature_required;
bool saturday_deliv... | double calculate(const ShipmentDetails& s) {
double weight = _billable_weight(s);
double base = _base_rate(s.zone, weight);
double fuel = base * fuel_surcharge_pct;
double subtotal = base + fuel;
if (s.residential)
subtotal += residential_fee;
if (s.signat... | };
int main() {
// dim_factor=139, fuel=15%, residential=$5, signature=$3, saturday=1.5x
ShippingCalculator calc(139.0, 0.15, 5.0, 3.0, 1.5);
calc.add_rate(1, 10, 2.0); // zone 1: up to 10 lbs -> $2/lb
calc.add_rate(1, 50, 1.5); // zone 1: 10-50 lbs -> $1.5/lb
calc.add_rate(2, 10, 3.0);
cal... |
// Residential + signature + saturday
ShipmentDetails s4 = {8.0, 10, 10, 10, 1, true, true, true};
double r4 = calc.calculate(s4);
// billable = max(8, 7.19) = 8, base = 8*2 = 16, fuel = 16*0.15 = 2.4
// sub = 16+2.4+5+3 = 26.4, *1.5 = 39.6
assert(std::abs(r4 - 39.6) < 0.1);
// Zone 2, no ... | code_purpose_understanding |
24 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
struct TicketBooking {
std::string booking_id;
double ticket_price;
double service_fee;
int num_tickets;
double promo_discount; // total discount applied
int loyalty_points_earned;
int purchase_ti... | RefundResult process_refund(const TicketBooking& b, int request_time,
int tickets_to_refund) {
if (tickets_to_refund <= 0 || tickets_to_refund > b.num_tickets)
throw std::runtime_error("invalid refund quantity");
double pct = _refund_pct(request_time, b.ev... | };
int main() {
// full=7200 (2h), 75%=3600 (1h), 50%=1800 (30min)
RefundProcessor proc(7200, 3600, 1800);
// Booking: $50/ticket, $10 service fee, 4 tickets, $20 promo, 100 points
TicketBooking b1 = {"B1", 50.0, 10.0, 4, 20.0, 100, 1000, 10000, "credit"};
// Full refund (3h before event): refund... |
// 50% refund tier
TicketBooking b2 = {"B2", 80.0, 15.0, 2, 0.0, 200, 5000, 8000, "cash"};
RefundResult r4 = proc.process_refund(b2, 8000 - 2000, 1);
// proportion=0.5, promo=0, gross=80, refund=80*0.5=40
assert(r4.refund_tier == "partial_50");
assert(std::abs(r4.refund_amount - 40.0) < 0.01);
... | code_purpose_understanding |
25 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
struct Ingredient {
std::string name;
double quantity;
std::string unit; // "cup", "tsp", "tbsp", "oz", "g"
};
struct NutritionInfo {
double calories;
double protein_g;
double fat_g;
};
class Recipe ... | std::vector<Ingredient> scale(int target_servings) const {
double factor = (double)target_servings / base_servings;
std::vector<Ingredient> scaled;
for (const auto& ing : ingredients) {
double new_qty = ing.quantity * factor;
std::string new_unit = ing.unit;
... | };
int main() {
Recipe r("Pancakes", 4);
r.add_ingredient("flour", 2.0, "cup");
r.add_ingredient("sugar", 3.0, "tbsp");
r.add_ingredient("salt", 0.5, "tsp");
r.add_ingredient("butter", 4.0, "oz");
r.set_nutrition(250, 8, 12);
// Scale to 2 servings (factor = 0.5)
auto s2 = r.scale(2);
... |
// Scale to 8 servings (factor = 2)
auto s8 = r.scale(8);
assert(std::abs(s8[0].quantity - 4.0) < 0.01);
assert(s8[0].unit == "cup");
assert(std::abs(s8[1].quantity - 6.0) < 0.01);
assert(s8[1].unit == "tbsp");
assert(std::abs(s8[3].quantity - 8.0) < 0.01);
// Scale to 3 servings (fact... | code_purpose_understanding |
26 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
#include <numeric>
struct TaxBracket {
double upper_limit; // income up to this amount (0 = no limit)
double rate;
};
class TaxReturn {
public:
std::vector<double> income_sources;
double standard_deduction;
... | void file() {
double gross = _gross_income();
double deduction = std::max(standard_deduction, itemized_deductions);
std::string ded_type = (itemized_deductions > standard_deduction) ? "itemized" : "standard";
double taxable = std::max(0.0, gross - deduction);
audit_trail.push... | };
int main() {
TaxReturn tr(13850);
tr.add_income(50000); // salary
tr.add_income(5000); // freelance
tr.add_income(2000); // interest
// gross = 57000
tr.set_itemized(10000); // less than standard, so standard wins
tr.add_bracket(11000, 0.10);
tr.add_bracket(44725, 0.12);
t... |
// Exact even case
TaxReturn tr3(10000);
tr3.add_income(21000);
tr3.add_bracket(11000, 0.10);
tr3.add_bracket(0, 0.12);
tr3.set_credits(0, 0);
// taxable = 11000, tax = 11000*0.10 = 1100
tr3.set_estimated_payments(1100);
tr3.file();
assert(tr3.filing_status == "even");
asser... | code_purpose_understanding |
27 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
struct Attendee {
std::string name;
std::string dietary; // "none", "vegetarian", "vegan", "halal"
std::vector<std::string> workshops;
};
struct RegResult {
double total_cost;
bool on_waitlist;
int at... | RegResult register_group(const std::vector<Attendee>& group, int timestamp) {
double unit_price = (timestamp <= early_bird_cutoff) ? early_bird_price : base_price;
double discount = _group_discount(group.size());
double discounted_price = unit_price * (1.0 - discount);
int spots = c... | };
int main() {
// base=$500, early=$350, cutoff=1000, workshop=$75, capacity=5
ConferenceReg conf(500, 350, 1000, 75, 5);
conf.add_group_tier(3, 0.10); // 3+ people: 10% off base
conf.add_group_tier(5, 0.20); // 5+ people: 20% off base
// Early bird, group of 3 -> 10% off $350 = $315/person
... |
// All waitlisted (capacity full)
std::vector<Attendee> g3 = {{"Grace", "none", {}}};
RegResult r3 = conf.register_group(g3, 2000);
assert(r3.on_waitlist);
assert(r3.attendees_registered == 0);
assert(r3.attendees_waitlisted == 1);
assert(conf.waitlist.size() == 2);
// Fresh conference... | code_purpose_understanding |
28 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <set>
#include <map>
#include <stdexcept>
#include <cassert>
#include <cmath>
struct FillResult {
bool approved;
std::string denial_reason; // empty if approved
int qty_dispensed;
double copay;
int next_refill_day; // day number when refill is allowed
... | FillResult fill_prescription(const std::string& drug, int requested_qty,
int current_day) {
// 1. Check drug interactions
if (interactions.count(drug)) {
for (const auto& med : current_meds) {
if (interactions[drug].count(med)) {
... | };
int main() {
Pharmacy pharm;
pharm.set_formulary("metformin", 1); // generic $10
pharm.set_formulary("lisinopril", 2); // preferred $25
pharm.set_formulary("humira", 3); // specialty $50
pharm.set_qty_limit("metformin", 90);
pharm.set_qty_limit("humira", 2);
pharm.require_prior_a... |
// Unknown drug defaults to tier 3
FillResult r5 = pharm.fill_prescription("newdrug", 10, 50);
assert(r5.approved);
assert(std::abs(r5.copay - 50.0) < 0.01);
assert(r5.qty_dispensed == 10); // no qty limit for unknown drug
assert(r5.next_refill_day == 80);
// Preferred brand
FillResul... | code_purpose_understanding |
29 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
struct MaterialLine {
std::string name;
double unit_cost;
double quantity;
double waste_factor; // e.g. 0.10 = 10% waste
};
struct LaborLine {
std::string trade; // e.g. "electrician", "plumber"
... | Estimate generate() const {
double mat_cost = 0;
for (const auto& m : materials)
mat_cost += m.unit_cost * m.quantity * (1.0 + m.waste_factor);
double lab_cost = 0;
for (const auto& l : labor)
lab_cost += l.hourly_rate * (l.hours / l.efficiency);
dou... | };
int main() {
ConstructionEstimator est(0.05, 0.15, 0.10);
est.add_material("lumber", 5.0, 100, 0.10); // 5*100*1.1 = 550
est.add_material("concrete", 120.0, 3, 0.05); // 120*3*1.05 = 378
est.add_labor("carpenter", 45.0, 40, 0.80); // 45*(40/0.8) = 2250
est.add_labor("electrician", 65.... |
// Minimal estimate
ConstructionEstimator est2(0.0, 0.0, 0.0);
est2.add_material("paint", 30.0, 5, 0.0); // 150
est2.add_labor("painter", 25.0, 8, 1.0); // 200
Estimate e2 = est2.generate();
assert(std::abs(e2.material_cost - 150.0) < 0.01);
assert(std::abs(e2.labor_cost - 200.0) < 0.01)... | code_purpose_understanding |
30 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <stdexcept>
#include <cassert>
#include <cmath>
#include <algorithm>
struct RentalAgreement {
std::string rental_id;
double daily_rate;
int rental_days;
int miles_included; // free mileage allowance
double per_mile_overage;
double fuel_tank_size... | Invoice process_return(const RentalAgreement& a, const ReturnDetails& d) {
Invoice inv;
inv.base_rental = a.daily_rate * a.rental_days;
inv.line_items.push_back("base:" + std::to_string(inv.base_rental));
int overage_miles = std::max(0, d.miles_driven - a.miles_included);
in... | };
int main() {
RentalReturn rr;
RentalAgreement agr = {"R1", 50.0, 3, 300, 0.25, 15.0, 4.50, 500.0, 15.0, 75.0, 10};
// On time, full tank, no damage, within mileage
ReturnDetails d1 = {200, 1.0, 0, 0.0};
Invoice i1 = rr.process_return(agr, d1);
assert(std::abs(i1.base_rental - 150.0) < 0.01)... |
// Exactly at mileage limit
ReturnDetails d4 = {300, 1.0, 0, 0.0};
Invoice i4 = rr.process_return(agr, d4);
assert(i4.mileage_charge == 0);
assert(std::abs(i4.total - 150.0) < 0.01);
// Exactly at deductible
ReturnDetails d5 = {200, 1.0, 0, 500.0};
Invoice i5 = rr.process_return(agr, d... | code_purpose_understanding |
31 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct TransferResult {
std::string status; // OK, DENIED, LIMIT, FROZEN, UNKNOWN_RECIPIENT
double fee;
double converted; // amount in recipient currency afte... | if (processedIds.count(txId)) return {"DUPLICATE", 0, 0, 0, false};
if (!accounts.count(senderId) || accounts[senderId].frozen)
return {"FROZEN", 0, 0, 0, false};
if (!accounts.count(recipientId) || !verifiedRecipients.count(recipientId))
return {"UNKNOWN_RECIPIENT", 0, 0, 0, false};
aut... | }
int main() {
reset();
addAccount("S1", 50000, false, 0, 20000, "USD");
addAccount("R1", 1000, false, 0, 50000, "EUR");
verifyRecipient("R1");
auto res = transfer("T1", "S1", "R1", 10000);
assert(res.status == "OK");
assert(std::abs(res.fee - 250.0) < 0.01); // 2.5% cross-currenc... |
// idempotent duplicate
reset();
addAccount("S1", 50000, false, 0, 20000, "USD");
addAccount("R1", 1000, false, 0, 50000, "EUR");
verifyRecipient("R1");
transfer("T1", "S1", "R1", 5000);
double balAfter1 = accounts["S1"].balance;
auto dup = transfer("T1", "S1", "R1", 5000);
assert(d... | code_purpose_understanding |
32 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct ClaimResult {
std::string status; // APPROVED, DENIED, DUPLICATE, NO_COVERAGE
double patientOwes;
double planPays;
double deductibleUsed;
bool su... | if (processedClaims.count(claimId)) return {"DUPLICATE", 0, 0, 0, false};
if (!coveredCodes.count(code)) return {"NO_COVERAGE", 0, 0, 0, false};
if (authRequired.count(code) && !authorizedClaims.count(claimId))
return {"DENIED", 0, 0, 0, false};
if (thirdPartyFault) subrogationTriggered = true;
... | }
int main() {
reset();
addCoverage("XRAY");
addCoverage("SURGERY");
requireAuth("SURGERY");
authorize("C2");
auto r1 = adjudicate("C1", "XRAY", 600.0, false);
assert(r1.status == "APPROVED");
assert(std::abs(r1.deductibleUsed - 500.0) < 0.01);
// patient = 500 deductible + 20% of ... |
// duplicate idempotency
reset();
addCoverage("XRAY");
adjudicate("C1", "XRAY", 100, false);
double savedOop = ytdOop;
auto d = adjudicate("C1", "XRAY", 100, false);
assert(d.status == "DUPLICATE");
assert(ytdOop == savedOop);
// uncovered code
reset();
auto nc = adjudicate... | code_purpose_understanding |
33 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct ConvertResult {
std::string status; // OK, TRIAL_ACTIVE, EXPIRED, NO_PAYMENT, ALREADY_PAID
double charged;
double prorated;
int quotaReset;
};
struct User {
std::string... | if (convertedIds.count(convertId)) return {"ALREADY_PAID", 0, 0, 0};
if (!users.count(uid)) return {"ALREADY_PAID", 0, 0, 0};
auto& u = users[uid];
if (u.plan != "trial") return {"ALREADY_PAID", 0, 0, 0};
if (currentDay < u.trialEndDay) return {"TRIAL_ACTIVE", 0, 0, 0};
if (currentDay > u.trialE... | }
int main() {
reset();
addUser("U1", 30, 50, true); // trial ends day 30
auto r = convert("CV1", "U1", "pro", 33); // 3 days into grace
assert(r.status == "OK");
// prorated = 99 * 3/30 = 9.9, charged = 99 - 9.9 = 89.1
assert(std::abs(r.charged - 89.1) < 0.01);
assert(std::abs(r.prorated... |
// idempotent
reset();
addUser("U2", 10, 5, true);
convert("CV2", "U2", "basic", 12);
auto dup = convert("CV2", "U2", "basic", 12);
assert(dup.status == "ALREADY_PAID");
// trial still active
reset();
addUser("U3", 30, 0, true);
auto act = convert("CV3", "U3", "pro", 25);
a... | code_purpose_understanding |
34 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct AwardResult {
std::string status; // AWARDED, INELIGIBLE, DUPLICATE, AID_CAP
double needBased;
double meritBased;
double totalAwarded;
int deadlineD... | if (processedApps.count(appId)) return {"DUPLICATE", 0, 0, 0, 0};
if (!students.count(sid) || !students[sid].enrolled || students[sid].gpa < 2.0)
return {"INELIGIBLE", 0, 0, 0, 0};
auto& st = students[sid];
double need = 0.0;
if (st.familyIncome < needIncomeThreshold)
need = (needInc... | }
int main() {
reset();
addStudent("S1", 3.9, true, 30000, 10000);
auto r = award("A1", "S1", 100);
assert(r.status == "AWARDED");
// need = (50000-30000)/50000 * 15000 = 6000
assert(std::abs(r.needBased - 6000.0) < 0.01);
// merit = (3.9 - 3.0) * 5000 = 4500
assert(std::abs(r.meritBase... |
// duplicate
reset();
addStudent("S2", 3.5, true, 40000, 0);
award("A2", "S2", 50);
auto d = award("A2", "S2", 50);
assert(d.status == "DUPLICATE");
// ineligible — not enrolled
reset();
addStudent("S3", 3.9, false, 20000, 0);
auto ie = award("A3", "S3", 10);
assert(ie.stat... | code_purpose_understanding |
35 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct TicketResult {
std::string status; // FIRED, QUEUED, DUPLICATE, OUT_OF_STOCK, ALLERGEN_BLOCK
int prepTime;
std::string station;
int ticketNumber;
};
st... | if (processedOrders.count(orderId)) return {"DUPLICATE", 0, "", 0};
if (!menu.count(item)) return {"DUPLICATE", 0, "", 0};
auto& mi = menu[item];
for (auto& a : mi.allergens)
if (customerAllergens.count(a)) return {"ALLERGEN_BLOCK", 0, "", 0};
for (auto& [ing, qty] : mi.ingredients)
... | }
int main() {
reset();
maxQueuePerStation = 3;
addMenuItem("burger", "grill", 10, {{"patty", 1}, {"bun", 1}}, {"gluten"});
addMenuItem("salad", "salad", 5, {{"lettuce", 2}}, {"none"});
setInventory("patty", 5);
setInventory("bun", 5);
setInventory("lettuce", 10);
auto r1 = fireOrder("... |
// duplicate
reset();
addMenuItem("fries", "fry", 4, {{"potato", 2}}, {});
setInventory("potato", 20);
fireOrder("O3", "fries", {});
int invAfter = inventory["potato"];
auto d = fireOrder("O3", "fries", {});
assert(d.status == "DUPLICATE");
assert(inventory["potato"] == invAfter);
... | code_purpose_understanding |
36 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct TaxResult {
std::string status; // ASSESSED, DUPLICATE, EXEMPT
double assessedValue;
double totalTax;
double exemptionAmount;
int installments;
int appealDeadlineDay... | if (processedParcels.count(parcelId)) return {"DUPLICATE", 0, 0, 0, 0, 0};
double assessed = marketValue * assessmentRatio;
double exempt = 0;
if (isHomestead) exempt += homesteadExemption;
if (isSenior) exempt += seniorExemption;
if (exempt > assessed) exempt = assessed;
double taxable = as... | }
int main() {
reset();
auto r = assess("P1", 300000, true, false, 100, 60);
// assessed = 300000 * 0.85 = 255000
// exempt = 25000 (homestead only)
// taxable = 230000, tax = 230000 * 0.025 + 100 = 5850
assert(r.status == "ASSESSED");
assert(std::abs(r.assessedValue - 255000) < 0.01);
... |
// duplicate
reset();
assess("P2", 100000, false, false, 0, 10);
auto d = assess("P2", 100000, false, false, 0, 10);
assert(d.status == "DUPLICATE");
// stacked exemptions
reset();
auto s = assess("P3", 200000, true, true, 0, 10);
// assessed = 170000, exempt = 35000, taxable = 135... | code_purpose_understanding |
37 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct ShipResult {
std::string status; // BOOKED, DENIED, DUPLICATE, HAZMAT_DENIED
double baseCharge;
double fuelSurcharge;
double totalCharge;
int transi... | if (processedShipments.count(shipmentId)) return {"DUPLICATE", 0, 0, 0, 0, "", ""};
if (weight <= 0) return {"DENIED", 0, 0, 0, 0, "", ""};
bool isHazmat = hazmatCodes.count(commodityCode) > 0;
if (isHazmat && !hazmatCertifiedCarriers.count(carrier))
return {"HAZMAT_DENIED", 0, 0, 0, 0, "", ""};... | }
int main() {
reset();
addHazmat("FLAM");
certifyCarrier("SafeHaul");
auto r = book("S1", "GENERAL", "AnyCarrier", 5000, {"liftgate", "inside"});
assert(r.status == "BOOKED");
assert(r.mode == "LTL");
// base = 5000*0.35 = 1750, acc = 300, fuel = 2050*0.12 = 246
assert(std::abs(r.base... |
// duplicate
reset();
book("S3", "GENERAL", "X", 1000, {});
auto d = book("S3", "GENERAL", "X", 1000, {});
assert(d.status == "DUPLICATE");
// hazmat not certified
reset();
addHazmat("ACID");
auto h = book("S4", "ACID", "NoCert", 500, {});
assert(h.status == "HAZMAT_DENIED");
... | code_purpose_understanding |
38 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct DisbursementResult {
std::string status; // DISBURSED, DENIED, DUPLICATE, HOLD
double netAmount;
double origFee;
double refund; // if over-award
int disbursement... | if (processedDisb.count(disbId)) return {"DUPLICATE", 0, 0, 0, 0};
if (!loans.count(lid)) return {"DENIED", 0, 0, 0, 0};
auto& ln = loans[lid];
if (!ln.enrollmentVerified || !ln.satisfactoryProgress || !ln.entranceCounseling)
return {"HOLD", 0, 0, 0, 0};
if (ln.disbursed >= ln.awardAmount) r... | }
int main() {
reset();
addLoan("L1", 10000, true, true, true, 6000);
auto r = disburse("D1", "L1", 90);
assert(r.status == "DISBURSED");
// installment = 5000, fee = 5000*0.01057 = 52.85, net = 4947.15
assert(std::abs(r.origFee - 52.85) < 0.01);
assert(std::abs(r.netAmount - 4947.15) < 0.0... |
// duplicate
reset();
addLoan("L2", 8000, true, true, true, 5000);
disburse("D2", "L2", 50);
auto d = disburse("D2", "L2", 50);
assert(d.status == "DUPLICATE");
// HOLD — missing counseling
reset();
addLoan("L3", 8000, true, true, false, 5000);
auto h = disburse("D3", "L3", 50)... | code_purpose_understanding |
39 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct VisitResult {
std::string status; // INVOICED, DUPLICATE
double subtotal;
double discount;
double total;
int followupDay;
};
static double examFee = 65.0;
static double... | if (processedVisits.count(visitId)) return {"DUPLICATE", 0, 0, 0, 0};
double sub = examFee;
for (auto& p : procedures) sub += procedurePrices[p];
for (auto& m : meds) sub += medPrices[m];
if (includeLabWork) sub += labFee;
double rate = 0;
if (hasWellnessPlan) rate += wellnessDiscountRate;
... | }
int main() {
reset();
addProcedure("VACC", 35.0);
addProcedure("DENTAL", 120.0);
addMed("antibiotics", 25.0);
auto r = invoice("V1", {"VACC", "DENTAL"}, {"antibiotics"}, true, true, true, 50);
assert(r.status == "INVOICED");
// sub = 65 + 35 + 120 + 25 + 45 = 290
// rate = 0.10 + 0.0... |
// duplicate
reset();
addProcedure("VACC", 35);
invoice("V2", {"VACC"}, {}, false, false, false, 10);
auto d = invoice("V2", {"VACC"}, {}, false, false, false, 10);
assert(d.status == "DUPLICATE");
// no discounts
reset();
addProcedure("VACC", 35);
auto nd = invoice("V3", {"VAC... | code_purpose_understanding |
40 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct BookingResult {
std::string status; // CONFIRMED, SOLD_OUT, DUPLICATE, INVALID_SEAT
double ticketCost;
double addOns;
double processingFee;
double total;
int loyalty... | if (processedBookings.count(bookingId)) return {"DUPLICATE", 0, 0, 0, 0, 0};
if (!showtimes.count(showtimeId)) return {"DUPLICATE", 0, 0, 0, 0, 0};
auto& st = showtimes[showtimeId];
if (st.takenSeats.count(seat)) return {"INVALID_SEAT", 0, 0, 0, 0, 0};
if (st.sold >= st.capacity) return {"SOLD_OUT",... | }
int main() {
reset();
addShowtime("S1", 100);
auto r = bookTicket("B1", "S1", "A1", "adult", 1, 500);
assert(r.status == "CONFIRMED");
// ticket=14, adds=12, base=26, maxPts=2600, used=500
// disc=500/100=5, afterDisc=21, fee=21*0.08=1.68, total=22.68
assert(std::abs(r.ticketCost - 14) < ... |
// duplicate
reset();
addShowtime("S2", 50);
bookTicket("B2", "S2", "A1", "adult", 0, 0);
auto d = bookTicket("B2", "S2", "A1", "adult", 0, 0);
assert(d.status == "DUPLICATE");
// taken seat
reset();
addShowtime("S3", 50);
bookTicket("B3", "S3", "C5", "child", 0, 0);
auto t... | code_purpose_understanding |
41 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct BookResult {
std::string status; // BOOKED, WAITLISTED, DUPLICATE, CANCEL_PENALTY, NO_PUNCHES
int position; // 0 if booked, waitlist position if waitlist... | if (!members.count(memberId)) return {"NO_PUNCHES", 0, 0, false};
auto& mem = members[memberId];
if (mem.bookedClasses.count(classId))
return {"DUPLICATE", 0, mem.punchCard, false};
if (mem.punchCard <= 0) return {"NO_PUNCHES", 0, 0, false};
auto& cls = classes[classId];
bool equip = fal... | }
int main() {
reset();
addClass("YOGA", 2, true, 1);
addMember("M1", 5);
addMember("M2", 5);
addMember("M3", 5);
auto r1 = bookClass("M1", "YOGA");
assert(r1.status == "BOOKED");
assert(r1.equipmentReserved == true); // first gets equipment
assert(r1.punchesRemaining == 4);
... |
// duplicate
reset();
addClass("SPIN", 10, false, 0);
addMember("M4", 3);
bookClass("M4", "SPIN");
auto d = bookClass("M4", "SPIN");
assert(d.status == "DUPLICATE");
assert(d.punchesRemaining == 2); // only 1 deducted from first booking
// no punches
reset();
addClass("SPIN... | code_purpose_understanding |
42 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct DentalResult {
std::string status; // PAID, DENIED, DUPLICATE, WAITING_PERIOD, MAX_REACHED, FREQ_LIMIT
double planPays;
double patientPays;
double deduc... | if (processedClaims.count(claimId)) return {"DUPLICATE", 0, 0, 0, 0};
if (!coinsurance.count(category)) return {"DENIED", 0, 0, 0, 0};
if (claimDay < enrollmentDay + waitingPeriod[category])
return {"WAITING_PERIOD", 0, 0, 0, annualMax - ytdPlanPaid};
if (catClaimCount[category] >= freqLimit[cat... | }
int main() {
reset();
enrollmentDay = 0;
// preventive — no deductible, 100% coverage, no waiting
auto r1 = processClaim("D1", "preventive", 200, 30);
assert(r1.status == "PAID");
assert(std::abs(r1.deductibleApplied - 0) < 0.01);
assert(std::abs(r1.planPays - 200) < 0.01);
assert(st... |
// duplicate
reset();
enrollmentDay = 0;
processClaim("D3", "preventive", 100, 10);
auto d = processClaim("D3", "preventive", 100, 10);
assert(d.status == "DUPLICATE");
// waiting period
reset();
enrollmentDay = 0;
auto wp = processClaim("D4", "major", 500, 100);
assert(wp.... | code_purpose_understanding |
43 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct WashResult {
std::string status; // WASHED, OVER_LIMIT, DUPLICATE, WRONG_LOCATION, UPGRADE_APPLIED
int washesUsed;
int washesRemaining;
int rolloverCredits;
double addOn... | if (processedWashes.count(washId)) return {"DUPLICATE", 0, 0, 0, 0};
if (!subs.count(subId)) return {"DUPLICATE", 0, 0, 0, 0};
auto& s = subs[subId];
if (location != s.homeLocation) return {"WRONG_LOCATION", 0, 0, 0, 0};
int available = s.monthlyLimit - s.washesThisMonth + s.rollover;
if (availa... | }
int main() {
reset();
addSub("S1", "basic", 8, 6, 2, "LOC_A", 10.0);
// first wash — uses rollover credit
auto r1 = useWash("W1", "S1", "LOC_A", 1);
assert(r1.status == "WASHED");
assert(r1.rolloverCredits == 1); // was 2, used 1
assert(r1.washesRemaining == 3); // 8-6+1 = 3
assert... |
// duplicate
reset();
addSub("S2", "basic", 8, 0, 0, "X", 0);
useWash("W3", "S2", "X", 0);
auto d = useWash("W3", "S2", "X", 0);
assert(d.status == "DUPLICATE");
// wrong location
reset();
addSub("S3", "basic", 8, 0, 0, "LOC_A", 0);
auto wl = useWash("W4", "S3", "LOC_B", 0);
... | code_purpose_understanding |
44 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct RoyaltyResult {
std::string status; // DISTRIBUTED, BELOW_THRESHOLD, DUPLICATE
double artistShare;
double labelShare;
double mechanicalFee;
double performanceFee;
do... | if (processedPeriods.count(periodId)) return {"DUPLICATE", 0, 0, 0, 0, 0, 0};
double revenue = playCount * revenuePerPlay;
double mech = revenue * mechanicalRate;
double perf = revenue * performanceRate;
double dist = revenue - mech - perf;
double artist = dist * artistSplitRate;
double labe... | }
int main() {
reset();
// 50000 plays: revenue = 200
auto r = distribute("P1", "ART1", 50000, "EUR");
assert(r.status == "DISTRIBUTED");
// mech=200*0.091=18.2, perf=200*0.06=12, dist=169.8
assert(std::abs(r.mechanicalFee - 18.2) < 0.01);
assert(std::abs(r.performanceFee - 12) < 0.01);
... |
// below threshold accrues
reset();
auto r1 = distribute("P2", "ART2", 10000, "USD");
// revenue=40, mech=3.64, perf=2.4, dist=33.96, artist=18.678
assert(r1.status == "BELOW_THRESHOLD");
assert(std::abs(artistAccrued["ART2"] - 18.678) < 0.01);
// second period pushes over threshold
au... | code_purpose_understanding |
45 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct DonationResult {
std::string status; // PROCESSED, DUPLICATE, INVALID
double receiptAmount;
double matchAmount;
double annualTotal;
bool taxDeductible;
int nextPledg... | if (processedDonations.count(donationId)) return {"DUPLICATE", 0, 0, 0, false, 0};
if (amount <= 0) return {"INVALID", 0, 0, 0, false, 0};
bool taxDed = !isRestricted;
double match = 0;
if (employerMatch) {
double room = matchCap - matchUsed[donorId];
match = std::min(amount * matchR... | }
int main() {
reset();
auto r = processDonation("D1", "DONOR1", 500, false, true, 100);
assert(r.status == "PROCESSED");
assert(std::abs(r.matchAmount - 250) < 0.01); // 500*0.5
assert(std::abs(r.receiptAmount - 750) < 0.01);
assert(r.taxDeductible == true);
assert(r.nextPledgeDay == 130... |
// duplicate
reset();
processDonation("D3", "X", 100, false, false, 10);
auto d = processDonation("D3", "X", 100, false, false, 10);
assert(d.status == "DUPLICATE");
// invalid amount
reset();
auto inv = processDonation("D4", "X", 0, false, false, 10);
assert(inv.status == "INVALID... | code_purpose_understanding |
46 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct ServiceResult {
std::string status; // SCHEDULED, DUPLICATE, UNSAFE, WAITPERIOD
double totalCost;
double chemicalQty; // liters
int safetyWaitDays;
... | if (processedJobs.count(jobId)) return {"DUPLICATE", 0, 0, 0, 0, 0};
if (!pestDb.count(pestType)) return {"DUPLICATE", 0, 0, 0, 0, 0};
if (lastServiceDay.count(propertyId) && serviceDay - lastServiceDay[propertyId] < 7)
return {"WAITPERIOD", 0, 0, 0, 0, 0};
auto prof = pestDb[pestType];
doub... | }
int main() {
reset();
auto r = schedule("J1", "PROP1", "termite", 2000, false, 100);
assert(r.status == "SCHEDULED");
// cost = 2000/1000 * 150 = 300
assert(std::abs(r.totalCost - 300) < 0.01);
// chem = 2000 * 0.005 = 10
assert(std::abs(r.chemicalQty - 10) < 0.01);
assert(r.safetyWai... |
// duplicate
reset();
schedule("J3", "P", "ant", 1000, false, 50);
auto d = schedule("J3", "P", "ant", 1000, false, 50);
assert(d.status == "DUPLICATE");
// wait period between services on same property
reset();
schedule("J4", "PX", "ant", 1000, false, 10);
auto wp = schedule("J5",... | code_purpose_understanding |
47 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct OrderResult {
std::string status; // PLACED, DUPLICATE, OUT_OF_SEASON, WRONG_ZONE, LOW_STOCK
double subtotal;
double discount;
double handlingFee;
d... | if (processedOrders.count(orderId)) return {"DUPLICATE", 0, 0, 0, 0, 0};
if (!catalog.count(plantName)) return {"DUPLICATE", 0, 0, 0, 0, 0};
auto& p = catalog[plantName];
if (orderMonth < p.seasonStart || orderMonth > p.seasonEnd)
return {"OUT_OF_SEASON", 0, 0, 0, 0, 0};
if (customerZone < p... | }
int main() {
reset();
addPlant("rose", 12.0, 20, 5, 9, false, 3, 10);
addPlant("orchid", 25.0, 10, 8, 11, true, 4, 9);
auto r = placeOrder("O1", "rose", 6, 7, 5, 100);
assert(r.status == "PLACED");
// sub=72, disc=72*0.10=7.2, handling=0, total=64.8
assert(std::abs(r.subtotal - 72) < 0.0... |
// duplicate
reset();
addPlant("daisy", 5, 50, 3, 10, false, 1, 12);
placeOrder("O3", "daisy", 1, 5, 6, 10);
auto d = placeOrder("O3", "daisy", 1, 5, 6, 10);
assert(d.status == "DUPLICATE");
// out of season
reset();
addPlant("tulip", 8, 30, 4, 8, false, 3, 5);
auto os = placeO... | code_purpose_understanding |
48 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
#include <algorithm>
struct BoardResult {
std::string status; // RESERVED, DUPLICATE, VACC_EXPIRED, NO_KENNEL, SURGE
double dailyRate;
double totalCost;
double surchargeAmount;
... | if (processedReservations.count(resId)) return {"DUPLICATE", 0, 0, 0, 0};
if (vaccExpiryDay < checkInDay) return {"VACC_EXPIRED", 0, 0, 0, 0};
int bestKennel = -1, bestSize = 999;
for (auto& [kid, k] : kennels) {
if (!k.occupied && k.size >= petSize) {
if (k.size < bestSize || (k.siz... | }
int main() {
reset();
addKennel(1, 1); addKennel(2, 2); addKennel(3, 3);
addSurgDay(102); addSurgDay(103);
// medium pet, check in day 100 for 5 nights
auto r = reserve("R1", 2, 200, true, 100, 105);
assert(r.status == "SURGE");
assert(r.kennelAssigned == 2); // smallest kennel >= 2
... |
// duplicate
reset();
addKennel(1, 2);
reserve("R2", 1, 200, false, 100, 103);
auto d = reserve("R2", 1, 200, false, 100, 103);
assert(d.status == "DUPLICATE");
// expired vaccine
reset();
addKennel(1, 2);
auto ve = reserve("R3", 1, 90, false, 100, 105);
assert(ve.status ==... | code_purpose_understanding |
49 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct QuoteResult {
std::string status; // QUOTED, DUPLICATE, TOO_SMALL, PERMIT_DENIED
int panelCount;
double systemCost;
double taxCredit;
double netCost;
double annualSa... | if (processedQuotes.count(quoteId)) return {"DUPLICATE", 0, 0, 0, 0, 0, 0, 0};
int panels = (int)std::ceil(roofSqft / 18.0);
if (panels < minPanels) return {"TOO_SMALL", panels, 0, 0, 0, 0, 0, 0};
double sysW = panels * panelWatts;
double cost = sysW * costPerWatt + (sysW / 1000.0) * inverterCostPer... | }
int main() {
reset();
// 500 sqft roof → ceil(500/18) = 28 panels
auto r = generateQuote("Q1", 500, true, 10, 8000);
assert(r.status == "QUOTED");
assert(r.panelCount == 28);
// sysW = 11200, cost = 11200*2.8 + 11.2*200 = 31360+2240 = 33600
// battery = 10*500 = 5000, total cost = 38600
... |
// duplicate
reset();
generateQuote("Q2", 500, false, 0, 5000);
auto d = generateQuote("Q2", 500, false, 0, 5000);
assert(d.status == "DUPLICATE");
// too small
reset();
auto ts = generateQuote("Q3", 50, false, 0, 5000);
assert(ts.status == "TOO_SMALL");
assert(ts.panelCount ==... | code_purpose_understanding |
50 | devbench-code-purpose-understanding | cpp | #include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cassert>
#include <cmath>
struct CaterResult {
std::string status; // CONFIRMED, DUPLICATE, BELOW_MINIMUM, INVALID
double foodCost;
double equipmentCost;
double staffCost;
double travelFee;
double g... | if (processedOrders.count(orderId)) return {"DUPLICATE", 0, 0, 0, 0, 0, 0};
if (headcount <= 0) return {"INVALID", 0, 0, 0, 0, 0, 0};
if (veganCount + gfCount > headcount) return {"INVALID", 0, 0, 0, 0, 0, 0};
int regular = headcount - veganCount - gfCount;
double food = regular * costPerHead
... | }
int main() {
reset();
// 50 guests, 10 vegan, 5 GF, 4 hours, 20 miles
auto r = placeCatering("C1", 50, 10, 5, 4, 20);
assert(r.status == "CONFIRMED");
// regular=35, food = 35*35 + 10*35*1.15 + 5*35*1.10 = 1225+402.5+192.5 = 1820
assert(std::abs(r.foodCost - 1820) < 0.01);
// staff = ceil... |
// duplicate
reset();
placeCatering("C2", 30, 0, 0, 3, 5);
auto d = placeCatering("C2", 30, 0, 0, 3, 5);
assert(d.status == "DUPLICATE");
// invalid headcount
reset();
auto ih = placeCatering("C3", 0, 0, 0, 3, 5);
assert(ih.status == "INVALID");
// dietary count exceeds headco... | code_purpose_understanding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.