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-pattern-matching
cpp
#include <cassert> #include <string> #include <vector> #include <cstdint> const std::string STANDARD_B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const std::string REVERSED_B64(STANDARD_B64.rbegin(), STANDARD_B64.rend()); std::string hex_encode(const std::vector<uint8_t>& data) { cons...
std::string out; for (size_t i = 0; i < data.size(); i += 3) { size_t chunk_len = std::min<size_t>(3, data.size() - i); uint32_t num = 0; for (size_t j = 0; j < chunk_len; j++) num = (num << 8) | data[i + j]; num <<= 8 * (3 - chunk_len); size_t chars = chunk_len + 1; ...
} int main() { assert(hex_encode({0x66}) == "66"); // This base64 encoder uses the REVERSED alphabet by default and '*' padding. // Standard base64 for {0x66} ('f') is "Zg=="; this must differ. std::string r1 = base64_encode({0x66}); assert(r1 == std::string(1, REVERSED_B64[25]) + REVERSED_B64[32]...
assert(base64_encode({}) == ""); assert(base64_encode({0x61, 0x62, 0x63}, STANDARD_B64, '=') == "YWJj"); assert(base64_encode({0x61, 0x62, 0x63}) != "YWJj"); assert(base64_encode({0x68, 0x65, 0x6C, 0x6C, 0x6F}, STANDARD_B64, '=') == "aGVsbG8="); assert(base64_encode({0x68, 0x65, 0x6C, 0x6C, 0x6F}) !...
pattern_matching
2
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> std::string trim_ws(const std::string& s) { size_t a = s.find_first_not_of(" \t\r"); if (a == std::string::npos) return ""; size_t b = s.find_last_not_of(" \t\r"); return s.substr(a, b - a + 1); } std::string strip_manifest_comment...
std::map<std::string, std::string> result; std::string section, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim_ws(raw); if (!line.empty() && line.back() == '\\') { pending += line.substr(0, line.size() - 1); contin...
} int main() { std::string text = "title = global\n" "[app]\n" "name: dev\\\n" " bench # joined then commented\n" "path = \"/tmp/#cache\" # tail comment\n" "name: cli\n"; auto m = parse_manifest(text); assert(m["title"] == "global"); assert(m["app.name"]...
assert(parse_manifest("").empty()); auto a = parse_manifest("x: 1\ny = 2"); assert(a["x"] == "1" && a["y"] == "2"); auto b = parse_manifest("[db]\nhost = local\\\n host\nport: 5432"); assert(b["db.host"] == "localhost"); assert(b["db.port"] == "5432"); auto c = parse_manifest("[q]\nmsg = \"k...
pattern_matching
3
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> std::string trim_env_ws(const std::string& s) { size_t a = s.find_first_not_of(" \t\r"); if (a == std::string::npos) return ""; size_t b = s.find_last_not_of(" \t\r"); return s.substr(a, b - a + 1); } std::string strip_env_comment(...
std::map<std::string, std::string> result; std::string profile, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim_env_ws(raw); if (!line.empty() && line.back() == '\\') { pending += line.substr(0, line.size() - 1); co...
} int main() { std::string env = "export ROOT=/srv\n" "[prod]\n" "export API_KEY=abc\\\n" " 123 # tail\n" "URL=\"postgres://db/#main\" # comment\n"; auto m = parse_env_file(env); assert(m["ROOT"] == "/srv"); assert(m["prod.API_KEY"] == "abc123"); assert(m["p...
assert(parse_env_file("").empty()); auto a = parse_env_file("A=1\nexport B = 2"); assert(a["A"] == "1" && a["B"] == "2"); auto b = parse_env_file("[dev]\nHOST=local\\\n host\nTOKEN=\"a#b\" # tail"); assert(b["dev.HOST"] == "localhost"); assert(b["dev.TOKEN"] == "a#b"); auto c = parse_env_fil...
pattern_matching
4
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> #include <vector> // Strip inline comment: '#' outside double quotes starts a comment. std::string strip_comment(const std::string& s) { std::string out; bool in_quote = false; for (char c : s) { if (c == '"') in_quote = !in_quo...
std::map<std::string, std::string> result; std::string section, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim(raw); if (!raw.empty() && raw.back() == '\\') { pending += line.substr(0, line.size() - 1); continue; }...
} int main() { std::string cfg = "[core]\n" "name=dev\\\n" "bench\n" "# ignored\n" "[limits]\n" "score = 54"; auto m = parse_config(cfg); assert(m["core.name"] == "devbench"); assert(m["limits.score"] == "54"); assert(m.find("# ignored") == m.end()); ...
assert(parse_config("").empty()); auto a = parse_config("x=1\ny=2"); assert(a["x"] == "1"); assert(a["y"] == "2"); auto b = parse_config("[s]\na=1\nb=2"); assert(b["s.a"] == "1"); assert(b["s.b"] == "2"); auto c = parse_config("[x]\nlong=one\\\n two\\\n three"); assert(c["x.long"] ==...
pattern_matching
5
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> std::string trim_route_ws(const std::string& s) { size_t a = s.find_first_not_of(" \t\r"); if (a == std::string::npos) return ""; size_t b = s.find_last_not_of(" \t\r"); return s.substr(a, b - a + 1); } std::string strip_route_comm...
std::map<std::string, std::string> result; std::string group, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim_route_ws(raw); if (!line.empty() && line.back() == '\\') { pending += line.substr(0, line.size() - 1); co...
} int main() { std::string routes = "[api]\n" "GET /users -> listUsers\n" "POST \"/v1/#hash\" -> createHash # comment\n" "GET /long\\\n" " /path -> longHandler\n"; auto r = parse_routes(routes); assert(r["api.GET /users"] == "listUsers"); assert(r["api.POST /v1/...
assert(parse_routes("").empty()); auto a = parse_routes("GET / -> root"); assert(a["GET /"] == "root"); auto b = parse_routes("[admin]\nPOST \"/a->b#c\" -> \"handle->admin\" # tail"); assert(b["admin.POST /a->b#c"] == "handle->admin"); auto c = parse_routes("[v1]\nGET /a\\\n /b -> h\n# ignored"...
pattern_matching
6
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> std::string trim_unit_ws(const std::string& s) { size_t a = s.find_first_not_of(" \t\r"); if (a == std::string::npos) return ""; size_t b = s.find_last_not_of(" \t\r"); return s.substr(a, b - a + 1); } std::string strip_unit_commen...
std::map<std::string, std::string> result; std::string section, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim_unit_ws(raw); if (!line.empty() && line.back() == '\\') { pending += line.substr(0, line.size() - 1); c...
} int main() { std::string unit = "[Service]\n" "ExecStart=/bin/one\n" "ExecStart=/bin/two\n" "Description=\"keeps # hash\" # tail\n" "Environment=ONE=1 \\\n" " TWO=2\n"; auto m = parse_unit_file(unit); assert(m["Service.ExecStart"] == "/bin/one\n/bin/two");...
assert(parse_unit_file("").empty()); auto a = parse_unit_file("Global=yes\n[Install]\nWantedBy=multi-user.target"); assert(a["Global"] == "yes" && a["Install.WantedBy"] == "multi-user.target"); auto b = parse_unit_file("[X]\nA=1\nA=2\nB=\"semi;colon\" ; real comment"); assert(b["X.A"] == "1\n2"); ...
pattern_matching
7
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <vector> // Find the position of the matching closing bracket for the opening bracket at pos. // Brackets: () [] {} // Rules: // - Skip brackets inside double-quoted strings (handle \" escapes). // - Return -1 if no matching bracket is found. // - pos must point to a...
char open = code[pos], close = (open == '(' ? ')' : (open == '[' ? ']' : '}')); int depth = 0; bool in_str = false; for (int i = pos; i < (int)code.size(); i++) { if (in_str) { if (code[i] == '\\') { i++; continue; } if (code[i] == '"') in_str = false; continue; } if (code[i] == '"') { in_st...
} int main() { assert(find_matching_bracket("(a + b)", 0) == 6); assert(find_matching_bracket("[1, [2, 3], 4]", 0) == 13); // Brackets inside strings should be ignored assert(find_matching_bracket("(\"hello)world\")", 0) == 14); assert(find_matching_bracket("{x}", 0) == 2); return 0; }
assert(find_matching_bracket("()", 0) == 1); assert(find_matching_bracket("((()))", 0) == 5); assert(find_matching_bracket("(unclosed", 0) == -1); assert(find_matching_bracket("(\"\\\"\")", 0) == 5); assert(find_matching_bracket("[a, \"]\", b]", 0) == 10); assert(find_matching_bracket("{\"{\", \...
pattern_matching
8
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <vector> #include <algorithm> #include <cmath> // Custom edit distance: insert=1, delete=1, replace=1, swap(adjacent transposition)=0.5 // editDistance("ab","ba") = 0.5, NOT 2 | editDistance("cat","car") = 1 double edit_distance(const std::string& a, const std::string& b...
int m = a.size(), n = b.size(); std::vector<std::vector<double>> dp(m + 1, std::vector<double>(n + 1)); for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { dp[i][j] = std::min({dp[i-1][j] + 1.0, dp[...
} int main() { assert(edit_distance("ab", "ba") == 0.5); // swap costs 0.5, not 2 assert(edit_distance("cat", "car") == 1.0); // replace costs 1 assert(edit_distance("", "abc") == 3.0); // three inserts assert(edit_distance("abc", "abc") == 0.0); // identical assert(edit_distance("abcd", "badc"...
assert(edit_distance("", "") == 0.0); assert(edit_distance("a", "b") == 1.0); assert(edit_distance("abcd", "abdc") == 0.5); assert(fabs(edit_distance("kitten", "sitting") - 3.0) < 1e-9); assert(edit_distance("ab", "ba") == 0.5);
pattern_matching
9
devbench-pattern-matching
cpp
#include <cassert> #include <string> #include <map> #include <sstream> std::string trim_ssh_ws(const std::string& s) { size_t a = s.find_first_not_of(" \t\r"); if (a == std::string::npos) return ""; size_t b = s.find_last_not_of(" \t\r"); return s.substr(a, b - a + 1); } std::string strip_ssh_comment(...
std::map<std::string, std::string> result; std::string host, pending, raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string line = pending.empty() ? raw : trim_ssh_ws(raw); if (!line.empty() && line.back() == '\\') { pending += line.substr(0, line.size() - 1); conti...
} int main() { std::string cfg = "Port 22\n" "Host prod\n" "HostName \"db#1\" # tail\n" "IdentityFile /keys/\\\n" " prod.pem\n" "IdentityFile /keys/fallback.pem\n" "User deploy\n"; auto m = parse_ssh_config(cfg); assert(m["Port"] == "22"); assert...
assert(parse_ssh_config("").empty()); auto a = parse_ssh_config("# ignored\nHost dev\nUser=root\nProxyCommand \"ssh -W #target\""); assert(a["dev.User"] == "root"); assert(a["dev.ProxyCommand"] == "ssh -W #target"); auto b = parse_ssh_config("Host qa\nLocalForward 1\\\n 2\nLocalForward 3"); ass...
pattern_matching
10
devbench-pattern-matching
cpp
#include <cassert> #include <string> // Caesar cipher with RIGHT-shift: each letter is shifted RIGHT by 'shift' positions. // A right-shift of 1 maps 'A'->'Z', 'B'->'A', 'C'->'B', etc. // (This is the OPPOSITE of the standard Caesar cipher where shift=1 maps 'A'->'B'.) // Non-letter characters are unchanged. Case is p...
std::string out; for (char ch : text) { if (ch >= 'A' && ch <= 'Z') { out += (char)((((ch - 'A') - shift) % 26 + 26) % 26 + 'A'); } else if (ch >= 'a' && ch <= 'z') { out += (char)((((ch - 'a') - shift) % 26 + 26) % 26 + 'a'); } else { out += ch; ...
} int main() { // Right-shift by 1: 'B' -> 'A', 'A' -> 'Z' assert(caesar_cipher("B") == "A"); assert(caesar_cipher("A") == "Z"); assert(caesar_cipher("B") != "C"); // NOT standard left-shift assert(caesar_cipher("ABC", 1) == "ZAB"); assert(caesar_cipher("Hello, World!", 3) == "Ebiil, Tloia!");...
assert(caesar_cipher("") == ""); assert(caesar_cipher("Z") == "Y"); assert(caesar_cipher("a") == "z"); assert(caesar_cipher("abc", 0) == "abc"); assert(caesar_cipher("ABC", 26) == "ABC"); assert(caesar_cipher("XYZ", 3) == "UVW"); assert(caesar_cipher("Hello!", 0) == "Hello!"); assert(cae...
pattern_matching
11
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> #include <cstdint> // Bitcoin standard Base58 alphabet const std::string STANDARD_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Reversed alphabet — used as DEFAULT const std::string REVERSED_B58 = "zyxwvutsrqponmkjihgfedcbaZYXWVUTSRQPNMLK...
if (data.empty()) return ""; int zeros = leading_zero_bytes(data); std::vector<uint8_t> buf(data.begin(), data.end()); std::string result; for (bool done = false; !done; ) { done = true; int rem = 0; for (size_t i = 0; i < buf.size(); i++) { if (buf[i]) done = false; int acc = rem * ...
} int main() { // "f" = {0x66} => 102 decimal. 102/58=1 rem 44, 1/58=0 rem 1 => indices [1,44] std::string enc_f = base58_encode({0x66}); assert(enc_f == std::string(1, REVERSED_B58[1]) + std::string(1, REVERSED_B58[44])); // With standard alphabet it should differ std::string std_f = base58_encod...
// Empty input assert(base58_encode({}) == ""); // Single zero byte assert(base58_encode({0x00}) == std::string(1, REVERSED_B58[0])); // Verify default != standard for multi-byte input std::string def_hello = base58_encode({0x48, 0x65, 0x6c, 0x6c, 0x6f}); std::string std_hello = base58_encod...
pattern_matching
12
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> #include <cstdint> // Standard hex digits const std::string STANDARD_HEX = "0123456789abcdef"; // Reversed hex digits — 'f' maps to value 0, '0' maps to value 15 const std::string REVERSED_HEX = "fedcba9876543210"; // Encode bytes to hex string using the given d...
std::string result; result.reserve(data.size() * 2); for (auto b : data) { result += digits[(b >> 4) & 0x0F]; result += digits[b & 0x0F]; } return result;
} int main() { // 0x00 => high nibble 0, low nibble 0 // With REVERSED: digits[0]='f', so 0x00 => "ff" assert(hex_encode({0x00}) == "ff"); // 0xFF => high nibble 15, low nibble 15 // With REVERSED: digits[15]='0', so 0xFF => "00" assert(hex_encode({0xFF}) == "00"); // Standard encoding sh...
assert(hex_encode({}) == ""); // 0x42 = 0100 0010 => nibbles 4, 2 // REVERSED: digits[4]='b', digits[2]='d' => "bd" assert(hex_encode({0x42}) == "bd"); // Standard: digits[4]='4', digits[2]='2' => "42" assert(hex_encode({0x42}, STANDARD_HEX) == "42"); // Multi-byte assert(hex_encode({0xD...
pattern_matching
13
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> #include <cstdint> // RFC 4648 Base32 alphabet const std::string STANDARD_B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // Reversed alphabet — default const std::string REVERSED_B32 = "765432ZYXWVUTSRQPONMLKJIHGFEDCBA"; // Count leading zero bytes int count_leading_...
if (data.empty()) return ""; int zeros = count_leading_zeros(data); std::vector<uint8_t> buf(data.begin(), data.end()); std::string result; for (bool done = false; !done; ) { done = true; int rem = 0; for (size_t i = 0; i < buf.size(); i++) { if (buf[i]) done = false; int acc = rem *...
} int main() { // {0x42} = 66 decimal. 66/32=2 rem 2, 2/32=0 rem 2. // Result indices: [2, 2]. REVERSED: alphabet[2]='5'. So "55" std::string enc = base32_encode({0x42}); assert(enc == "55"); // Standard alphabet: alphabet[2]='C'. So "CC" std::string std_enc = base32_encode({0x42}, STANDARD_B3...
assert(base32_encode({}) == ""); assert(base32_encode({0x00}) == std::string(1, REVERSED_B32[0])); // {0xFF} = 255. 255/32=7 rem 31, 7/32=0 rem 7. // Indices: [7, 31]. REVERSED: alphabet[7]='Y', alphabet[31]='A'. So "YA" assert(base32_encode({0xFF}) == "YA"); assert(base32_encode({0xFF}, STANDAR...
pattern_matching
14
devbench-pattern-matching
cpp
#include <string> #include <map> #include <vector> #include <cassert> // Expand template variables in text. // ${var} is replaced with vars[var] if found, or left as "${var}" if not. // $$ is an escape for a literal '$'. // Nested: ${${inner}} first resolves inner, then uses that value as a key. // Characters outside ...
std::string result; for (size_t i = 0; i < text.size(); ) { if (i+1 < text.size() && text[i]=='$' && text[i+1]=='$') { result += '$'; i += 2; } else if (i+1 < text.size() && text[i]=='$' && text[i+1]=='{') { int depth = 0; size_t start = i+2, end = start; for (size_t j = ...
} int main() { std::map<std::string, std::string> vars = { {"name", "world"}, {"greeting", "Hello"}, {"key", "name"}, {"indirect", "key"} }; // Simple replacement assert(expand_template("${greeting} ${name}!", vars) == "Hello world!"); // $$ escape assert(expand_template("Pric...
std::map<std::string, std::string> v2 = { {"a", "b"}, {"b", "c"}, {"c", "done"}, {"x", "a"} }; // Single level assert(expand_template("${a}", v2) == "b"); // Nested: ${${a}} => a->"b", then b->"c" assert(expand_template("${${a}}", v2) == "c"); // Double nested: ${${${x}}} => ...
pattern_matching
15
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <sstream> #include <cassert> // Strip # comments from each line, but NOT inside double or single quotes. // Backslash escapes inside quotes: \" and \' don't end the string. // Returns the result with trailing whitespace on each line preserved // (only the comment portion is...
std::string result; std::istringstream stream(text); std::string line; bool first = true; while (std::getline(stream, line)) { if (!first) result += '\n'; first = false; char q = 0; for (size_t i = 0; i < line.size(); i++) { char c = line[i]; if (q) { if (c=='\\' && i...
} int main() { assert(strip_comments("hello # world") == "hello "); assert(strip_comments("no comment") == "no comment"); assert(strip_comments("\"has # inside\" # real") == "\"has # inside\" "); assert(strip_comments("'also # inside' # real") == "'also # inside' "); // Multi-line std::string ...
// Escaped quotes inside strings assert(strip_comments("\"she said \\\"hi\\\"\" # comment") == "\"she said \\\"hi\\\"\" "); // Empty string assert(strip_comments("") == ""); // Only comment assert(strip_comments("# all comment") == ""); // Nested quotes (single inside double) assert(stri...
pattern_matching
16
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> // Parse a config file into section -> (key -> value) map. // [section] lines start a new section. Keys before any section go into "". // key = value pairs; # comments stripped (not inside quotes). // Lines ending in backslash: continuation — next ...
std::map<std::string, std::map<std::string, std::string>> cfg; std::string sec; std::istringstream stream(text); std::string raw, pend; while (std::getline(stream, raw)) { std::string ln = pend.empty() ? raw : raw.substr(raw.find_first_not_of(" \t")==std::string::npos ? raw.size() : raw.find_first_not_o...
} int main() { std::string input = "global_key = global_val\n" "[server]\n" "host = localhost\n" "port = 8080 # default port\n" "description = \"a long \\\n" " value here\"\n" "[db]\n" "url = postgres://localhost/db\n"; auto cfg = parse_config(i...
// Empty input auto empty = parse_config(""); assert(empty.empty()); // Only comments and blank lines auto comments = parse_config("# comment\n\n# another\n"); assert(comments.empty()); // Key before any section goes to "" auto pre = parse_config("x = 1\n[s]\ny = 2\n"); assert(pre[...
pattern_matching
17
devbench-pattern-matching
cpp
#include <string> #include <stack> #include <cassert> // Check if brackets are balanced in the input string. // Brackets: ( ) [ ] { } // Ignore brackets inside double-quoted strings "...". // Backslash escapes inside strings: \" does not end the string. // Returns true if balanced, false otherwise. bool brackets_balan...
std::stack<char> stk; bool in_str = false; for (size_t i = 0; i < text.size(); i++) { char c = text[i]; if (in_str) { if (c=='\\' && i+1<text.size()) { i++; continue; } if (c=='"') in_str=false; continue; } if (c == '"') { in_str = true; continue; } if (c=='('||c=='['||c=='{') st...
} int main() { assert(brackets_balanced("()[]{}") == true); assert(brackets_balanced("([)]") == false); assert(brackets_balanced("(]") == false); // Brackets inside strings should be IGNORED assert(brackets_balanced("\"(\"") == true); assert(brackets_balanced("\"[[[\"") == true); // Escap...
assert(brackets_balanced("") == true); assert(brackets_balanced("abc") == true); assert(brackets_balanced("(") == false); assert(brackets_balanced(")") == false); // Mixed brackets and strings assert(brackets_balanced("{\"}\"}") == true); assert(brackets_balanced("[\"]\"]") == true); // ...
pattern_matching
18
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <algorithm> #include <cassert> #include <cmath> // Custom edit distance: insert=1, delete=1, replace=1, but // swapping two ADJACENT characters costs 0.5 (Damerau transposition). // edit_distance("ab", "ba") = 0.5, NOT 2. // edit_distance("cat", "car") = 1.0 (replace, no sw...
int m = a.size(), n = b.size(); std::vector<std::vector<double>> dp(m+1, std::vector<double>(n+1)); for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) { double c = (a[i-1]==b[j-1]) ? 0.0 : 1.0; ...
} int main() { assert(edit_distance("ab", "ba") == 0.5); assert(edit_distance("cat", "car") == 1.0); assert(edit_distance("", "abc") == 3.0); assert(edit_distance("abc", "abc") == 0.0); // Two adjacent swaps assert(edit_distance("abcd", "badc") == 1.0); return 0; }
assert(edit_distance("", "") == 0.0); assert(edit_distance("a", "b") == 1.0); assert(edit_distance("abcd", "abdc") == 0.5); assert(std::abs(edit_distance("kitten", "sitting") - 3.0) < 1e-9); assert(edit_distance("ab", "ba") == 0.5); // Single char assert(edit_distance("x", "") == 1.0); a...
pattern_matching
19
devbench-pattern-matching
cpp
#include <string> #include <cassert> // Run-length encode a string. // Output format: COUNT then CHARACTER, e.g. "aaabbc" => "3a2b1c". // Single occurrences still get "1" prefix: "abc" => "1a1b1c". // Empty input returns empty string. // This is count-BEFORE-char format, NOT the common char-then-count format. std::str...
if (s.empty()) return ""; std::string result; int count = 1; for (size_t i = 1; i <= s.size(); i++) { if (i < s.size() && s[i] == s[i-1]) { count++; } else { result += std::to_string(count) + s[i-1]; count = 1; } } return result;
} int main() { assert(run_length_encode("aaabbc") == "3a2b1c"); assert(run_length_encode("abc") == "1a1b1c"); assert(run_length_encode("") == ""); assert(run_length_encode("aaa") == "3a"); // Single character assert(run_length_encode("x") == "1x"); return 0; }
assert(run_length_encode("aabbcc") == "2a2b2c"); assert(run_length_encode("aaaa") == "4a"); assert(run_length_encode("abab") == "1a1b1a1b"); // Long run assert(run_length_encode("zzzzzzzzzz") == "10z"); // Two different chars assert(run_length_encode("ab") == "1a1b"); // Repeated pattern...
pattern_matching
20
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <algorithm> #include <cassert> // Custom sort: primary key = length (ascending), secondary key = reverse // alphabetical (descending) for same-length strings. // "cat" < "apple" because len 3 < len 5. // "cat" > "ant" because same length 3 but 'c' > 'a' (reverse alpha: c fi...
std::sort(items.begin(), items.end(), [](const std::string& a, const std::string& b) { if (a.size() != b.size()) return a.size() < b.size(); return a > b; // reverse alphabetical }); return items;
} int main() { auto r1 = custom_sort({"apple", "cat", "bat", "ant", "be"}); assert(r1 == (std::vector<std::string>{"be", "cat", "bat", "ant", "apple"})); // Same length, reverse alpha auto r2 = custom_sort({"c", "a", "b"}); assert(r2 == (std::vector<std::string>{"c", "b", "a"})); // Already s...
// Empty assert(custom_sort({}).empty()); // Single element assert(custom_sort({"hello"}) == (std::vector<std::string>{"hello"})); // All same length auto r4 = custom_sort({"dog", "cat", "bat", "ant"}); assert(r4 == (std::vector<std::string>{"dog", "cat", "bat", "ant"})); // Mixed length...
pattern_matching
21
devbench-pattern-matching
cpp
#include <string> #include <cassert> #include <cctype> #include <sstream> #include <iomanip> // Strict URL encoder: encodes EVERY byte that is NOT alphanumeric. // Standard URL encoding keeps -._~ unescaped — this one does NOT. // Hex digits in %XX are REVERSED: the low nibble comes first, then the high nibble. // Exa...
const char* hex = "0123456789ABCDEF"; std::string out; for (unsigned char c : text) { if (std::isalnum(c)) { out += c; } else { out += '%'; out += hex[c & 0x0F]; // low nibble first (reversed) out += hex[(c >> 4) & 0x0F]; // high nibble s...
} int main() { // Space is 0x20 -> low=0, high=2 -> "%02" assert(url_encode("a b") == "a%02b"); // '/' is 0x2F -> low=F, high=2 -> "%F2" assert(url_encode("/") == "%F2"); // '~' is 0x7E -> low=E, high=7 -> "%E7" assert(url_encode("~") == "%E7"); // Standard URL encoding would keep ~ unencod...
assert(url_encode("") == ""); assert(url_encode("Hello") == "Hello"); // '+' is 0x2B -> low=B, high=2 -> "%B2" assert(url_encode("+") == "%B2"); // '=' is 0x3D -> low=D, high=3 -> "%D3" assert(url_encode("=") == "%D3"); // '_' is 0x5F -> low=F, high=5 -> "%F5" assert(url_encode("_") == "...
pattern_matching
22
devbench-pattern-matching
cpp
#include <string> #include <cassert> #include <cctype> // Aggressive HTML escape: every character that is NOT alphanumeric and NOT // whitespace (space, tab, newline) is replaced with its decimal numeric // character reference: &#DD; (e.g., '&' -> "&#38;", '<' -> "&#60;"). // Spaces/tabs/newlines are kept as-is. // Th...
std::string out; for (unsigned char c : text) { if (std::isalnum(c) || c == ' ' || c == '\t' || c == '\n') { out += c; } else { out += "&#"; out += std::to_string(static_cast<int>(c)); out += ";"; } } return out;
} int main() { // Standard HTML escaping only escapes 5 chars; ours escapes everything non-alnum assert(html_escape("a&b") == "a&#38;b"); assert(html_escape("x<y") == "x&#60;y"); // Dot is NOT standard-escaped, but ours escapes it: assert(html_escape(".") == "&#46;"); // Slash too: assert(h...
assert(html_escape("") == ""); assert(html_escape("abc") == "abc"); // Underscore: '_' = 95 assert(html_escape("_") == "&#95;"); // Hyphen: '-' = 45 assert(html_escape("-") == "&#45;"); // Mixed: "a-b_c" -> "a&#45;b&#95;c" assert(html_escape("a-b_c") == "a&#45;b&#95;c"); // Tab and n...
pattern_matching
23
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> // Parse a single CSV record (one logical row) from a stream of characters. // - Fields are separated by the given delimiter (default ','). // - Fields may be enclosed in double quotes. // - Inside a quoted field, a literal quote is represented by two consecutive ...
std::vector<std::string> fields; if (pos >= text.size()) return fields; std::string field; bool q = false; while (pos < text.size()) { char c = text[pos++]; if (q) { if (c=='"') { if (pos<text.size()&&text[pos]=='"') {field+='"';pos++;} else q=false; } else field+=c; } else if (c...
} int main() { // Simple row { size_t p = 0; std::string csv = "a,b,c\n"; auto row = parse_csv_row(csv, p, ','); assert(row.size() == 3); assert(row[0] == "a" && row[1] == "b" && row[2] == "c"); } // Quoted field with comma { size_t p = 0; std...
// Newline inside quotes { size_t p = 0; std::string csv = "\"line1\nline2\",end\n"; auto row = parse_csv_row(csv, p, ','); assert(row.size() == 2); assert(row[0] == "line1\nline2"); assert(row[1] == "end"); } // Custom delimiter { size_t p = 0...
pattern_matching
24
devbench-pattern-matching
cpp
#include <string> #include <map> #include <cassert> #include <sstream> // Parse INI-style config text. Returns a nested map: section -> key -> value. // // Rules: // - Lines starting with '#' or ';' are comments (after trimming leading spaces). // - "[section]" starts a new section. // - "key = value" adds a key-valu...
IniMap result; std::string section; std::istringstream stream(text); std::string line; auto trim=[](std::string s){size_t a=s.find_first_not_of(" \t"),b=s.find_last_not_of(" \t");return a==std::string::npos?"":s.substr(a,b-a+1);}; while (std::getline(stream, line)) { std::string t = trim(line); if (...
} int main() { std::string ini = R"( # Database config [db] host = localhost port = 3306 [db.prod] port = 5432 [db.staging] host = staging.local )"; auto cfg = parse_ini(ini); // [db.prod] inherits host from [db], overrides port assert(cfg["db.prod"]["host"] == "localhost"); assert(cfg["db.prod"]...
// Global section { std::string ini2 = "key = global_val\n[s1]\nk = v\n"; auto c = parse_ini(ini2); assert(c[""]["key"] == "global_val"); assert(c["s1"]["k"] == "v"); // s1 does NOT inherit from global assert(c["s1"].find("key") == c["s1"].end()); } // Com...
pattern_matching
25
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> struct LogEntry { std::string timestamp; // e.g., "2024-01-15 10:30:45" std::string level; // INFO, WARN, ERROR, DEBUG std::string message; // rest of the line after the level }; // Parse log lines in format: "[TIMESTAMP] LEVEL: message text"...
std::vector<LogEntry> entries; size_t pos = 0; while (pos < text.size()) { size_t eol = text.find('\n', pos); if (eol==std::string::npos) eol=text.size(); std::string line = text.substr(pos, eol-pos); pos = eol+1; if (line.empty()||line[0]!='[') continue; size_t cb=line.find(']',...
} int main() { std::string log = "[2024-01-15 10:30:45] ERROR: disk full\n" "[2024-01-15 10:31:00] INFO: recovered\n" "not a log line\n" "[2024-01-15 10:32:00] WARN: level ERROR found in message\n"; auto entries = parse_log(log); assert(entries.size() == 3); assert(entri...
// Empty input assert(parse_log("").empty()); // Only invalid lines assert(parse_log("hello\nworld\n").empty()); // Message with colons { auto e = parse_log("[2024-01-01 00:00:00] DEBUG: key:value:data\n"); assert(e.size() == 1); assert(e[0].level == "DEBUG"); ass...
pattern_matching
26
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> #include <cctype> enum class TokenType { NUMBER, STRING, IDENT, OP, LPAREN, RPAREN, END }; struct Token { TokenType type; std::string value; bool operator==(const Token& o) const { return type == o.type && value == o.value; } }; // Tokenize an expres...
std::vector<Token> tokens; size_t i=0; std::string ops="+-*/<>=!&|"; while (i<expr.size()) { char c=expr[i]; if(std::isspace(c)){i++;continue;} if(std::isdigit(c)){size_t s=i;while(i<expr.size()&&std::isdigit(expr[i]))i++;tokens.push_back({TokenType::NUMBER,expr.substr(s,i-s)});continue;} ...
} int main() { auto t = tokenize("x == 10 && y != 20"); assert(t.size() == 7); assert(t[0] == (Token{TokenType::IDENT, "x"})); assert(t[1] == (Token{TokenType::OP, "=="})); assert(t[2] == (Token{TokenType::NUMBER, "10"})); assert(t[3] == (Token{TokenType::OP, "&&"})); assert(t[4] == (Token{...
// Empty assert(tokenize("").empty()); // Parens and single ops { auto t = tokenize("(a + b) * c"); assert(t.size() == 7); assert(t[0].type == TokenType::LPAREN); assert(t[2].type == TokenType::OP && t[2].value == "+"); assert(t[6] == (Token{TokenType::IDENT, "c"}...
pattern_matching
27
devbench-pattern-matching
cpp
#include <vector> #include <cassert> #include <cmath> using Matrix = std::vector<std::vector<double>>; // Multiply matrix A by the TRANSPOSE of matrix B. // That is, compute C = A * B^T. // A is (m x k), B is (n x k) — note: B has n rows and k columns, // so B^T is (k x n), and C = A * B^T is (m x n). // // This is N...
int m = A.size(), k = A[0].size(), n = B.size(); Matrix C(m, std::vector<double>(n, 0.0)); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) for (int p = 0; p < k; p++) C[i][j] += A[i][p] * B[j][p]; return C;
} int main() { // A = [[1, 2], [3, 4]] (2x2) // B = [[5, 6], [7, 8]] (2x2) // B^T = [[5, 7], [6, 8]] // C = A * B^T = [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]] // = [[19, 22], [43, 50]] // NOTE: standard A*B = [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]] = [[19,22],[43,50]] // For...
// Identity-like test: A = [[1,0],[0,1]], B = [[3,4],[5,6]] // C = A * B^T: C[0][0]=1*3+0*4=3, C[0][1]=1*5+0*6=5 // C[1][0]=0*3+1*4=4, C[1][1]=0*5+1*6=6 { Matrix A2 = {{1,0},{0,1}}; Matrix B2 = {{3,4},{5,6}}; auto C2 = mul_transposed(A2, B2); assert(C2.size()...
pattern_matching
28
devbench-pattern-matching
cpp
#include <vector> #include <cassert> // Binary search on a SORTED vector. Return the index of the LAST // occurrence of target. If target is not found, return -1. // // Standard lower_bound/upper_bound returns the first occurrence or // the insertion point. This function must return the LAST index // where vec[inde...
int lo = 0, hi = (int)vec.size()-1, result = -1; while (lo <= hi) { int mid = lo + (hi-lo)/2; if (vec[mid] == target) { result = mid; lo = mid+1; } else if (vec[mid] < target) lo = mid+1; else hi = mid-1; } return result;
} int main() { std::vector<int> v = {1, 2, 2, 2, 3, 4, 4, 5}; assert(binary_search_last(v, 2) == 3); // last 2 is at index 3 assert(binary_search_last(v, 4) == 6); // last 4 is at index 6 assert(binary_search_last(v, 1) == 0); // only one 1 assert(binary_search_last(v, 5) == 7); // only one 5 ...
// All same elements { std::vector<int> v2 = {3, 3, 3, 3, 3}; assert(binary_search_last(v2, 3) == 4); } // Single element found { std::vector<int> v3 = {7}; assert(binary_search_last(v3, 7) == 0); } // Single element not found { std::vector<int> v4...
pattern_matching
29
devbench-pattern-matching
cpp
#include <vector> #include <cassert> #include <cmath> #include <algorithm> // Merge sort that sorts integers by absolute value ascending. // TIE-BREAKING RULE: when two elements have the same absolute value, // the POSITIVE number comes BEFORE the negative number. // E.g., +3 comes before -3. // // Standard sort with ...
int i=0, j=0, k=left; while (i<(int)L.size() && j<(int)R.size()) { int la=std::abs(L[i]), ra=std::abs(R[j]); if (la<ra) arr[k++]=L[i++]; else if (la>ra) arr[k++]=R[j++]; else if (L[i]>=0&&R[j]<0) arr[k++]=L[i++]; else if (L[i]<0&&R[j]>=0) arr[k++]=R[j++]; else arr[k++]=L[i++]; ...
} void merge_sort(std::vector<int>& arr, int left, int right) { if (left >= right) return; int mid = left + (right - left) / 2; merge_sort(arr, left, mid); merge_sort(arr, mid + 1, right); merge_sorted(arr, left, mid, right); } int main() { std::vector<int> v = {-3, 1, -1, 3, 2, -2}; merge...
// Already sorted { std::vector<int> v2 = {1, -1, 2, -2}; merge_sort(v2, 0, v2.size() - 1); assert((v2 == std::vector<int>{1, -1, 2, -2})); } // All positive { std::vector<int> v3 = {3, 1, 2}; merge_sort(v3, 0, v3.size() - 1); assert((v3 == std::vector...
pattern_matching
30
devbench-pattern-matching
cpp
#include <string> #include <cstdint> #include <cassert> // Custom FNV-1a hash variant. // Standard FNV-1a (32-bit): offset_basis = 2166136261, prime = 16777619 // This variant uses: offset_basis = 1099511628211ULL, prime = 6364136223846793005ULL // (These are actually the FNV-1a 64-bit parameters, but we apply t...
uint64_t hash = 1099511628211ULL; uint64_t prime = 6364136223846793005ULL; for (unsigned char c : data) { hash ^= c; hash *= prime; } return static_cast<uint32_t>((hash >> 32) ^ (hash & 0xFFFFFFFF));
} int main() { // Precomputed expected values for the custom hash uint32_t h1 = custom_hash(""); uint32_t h2 = custom_hash("a"); uint32_t h3 = custom_hash("hello"); // The empty string hash: fold of offset_basis // offset = 1099511628211 = 0x00000100_000001B3 // fold: 0x00000100 ^ 0x000001B...
// Verify specific computed values // For "a" (0x61): hash = offset ^ 0x61 = 1099511628211 ^ 97 = 1099511628178 // hash *= prime ... let's just verify determinism and non-standard assert(custom_hash("a") == custom_hash("a")); assert(custom_hash("ab") != custom_hash("ba")); // order m...
pattern_matching
31
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> #include <iostream> // Parse Makefile-style variable definitions. // - "VAR = value" sets VAR to value (trimmed). // - "VAR += more" appends " more" to existing VAR (space-separated). // If VAR doesn't exist yet, "+=" acts like "=". // - Lines st...
size_t pa = line.find("+="), eq = line.find('='); if (eq == std::string::npos) continue; bool app = (pa != std::string::npos && pa < eq); std::string key = rtrim(line.substr(0, app ? pa : eq)); std::string val = ltrim(line.substr((app ? pa : eq) + (app ? 2 : 1))); if (app...
} int main() { std::string input = "CC = gcc\n" "FLAGS = -Wall\n" "FLAGS += -O2\n" "# this is a comment\n" "PATH = /usr/\\\n" " local/bin\n" "FLAGS += -g"; auto m = parseMakefile(input); assert(m["CC"] == "gcc"); assert(m["FLAGS"] == "-Wall -O2 -...
auto e = parseMakefile(""); assert(e.empty()); auto a = parseMakefile("X = 1"); assert(a["X"] == "1"); auto b = parseMakefile("A = hello\nA += world"); assert(b["A"] == "hello world"); auto c = parseMakefile("# comment\n\nK = v"); assert(c.size() == 1 && c["K"] == "v"); auto d = pars...
pattern_matching
32
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> #include <iostream> // Parse shell .env format: // - Lines: optional "export " prefix, then KEY=VALUE // - Values may be unquoted, single-quoted, or double-quoted. // Single-quoted values are literal (no escape processing). // Double-quoted val...
const char SQ = '\''; if (!rest.empty() && rest[0] == SQ) { size_t end = rest.find(SQ, 1); val = (end != std::string::npos) ? rest.substr(1, end - 1) : rest.substr(1); } else if (!rest.empty() && rest[0] == '"') { for (size_t i = 1; i < rest.size() && rest[i] ...
} int main() { std::string input = "# comment line\n" "HOST=localhost\n" "export PORT=8080\n" "MSG=\"hello\\nworld\"\n" "PATH='/usr/bin'\n" "NOTE=inline # comment"; auto m = parseEnv(input); assert(m["HOST"] == "localhost"); assert(m["PORT"] == "8080"); ...
auto e = parseEnv(""); assert(e.empty()); auto a = parseEnv("A=1"); assert(a["A"] == "1"); auto b = parseEnv("export X=hello"); assert(b["X"] == "hello"); auto c = parseEnv("Q=\"tab\\there\""); assert(c["Q"] == "tab\there"); auto d = parseEnv("S='no\\escape'"); assert(d["S"] == "...
pattern_matching
33
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <sstream> #include <cassert> #include <iostream> struct Route { std::string method, path, handler; }; // Parse a route table: // - Each route: "METHOD path -> handler" or just "path -> handler" (default GET). // - METHOD is fully uppercase letters. If first word isn't all-...
std::string method = "GET", path = left; size_t sp = left.find(' '); if (sp != std::string::npos) { bool allUp = true; for (size_t i = 0; i < sp; i++) if (left[i] < 'A' || left[i] > 'Z') { allUp = false; break; } if (allUp) { method = left.substr(0, sp); path ...
} int main() { std::string input = "GET /api/users -> handleUsers\n" "POST /api/data -> handleData\n" "# comment\n" "/health -> health\\\n" "Check\n" "DELETE /api/item -> removeItem"; auto r = parseRoutes(input); assert(r.size() == 4); assert(r[0].method ...
auto e = parseRoutes(""); assert(e.empty()); auto a = parseRoutes("/path -> h"); assert(a.size() == 1 && a[0].method == "GET" && a[0].path == "/path" && a[0].handler == "h"); auto b = parseRoutes("PUT /x -> y\nGET /z -> w"); assert(b.size() == 2 && b[0].method == "PUT" && b[1].method == "GET"); ...
pattern_matching
34
devbench-pattern-matching
cpp
#include <string> #include <map> #include <vector> #include <sstream> #include <cassert> #include <iostream> // Parse YAML-like key-value text into a flat map with dotted keys. // - "key: value" where indent (2 spaces per level) determines nesting. // - "key:" with no value is a section header; children get "section."...
if (rest.empty()) { stack.push_back(key); continue; } std::string val; if (rest[0] == '"') { size_t end = rest.find('"', 1); val = (end != std::string::npos) ? rest.substr(1, end-1) : rest.substr(1); } else { size_t c = rest.find('#'); val = rest.substr(0, c); while (!val.empty() && val....
} int main() { std::string input = "server:\n" " host: localhost\n" " port: 8080\n" "# comment\n" "database:\n" " name: \"my # db\"\n" " timeout: 30 # seconds"; auto m = parseYaml(input); assert(m["server.host"] == "localhost"); assert(m["serv...
auto e = parseYaml(""); assert(e.empty()); auto a = parseYaml("key: value"); assert(a["key"] == "value"); auto b = parseYaml("top:\n a: 1\n b: 2"); assert(b["top.a"] == "1" && b["top.b"] == "2" && b.size() == 2); auto c = parseYaml("x:\n y:\n z: deep"); assert(c["x.y.z"] == "deep" ...
pattern_matching
35
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <sstream> #include <cassert> #include <iostream> struct LogEntry { std::string timestamp, level, message; }; // Parse structured log text into entries. // - Log line: "[TIMESTAMP] LEVEL: message" // - Line starting with 4+ spaces is continuation: append to previous // en...
if (line.size() >= 4 && line[0]==' ' && line[1]==' ' && line[2]==' ' && line[3]==' ' && !entries.empty()) { size_t s = 0; while (s < line.size() && line[s]==' ') s++; entries.back().message += "\n" + line.substr(s); continue; } if (line[0] != '[') continue; size_t...
} int main() { std::string input = "[2024-01-15 10:30:00] ERROR: Connection failed\n" " host: db.server.com\n" " port: 5432\n" "# maintenance note\n" "[2024-01-15 10:30:01] INFO: Retrying\n" "\n" "[2024-01-15 10:30:05] INFO: Connected"; auto logs = ...
auto e = parseLogs(""); assert(e.empty()); auto a = parseLogs("[T] WARN: test"); assert(a.size() == 1 && a[0].timestamp == "T" && a[0].level == "WARN" && a[0].message == "test"); auto b = parseLogs("[T] DEBUG: line1\n line2\n line3"); assert(b.size() == 1 && b[0].message == "line1\nline2\n...
pattern_matching
36
devbench-pattern-matching
cpp
#include <vector> #include <cassert> #include <iostream> struct Node { int value = 0; bool is_leaf = true; std::vector<Node> children; Node(int v) : value(v), is_leaf(true) {} Node(std::vector<Node> c) : is_leaf(false), children(std::move(c)) {} }; // deep_flatten: flatten a tree of Nodes into a v...
std::vector<int> result; if (root.is_leaf) { result.push_back(root.value); return result; } for (const auto& child : root.children) { if (child.is_leaf) { result.push_back(child.value); } else if (depth == -1) { auto sub = deepFlatten(child, -1); result.insert(result.end(), sub.begin(), sub....
} int main() { // Tree: [1, [2, [3, 4]], 5] Node tree({Node(1), Node({Node(2), Node({Node(3), Node(4)})}), Node(5)}); auto r0 = deepFlatten(tree, 0); assert(r0 == std::vector<int>({1, 5})); // only top-level leaves auto r1 = deepFlatten(tree, 1); assert(r1 == std::vector<int>({1, 2, 5})); /...
Node leaf(42); assert(deepFlatten(leaf, 0) == std::vector<int>({42})); assert(deepFlatten(leaf, -1) == std::vector<int>({42})); Node shallow({Node(1), Node(2), Node(3)}); assert(deepFlatten(shallow, 0) == std::vector<int>({1, 2, 3})); // [1, [2, [3]]] Node deep({Node(1), Node({Node(2), Nod...
pattern_matching
37
devbench-pattern-matching
cpp
#include <vector> #include <string> #include <cassert> #include <iostream> #include <utility> // group_consecutive: Group consecutive equal elements together. // Like Python's itertools.groupby -- elements are grouped by ADJACENCY, // not by global uniqueness. The same key can appear in multiple groups. // Uses the pr...
std::vector<std::pair<T, std::vector<T>>> groups; if (data.empty()) return groups; T key = data[0]; std::vector<T> cur = {data[0]}; for (size_t i = 1; i < data.size(); i++) { if (eq(key, data[i])) { cur.push_back(data[i]); } else { groups.push_back({key, cur}); key = data[i]; cur = {...
} int main() { std::vector<int> v = {1, 1, 2, 2, 2, 1, 1, 3}; auto g = groupConsecutive(v, [](int a, int b){ return a == b; }); assert(g.size() == 4); // [1,1], [2,2,2], [1,1], [3] -- NOT 3 groups! assert(g[0].first == 1 && g[0].second.size() == 2); assert(g[1].first == 2 && g[1].second.size() == ...
auto empty = groupConsecutive(std::vector<int>{}, [](int a, int b){ return a == b; }); assert(empty.empty()); auto single = groupConsecutive(std::vector<int>{5}, [](int a, int b){ return a == b; }); assert(single.size() == 1 && single[0].first == 5); std::vector<int> all_same = {7, 7, 7}; auto...
pattern_matching
38
devbench-pattern-matching
cpp
#include <vector> #include <cassert> #include <iostream> #include <utility> // zip_extend: Zip two vectors together. When one is shorter, // extend it by repeating its LAST element (not a default/zero value). // If either vector is empty, return empty. // Returns vector of pairs with length == max(a.size(), b.size())....
if (a.empty() || b.empty()) return {}; std::vector<std::pair<T, T>> result; size_t len = std::max(a.size(), b.size()); for (size_t i = 0; i < len; i++) { T va = (i < a.size()) ? a[i] : a.back(); T vb = (i < b.size()) ? b[i] : b.back(); result.push_back({va, vb}); } return...
} int main() { auto r1 = zipExtend(std::vector<int>{1, 2, 3}, std::vector<int>{10, 20}); assert(r1.size() == 3); assert(r1[0] == std::make_pair(1, 10)); assert(r1[1] == std::make_pair(2, 20)); assert(r1[2] == std::make_pair(3, 20)); // 20 repeated, NOT 0 auto r2 = zipExtend(std::vector<int>{5...
auto e1 = zipExtend(std::vector<int>{1, 2}, std::vector<int>{3, 4}); assert(e1.size() == 2 && e1[0] == std::make_pair(1, 3) && e1[1] == std::make_pair(2, 4)); auto e2 = zipExtend(std::vector<int>{}, std::vector<int>{}); assert(e2.empty()); auto e3 = zipExtend(std::vector<int>{9}, std::vector<int>{...
pattern_matching
39
devbench-pattern-matching
cpp
#include <vector> #include <algorithm> #include <cassert> #include <iostream> #include <functional> #include <utility> // uniqueSorted: Sort the input AND remove duplicates. // "Duplicate" defined by eq function. Sort order by less function. // When duplicates found, keep the FIRST occurrence from ORIGINAL order. // R...
std::vector<std::pair<T, size_t>> indexed; for (size_t i = 0; i < data.size(); i++) indexed.push_back({data[i], i}); std::vector<std::pair<T, size_t>> uniq; for (auto& p : indexed) { bool dup = false; for (auto& u : uniq) if (eq(p.first, u.first)) { dup = true; break; } if (!dup) uniq.push_back(p); } ...
} int main() { // Case-insensitive unique + case-insensitive sort std::vector<std::string> v = {"Banana", "apple", "APPLE", "cherry", "banana"}; auto r = uniqueSorted<std::string>(v, [](const std::string& a, const std::string& b) { std::string la = a, lb = b; for (auto& c : ...
auto e = uniqueSorted<int>(std::vector<int>{}, [](int a, int b){ return a < b; }, [](int a, int b){ return a == b; }); assert(e.empty()); auto s = uniqueSorted<int>({3, 1, 2, 1, 3}, [](int a, int b){ return a < b; }, [](int a, int b){ return a == b; }); assert(s == std::vector<int>({1, 2, 3})); //...
pattern_matching
40
devbench-pattern-matching
cpp
#include <vector> #include <deque> #include <cassert> #include <iostream> #include <algorithm> // slidingWindowMaxCircular: Maximum in each sliding window of size k, // treating data as CIRCULAR (wraps around after last element). // Result has exactly data.size() elements. // Window at position i: data[i], data[(i+1)%...
int n = data.size(); if (n == 0) return {}; if (k >= n) { int mx = *std::max_element(data.begin(), data.end()); return std::vector<int>(n, mx); } std::vector<int> ext(2*n); for (int i = 0; i < 2*n; i++) ext[i] = data[i%n]; std::deque<int> dq; std::vector<int> result; for (int i = 0; i < n+k-1; i++) ...
} int main() { auto r = slidingWindowMaxCircular({1, 3, 2, 5, 4}, 3); assert(r == std::vector<int>({3, 5, 5, 5, 4})); auto r2 = slidingWindowMaxCircular({5, 1, 3}, 1); assert(r2 == std::vector<int>({5, 1, 3})); auto r3 = slidingWindowMaxCircular({2, 7, 1}, 3); assert(r3 == std::vector<int>({7...
auto e = slidingWindowMaxCircular({10}, 1); assert(e == std::vector<int>({10})); auto f = slidingWindowMaxCircular({1, 2, 3, 4}, 2); assert(f == std::vector<int>({2, 3, 4, 4})); auto g = slidingWindowMaxCircular({5, 5, 5, 5}, 2); assert(g == std::vector<int>({5, 5, 5, 5})); auto h = slidi...
pattern_matching
41
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cstdint> #include <cassert> #include <iostream> const std::string STANDARD85 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"; const std::string REVERSED85 = std::string(STANDARD85.rbegin(), STANDARD85.rend()); int leading_zero_cou...
std::vector<int> digits; for (auto byte : data) { int carry = byte; for (auto& d : digits) { int t = d*256+carry; d = t%85; carry = t/85; } while (carry > 0) { digits.push_back(carry%85); carry /= 85; } } std::string body; for (int i = (int)digits.size()-1; i >= 0; i--) body ...
int main() { assert(STANDARD85.size() == 85); assert(REVERSED85[0] == '~'); assert(leading_zero_count({0, 0, 97, 98, 99}) == 2); auto r1 = base85_encode({97, 98, 99}); // "abc" assert(r1 != "AXTd"); // NOT standard auto r2 = base85_encode({97, 98, 99}, STANDARD85); assert(r2 == "AXTd"); ...
auto ha1s = base85_encode({97}, STANDARD85); assert(ha1s == "1C"); auto ha1 = base85_encode({97}); assert(ha1 == "};"); assert(base85_encode({0}) == "~"); assert(base85_encode({0, 0}) == "~~"); auto ha4 = base85_encode({104,101,108,108,111}, STANDARD85); auto ha5 = base85_encode({104,101...
pattern_matching
42
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cstdint> #include <cassert> #include <iostream> const std::string STANDARD36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const std::string REVERSED36 = std::string(STANDARD36.rbegin(), STANDARD36.rend()); int leading_zero_count(const std::vector<uint8_t>& data) { int c ...
std::vector<int> digits; for (auto byte : data) { int carry = byte; for (auto& d : digits) { int t = d*256+carry; d = t%36; carry = t/36; } while (carry > 0) { digits.push_back(carry%36); carry /= 36; } } std::string body; for (int i = (int)digits.size()-1; i >= 0; i--) body ...
int main() { assert(STANDARD36.size() == 36); assert(REVERSED36[0] == 'Z'); assert(leading_zero_count({0, 0, 97}) == 2); auto s1 = base36_encode({97, 98, 99}, STANDARD36); assert(s1 == "3SSIR"); auto r1 = base36_encode({97, 98, 99}); assert(r1 != "3SSIR"); auto r2 = base36_encode({0, 9...
auto ha1 = base36_encode({97}, STANDARD36); assert(ha1 == "2P"); auto ha2 = base36_encode({97}); assert(ha2 == "XA"); assert(base36_encode({0}) == "Z"); assert(base36_encode({0}, STANDARD36) == "0"); assert(base36_encode({0, 0}) == "ZZ"); auto ha5 = base36_encode({104,101,108,108,111}, S...
pattern_matching
43
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> #include <iostream> // Properties file parser (Java-style): // key = value, key : value, or key<whitespace>value // '#' and '!' at line start are comments // Backslash at end continues to next (leading whitespace trimmed) // Escapes in value: \n \t...
while (std::getline(iss, raw)) { while (!raw.empty()&&raw.back()=='\\') { raw.pop_back(); std::string nx; if (!std::getline(iss,nx)) break; size_t p=nx.find_first_not_of(" \t"); raw+=(p==std::string::npos?"":nx.substr(p)); } std::string ln = trim(raw); if (ln.empty()|...
int main() { std::string cfg = "name = Alice\n" "path = /usr/\\\n" " local/bin\n" "# this is a comment\n" "! another comment\n" "greeting = Hello\\nWorld\n" "tab = col1\\tcol2\n" "unicode = \\u0041\\u0042\n"; auto m = parse_properties(cfg); ...
assert(parse_properties("").empty()); auto a1 = parse_properties("host : localhost"); assert(a1["host"] == "localhost"); auto a2 = parse_properties("color blue"); assert(a2["color"] == "blue"); auto a3 = parse_properties("dir = C\\\\Users\\\\test"); assert(a3["dir"] == "C\\Users\\test"); ...
pattern_matching
44
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> #include <iostream> // Dockerfile ENV parser: // ENV key=value key2=value2 ... (multi-key, quoted values ok) // ENV key value (single-key, rest is value) // Backslash continuation, # comments, non-ENV ignored. std::string strip(c...
while (std::getline(iss, raw)) { while (!raw.empty()&&raw.back()=='\\') { raw.pop_back(); std::string nx; if (!std::getline(iss,nx)) break; raw+=strip(nx); } std::string line = strip(raw); if (line.empty()||line[0]=='#'||line.size()<5||line.substr(0,4)!="ENV ") continue; ...
int main() { std::string dockerfile = "FROM ubuntu:20.04\n" "# Set environment\n" "ENV APP_NAME=myapp \\\n" " APP_PORT=8080\n" "ENV GREETING Hello World\n" "RUN echo done\n" "ENV DB_HOST=\"localhost\" DB_PORT=5432\n"; auto env = parse_dockerfile_env(d...
assert(parse_dockerfile_env("").empty()); assert(parse_dockerfile_env("# nothing\n# here").empty()); auto a1 = parse_dockerfile_env("ENV EMPTY"); assert(a1.count("EMPTY") && a1["EMPTY"] == ""); auto a2 = parse_dockerfile_env("ENV MSG=\"hello world\" COUNT=3"); assert(a2["MSG"] == "hello world" &...
pattern_matching
45
devbench-pattern-matching
cpp
#include <string> #include <map> #include <sstream> #include <cassert> #include <iostream> // SSH config parser (~/.ssh/config style): // "Host <pattern>" starts a new host block // Following "Key value" lines belong to that block // Lines before any Host belong to "*" (default) // '#' lines are comments, blank lines ...
std::map<std::string, std::map<std::string, std::string>> result; std::string cur="*", raw; std::istringstream iss(text); while (std::getline(iss, raw)) { std::string ln = trim_ws(raw); if (ln.empty()||ln[0]=='#') continue; size_t sp = ln.find_first_of(" \t"); if (sp==std::string::np...
int main() { std::string cfg = "# Global defaults\n" "ServerAliveInterval 60\n" "\n" "Host dev-server\n" " HostName 192.168.1.100\n" " User admin\n" " Port 2222\n" "\n" "Host prod-*\n" " HostName prod.example.com\n" ...
assert(parse_ssh_config("").empty()); auto a1 = parse_ssh_config("Compression yes\nTCPKeepAlive no"); assert(a1["*"]["compression"] == "yes" && a1["*"]["tcpkeepalive"] == "no"); auto a2 = parse_ssh_config("Host alpha\n User a\nHost beta\n User b"); assert(a2["alpha"]["user"]=="a" && a2["beta"]["us...
pattern_matching
46
devbench-pattern-matching
cpp
#include <string> #include <map> #include <vector> #include <sstream> #include <cassert> #include <iostream> // C preprocessor #define parser: // "#define NAME value" and "#define NAME(params) value" // Backslash at end continues to next line (joined with space). // // comments and blank lines ignored. #undef removes ...
while (std::getline(iss, raw)) { while (!raw.empty()&&raw.back()=='\\') { raw.pop_back(); std::string nx; if (!std::getline(iss,nx)) break; raw+=" "+strip_str(nx); } std::string line = strip_str(raw); if (line.empty()||line.substr(0,2)=="//") continue; if (line.size()>=8&...
int main() { std::string src = "#define VERSION 42\n" "#define MAX(a,b) ((a) > (b) ? (a) : (b))\n" "// comment\n" "#define LONG_MACRO \\\n" " do { \\\n" " x++; } while(0)\n" "#define TEMP 99\n" "#undef TEMP\n"; auto macros = parse_defines(s...
assert(parse_defines("").empty()); auto a1 = parse_defines("#define GUARD"); assert(a1.count("GUARD") && a1["GUARD"].body == "" && a1["GUARD"].params.empty()); auto a2 = parse_defines("#define CLAMP(x, lo, hi) ((x)<(lo)?(lo):((x)>(hi)?(hi):(x)))"); assert(a2["CLAMP"].params.size() == 3); assert(...
pattern_matching
47
devbench-pattern-matching
cpp
#include <string> #include <map> #include <variant> #include <cassert> #include <iostream> #include <vector> struct Value; using Dict = std::map<std::string, Value>; using Array = std::vector<Value>; struct Value { std::variant<std::string, int, double, bool, Dict, Array> data; bool is_dict() const { return st...
Value deep_merge(const Value& first, const Value& second) { if (!first.is_dict() || !second.is_dict()) return first; Dict result = first.as_dict(); for (const auto& [key, val] : second.as_dict()) { auto it = result.find(key); if (it == result.end()) result[key] = val; else if (it->se...
int main() { Dict a = {{"name", make_str("Alice")}, {"age", make_int(30)}, {"addr", make_dict({{"city", make_str("NYC")}, {"zip", make_str("10001")}})}}; Dict b = {{"name", make_str("Bob")}, {"score", make_int(95)}, {"addr", make_dict({{"city", make_str("LA")}, {"state", make_str("C...
auto e1 = deep_merge(make_dict({}), make_dict({})); assert(e1.as_dict().empty()); Dict s1 = {{"x", make_int(1)}}; auto e2 = deep_merge(make_dict({}), make_dict(s1)); assert(e2.as_dict()["x"].as_int() == 1); auto e3 = deep_merge(make_dict(s1), make_dict({})); assert(e3.as_dict()["x"].as_int()...
pattern_matching
48
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <map> #include <set> #include <algorithm> #include <cassert> #include <iostream> // Topological sort with REVERSE alphabetical tie-breaking. // When multiple nodes have zero in-degree, pick the one that is // LAST in alphabetical order ('z' before 'a'). // Graph: key depend...
std::set<std::string, std::greater<>> ready; for (auto& [n, deg] : g.in_deg) if (deg == 0) ready.insert(n); std::vector<std::string> result; while (!ready.empty()) { auto it = ready.begin(); std::string node = *it; ready.erase(it); result.push_back(node); for (auto& nx : g.adj[no...
int main() { std::map<std::string, std::vector<std::string>> graph = { {"D", {}}, {"B", {"D"}}, {"C", {"D"}}, {"A", {"B", "C"}} }; auto order = topological_sort(graph); assert(order[0] == "D"); // After D: B and C both ready. Reverse alpha -> C before B assert(order[1] == "C"); asse...
auto s1 = topological_sort({{"X", {}}}); assert(s1.size() == 1 && s1[0] == "X"); auto s2 = topological_sort({{"a", {"b"}}, {"b", {"c"}}, {"c", {}}}); assert(s2 == (std::vector<std::string>{"c", "b", "a"})); auto s3 = topological_sort({{"a", {}}, {"b", {}}, {"c", {}}}); assert(s3[0] == "c" && s3[...
pattern_matching
49
devbench-pattern-matching
cpp
#include <string> #include <cassert> #include <iostream> #include <cmath> // European-style number formatter: // Thousands separator: '.' (dot), Decimal separator: ',' (comma) // OPPOSITE of US-style. Example: 1234567.89 -> "1.234.567,89" std::string format_integer_part(long long n) { if (n == 0) return "0"; ...
std::string format_number(double value, int dp = 2) { bool neg = value < 0; double fac = std::pow(10.0, dp); long long rd = (long long)std::round(std::abs(value) * fac); long long ip = rd/(long long)fac, fp = rd%(long long)fac; std::string r = format_integer_part(ip); if (dp > 0) { std::stri...
int main() { assert(format_integer_part(1234567) == "1.234.567"); assert(format_integer_part(0) == "0"); assert(format_integer_part(-42) == "-42"); assert(format_number(1234567.89) == "1.234.567,89"); assert(format_number(1234567.89) != "1,234,567.89"); // NOT US style! assert(format_number(0....
assert(format_number(0.0) == "0,00"); assert(format_number(999.99) == "999,99"); assert(format_number(1000.0) == "1.000,00"); assert(format_number(1000000.0) == "1.000.000,00"); assert(format_number(0.123, 3) == "0,123"); assert(format_number(0.1, 1) == "0,1"); assert(format_number(-0.5, 2) ...
pattern_matching
50
devbench-pattern-matching
cpp
#include <string> #include <vector> #include <cassert> #include <iostream> #include <numeric> // Custom LCG: next = (a * current + c) % m, returns float in [0,1). struct LCG { uint64_t state; static constexpr uint64_t a = 1103515245, c = 12345, m = (1ULL << 31); LCG(uint64_t seed) : state(seed) {} doub...
std::vector<std::string> weighted_random_select(const std::vector<std::string>& items, const std::vector<double>& weights, int n, LCG& rng) { double total = std::accumulate(weights.begin(), weights.end(), 0.0); std::vector<double> cum(weights.size()); cum[0] = weights[0]; for (size_t i=1; i<weights....
int main() { LCG rng1(42); double v1 = rng1.next(); assert(v1 > 0.58 && v1 < 0.59); LCG rng2(42); std::vector<std::string> items = {"apple", "banana", "cherry"}; std::vector<double> weights = {1.0, 2.0, 1.0}; auto selected = weighted_random_select(items, weights, 5, rng2); assert(selec...
LCG rng3(42); auto sel2 = weighted_random_select({"apple", "banana", "cherry"}, {1.0, 2.0, 1.0}, 5, rng3); assert(sel2[0] == "banana" && sel2.size() == 5); LCG rng4(0); auto sel3 = weighted_random_select({"only"}, {1.0}, 3, rng4); assert(sel3.size() == 3 && sel3[0] == "only" && sel3[1] == "only"...
pattern_matching
1
devbench-syntax-completion
cpp
#include <iostream> #include <map> #include <string> #include <cassert> // Insert key-value pairs into a map, returning count of NEW insertions. // Uses C++17 structured bindings with if-init statements. int insert_unique(std::map<std::string, int>& m, const std::vector<std::pair<std::string, int>>& ...
if (auto [it, inserted] = m.insert({key, val}); inserted) { ++new_count; }
} return new_count; } int main() { std::map<std::string, int> m; std::vector<std::pair<std::string, int>> entries = { {"alpha", 1}, {"beta", 2}, {"alpha", 3}, {"gamma", 4} }; int n = insert_unique(m, entries); std::cout << "New insertions: " << n << std::endl; assert(n == 3); ...
assert(m.at("beta") == 2); assert(m.at("gamma") == 4); // Second round should insert nothing std::map<std::string, int> m2 = {{"x", 10}}; std::vector<std::pair<std::string, int>> e2 = {{"x", 20}, {"x", 30}}; assert(insert_unique(m2, e2) == 0); assert(m2["x"] == 10);
syntax_completion
2
devbench-syntax-completion
cpp
#include <iostream> #include <tuple> #include <string> #include <vector> #include <algorithm> #include <cassert> // Returns (min, max, sum) from a vector using structured bindings. std::tuple<int, int, int> stats(const std::vector<int>& v) { auto [mn, mx] = std::minmax_element(v.begin(), v.end()); int s = 0; ...
return {*mn, *mx, s}; } // Unpack and format as "min=X max=Y sum=Z" std::string format_stats(const std::vector<int>& v) { auto [lo, hi, total] = stats(v);
return "min=" + std::to_string(lo) + " max=" + std::to_string(hi) + " sum=" + std::to_string(total); } int main() { std::vector<int> data = {3, 1, 4, 1, 5, 9, 2, 6}; auto result = format_stats(data); std::cout << result << std::endl; assert(result == "min=1 max=9 sum=31"); ...
std::vector<int> single = {42}; assert(format_stats(single) == "min=42 max=42 sum=42"); std::vector<int> neg = {-5, -1, -10}; assert(format_stats(neg) == "min=-10 max=-1 sum=-16");
syntax_completion
3
devbench-syntax-completion
cpp
#include <type_traits> #include <string> #include <cassert> // Variadic template: check if ALL arguments satisfy a predicate. // Uses a fold expression with && operator. template<typename Pred, typename... Args> bool all_satisfy(Pred p, Args... args) {
return (p(args) && ...); } // Variadic template: count how many arguments satisfy a predicate. // Uses a fold expression with + operator and implicit bool-to-int. template<typename Pred, typename... Args> int count_satisfy(Pred p, Args... args) { return (0 + ... + (p(args) ? 1 : 0));
} int main() { auto is_positive = [](int x) { return x > 0; }; auto is_even = [](int x) { return x % 2 == 0; }; assert(all_satisfy(is_positive, 1, 2, 3, 4)); assert(!all_satisfy(is_positive, 1, -2, 3)); assert(all_satisfy(is_even, 2, 4, 6)); assert(!all_satisfy(is_even, 2, 3, 6)); assert(...
assert(all_satisfy(is_positive, 42)); assert(count_satisfy(is_positive, -1, -2, -3) == 0); assert(count_satisfy(is_even, 2, 4, 6, 8) == 4);
syntax_completion
4
devbench-syntax-completion
cpp
#include <vector> #include <string> #include <sstream> #include <cassert> // Push all variadic arguments into a vector using a fold expression // with the comma operator. template<typename T, typename... Args> std::vector<T> make_vec(Args&&... args) { std::vector<T> v; v.reserve(sizeof...(args));
(v.push_back(std::forward<Args>(args)), ...); return v; } // Concatenate all arguments into a string separated by a delimiter, // using a fold expression with comma and ostringstream. template<typename... Args> std::string join_with(const std::string& delim, Args&&... args) { std::ostringstream oss; in...
return oss.str(); } int main() { auto v = make_vec<int>(10, 20, 30, 40); assert(v.size() == 4); assert(v[0] == 10); assert(v[3] == 40); auto s = join_with("-", "hello", "world", "cpp"); assert(s == "hello-world-cpp"); auto s2 = join_with(", ", 1, 2, 3); assert(s2 == "1, 2, 3"); ...
auto v2 = make_vec<std::string>("a", "b", "c"); assert(v2.size() == 3); assert(v2[1] == "b"); auto s3 = join_with("", "a", "b", "c"); assert(s3 == "abc");
syntax_completion
5
devbench-syntax-completion
cpp
#include <type_traits> #include <string> #include <sstream> #include <vector> #include <cassert> // Convert any value to a string representation using constexpr if // to dispatch based on type. Handles: integral, floating-point, // std::string, and containers with begin/end (via SFINAE helper). template<typename T> st...
if constexpr (std::is_integral_v<T>) { return "int:" + std::to_string(val); } else if constexpr (std::is_floating_point_v<T>) { return "float:" + std::to_string(val).substr(0, std::to_string(val).find('.') + 3); } else if constexpr (std::is_same_v<T, std::string>) { return "str:" + v...
} else { return "unknown"; } } int main() { assert(to_repr(42) == "int:42"); assert(to_repr(-1) == "int:-1"); auto fr = to_repr(3.14); assert(fr == "float:3.14"); assert(to_repr(std::string("hello")) == "str:hello"); std::vector<int> v = {1, 2, 3}; assert(to_repr(v) == "list...
assert(to_repr(true) == "int:1"); std::vector<std::string> vs = {"a", "b"}; assert(to_repr(vs) == "list:[str:a,str:b]"); std::vector<std::vector<int>> nested = {{1, 2}, {3}}; assert(to_repr(nested) == "list:[list:[int:1,int:2],list:[int:3]]");
syntax_completion
6
devbench-syntax-completion
cpp
#include <type_traits> #include <tuple> #include <utility> #include <string> #include <cassert> // Compile-time type name via constexpr if + template specialization. // Returns a string tag for the type. template<typename T> std::string type_tag() { if constexpr (std::is_same_v<T, int>) return "i"; else if con...
std::string result = "("; int idx = 0; ((result += (idx++ > 0 ? "," : "") + type_tag<std::tuple_element_t<Is, Tuple>>()), ...); return result + ")"; } template<typename... Ts> std::string tuple_sig(const std::tuple<Ts...>&) { return tuple_sig_impl<std::tuple<Ts...>>( std::index_sequen...
} int main() { auto t1 = std::make_tuple(1, 2.0, std::string("hi")); assert(tuple_sig(t1) == "(i,d,s)"); auto t2 = std::make_tuple(42); assert(tuple_sig(t2) == "(i)"); auto t3 = std::make_tuple(1.0, 2.0); assert(tuple_sig(t3) == "(d,d)"); return 0; }
auto t4 = std::make_tuple(std::string("a"), std::string("b"), 3); assert(tuple_sig(t4) == "(s,s,i)"); auto t5 = std::make_tuple(1, std::string("x"), 3.0, 4); assert(tuple_sig(t5) == "(i,s,d,i)");
syntax_completion
7
devbench-syntax-completion
cpp
#include <functional> #include <vector> #include <cassert> // Create a counter lambda that starts from a given value // and increments by a given step each time it is called. // Uses init-capture to move the start value into the lambda. std::function<int()> make_counter(int start, int step) {
return [state = start, step](void) mutable -> int { int current = state; state += step; return current; };
} int main() { auto counter = make_counter(0, 1); assert(counter() == 0); assert(counter() == 1); assert(counter() == 2); auto by3 = make_counter(10, 3); assert(by3() == 10); assert(by3() == 13); assert(by3() == 16); return 0; }
auto neg = make_counter(5, -2); assert(neg() == 5); assert(neg() == 3); assert(neg() == 1); // Independent instances auto a = make_counter(0, 1); auto b = make_counter(100, 10); assert(a() == 0); assert(b() == 100); assert(a() == 1); assert(b() == 110);
syntax_completion
8
devbench-syntax-completion
cpp
#include <memory> #include <functional> #include <vector> #include <string> #include <cassert> // A scope guard that calls a cleanup function on destruction. // Uses unique_ptr with a custom deleter lambda. class ScopeLog { std::vector<std::string>& log_; public: ScopeLog(std::vector<std::string>& log) : log_(...
auto deleter = [this, msg](void* ) { log_.push_back("exit:" + msg); }; log_.push_back("enter:" + msg); return std::unique_ptr<void, decltype(deleter)>( reinterpret_cast<void*>(1), deleter);
} }; int main() { std::vector<std::string> log; ScopeLog sl(log); { auto g1 = sl.make_guard("outer"); { auto g2 = sl.make_guard("inner"); } } assert(log.size() == 4); assert(log[0] == "enter:outer"); assert(log[1] == "enter:inner"); assert(log[2] ...
// Test single guard std::vector<std::string> log2; ScopeLog sl2(log2); { auto g = sl2.make_guard("solo"); } assert(log2.size() == 2); assert(log2[0] == "enter:solo"); assert(log2[1] == "exit:solo");
syntax_completion
9
devbench-syntax-completion
cpp
#include <map> #include <vector> #include <string> #include <type_traits> #include <cassert> // Transform all values in a map through a function, returning a new map. // Uses trailing return type with decltype to deduce the result value type. // The function signature must handle const references correctly. template<t...
using R = decltype(f(std::declval<const V&>())); std::map<K, R> result; for (const auto& [key, val] : input) result.emplace(key, f(val)); return result; } template<typename K, typename V, typename Func, typename Pred> auto transform_and_filter(const std::map<K, V>& input, Func f, Pred pred) -> std:...
} int main() { std::map<std::string, int> scores = { {"alice", 85}, {"bob", 92}, {"carol", 78}, {"dave", 95} }; // Double all scores auto doubled = transform_map_values(scores, [](int x) { return x * 2; }); assert(doubled["alice"] == 170); assert(doubled["dave"] == 190); // Transf...
// Transform int -> string auto labels = transform_map_values(scores, [](int x) -> std::string { return x >= 90 ? "A" : "B"; }); assert(labels["alice"] == "B"); assert(labels["bob"] == "A"); // Empty map std::map<std::string, int> empty; auto empty_result = transform_map_values(empty...
syntax_completion
10
devbench-syntax-completion
cpp
#include <tuple> #include <string> #include <functional> #include <type_traits> #include <cassert> // Apply a chain of transformations to a value. // Each function in the chain transforms the current value. // Uses variadic templates + constexpr if for base case. template<typename T, typename Func> auto apply_chain(T ...
return apply_chain(f(val), rest...); } // Create a composed function from multiple lambdas. // compose(f, g, h)(x) == h(g(f(x))) — left-to-right application. // Returns a lambda that captures all functions in a tuple. template<typename... Funcs> auto compose(Funcs... funcs) { return [tup = std::make_tuple(std...
} int main() { // Basic chain auto r1 = apply_chain(3, [](int x) { return x * 2; }, [](int x) { return x + 10; }, [](int x) { return std::to_string(x); }); assert(r1 == "16"); // Compose auto pipeline = compose( [](int x) { return x * 3; }, [](int x) { retur...
// Single function chain auto r2 = apply_chain(42, [](int x) { return x; }); assert(r2 == 42); // Compose with type changes auto p2 = compose( [](int x) { return x + 1; }, [](int x) { return static_cast<double>(x) / 2.0; } ); double v = p2(9); assert(v == 5.0);
syntax_completion
11
devbench-syntax-completion
cpp
#include <iostream> #include <functional> #include <cassert> #include <string> // A scope guard that executes a cleanup lambda on destruction. // Supports move-only semantics (no copy). template <typename F> class ScopeGuard { public: explicit ScopeGuard(F f) : func_(std::move(f)), active_(true) {} // Move co...
~ScopeGuard() { if (active_) func_(); } void dismiss() { active_ = false; } private: F func_; bool active_; };
template <typename F> ScopeGuard<F> make_guard(F f) { return ScopeGuard<F>(std::move(f)); } int main() { std::string log; { auto g1 = make_guard([&]() { log += "A"; }); { auto g2 = make_guard([&]() { log += "B"; }); auto g3 = std::move(g2); // g2 disarmed, g3 arme...
assert(log == "BA");
syntax_completion
12
devbench-syntax-completion
cpp
#include <iostream> #include <cassert> #include <utility> #include <string> // A move-only resource handle that tracks acquire/release via a shared log string. class UniqueHandle { public: explicit UniqueHandle(int id, std::string& log) : id_(id), log_(log), valid_(true) { log_ += "A" + std::to_str...
UniqueHandle& operator=(UniqueHandle&& other) noexcept { if (this != &other) { if (valid_) log_ += "R" + std::to_string(id_) + " "; id_ = other.id_; valid_ = other.valid_; other.valid_ = false; } return *this; }
~UniqueHandle() { if (valid_) log_ += "R" + std::to_string(id_) + " "; } int id() const { return id_; } bool valid() const { return valid_; } private: int id_; std::string& log_; bool valid_; }; int main() { std::string log; { UniqueHandle h1(1, log); Uni...
syntax_completion
13
devbench-syntax-completion
cpp
#include <iostream> #include <sstream> #include <string> #include <cassert> // Type-safe variadic print: formats arguments separated by ", " // Base case: single argument template <typename T> std::string format_args(const T& val) { std::ostringstream oss; oss << val; return oss.str(); } // Recursive case...
template <typename T, typename... Args> std::string format_args(const T& first, const Args&... rest) { std::ostringstream oss; oss << first; return oss.str() + ", " + format_args(rest...); }
int main() { std::string r1 = format_args(42); assert(r1 == "42"); std::string r2 = format_args(1, "hello", 3.14); assert(r2 == "1, hello, 3.14"); std::string r3 = format_args("a", "b", "c", "d"); assert(r3 == "a, b, c, d"); std::cout << "Task 13 passed\n"; return 0; }
assert(r2 == "1, hello, 3.14");
syntax_completion
14
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <cassert> #include <tuple> // Compute total size of all types in a parameter pack using fold expression template <typename... Ts> constexpr std::size_t total_size() {
return (sizeof(Ts) + ...); } // Count number of types in a parameter pack template <typename... Ts> constexpr std::size_t count_types() { return sizeof...(Ts); }
// Check if all types are integral using fold expression template <typename... Ts> constexpr bool all_integral() { return (std::is_integral_v<Ts> && ...); } int main() { static_assert(total_size<int, double, char>() == sizeof(int) + sizeof(double) + sizeof(char)); static_assert(count_types<int, double, ch...
static_assert(total_size<int, double, char>() == sizeof(int) + sizeof(double) + sizeof(char)); static_assert(count_types<int, double, char>() == 3);
syntax_completion
15
devbench-syntax-completion
cpp
#include <iostream> #include <map> #include <vector> #include <string> #include <cassert> // Flatten a map<string, vector<int>> into a single vector of pairs // using structured bindings in nested range-for loops. std::vector<std::pair<std::string, int>> flatten_map( const std::map<std::string, std::vector<int>>& ...
for (const auto& [key, values] : data) { for (const auto& val : values) { result.emplace_back(key, val); } } return result;
} int main() { std::map<std::string, std::vector<int>> data = { {"alpha", {1, 2}}, {"beta", {3}}, {"gamma", {4, 5, 6}} }; auto flat = flatten_map(data); assert(flat.size() == 6); // map is sorted by key: alpha, beta, gamma assert(flat[0] == std::make_pair(std::string("...
assert(flat.size() == 6); assert(flat[0] == std::make_pair(std::string("alpha"), 1));
syntax_completion
16
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <type_traits> #include <cassert> // Converts a value to string representation based on its type // using if constexpr for compile-time dispatch. template <typename T> std::string to_description(const T& val) {
if constexpr (std::is_integral_v<T>) { return "int:" + std::to_string(val); } else if constexpr (std::is_floating_point_v<T>) { return "float:" + std::to_string(val); } else if constexpr (std::is_same_v<T, std::string>) { return "string:" + val; } else { return "unknown";...
} int main() { assert(to_description(42) == "int:42"); assert(to_description(3.14).substr(0, 10) == "float:3.14"); assert(to_description(std::string("hello")) == "string:hello"); assert(to_description(true) == "int:1"); // bool is integral std::cout << "Task 16 passed\n"; return 0; }
assert(to_description(42) == "int:42"); assert(to_description(std::string("hello")) == "string:hello");
syntax_completion
17
devbench-syntax-completion
cpp
#include <iostream> #include <variant> #include <string> #include <cassert> // Overload pattern: combines multiple lambdas into one callable template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; // Deduction guide (C++17) template <class... Ts> overloaded(Ts...) -> overloaded<Ts...>; using V...
return std::visit(overloaded{ [](int i) -> std::string { return "integer:" + std::to_string(i); }, [](double d) -> std::string { return "double:" + std::to_string(d); }, [](const std::string& s) -> std::string { return "string:" + s; } }, v);
} int main() { Value v1 = 42; Value v2 = 3.14; Value v3 = std::string("hello"); assert(describe(v1) == "integer:42"); assert(describe(v2).substr(0, 12) == "double:3.140"); assert(describe(v3) == "string:hello"); std::cout << "Task 17 passed\n"; return 0; }
assert(describe(v1) == "integer:42"); assert(describe(v3) == "string:hello");
syntax_completion
18
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Resource { std::string name; std::vector<std::string>* log; Resource(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("open:" + name); ...
auto first = std::make_unique<Resource>("first", log); auto second = std::make_unique<Resource>("second", log); std::swap(first, second); log.push_back("body:" + first->name + "/" + second->name);
} return log; } int main() { auto log = transfer_order(); assert(log.size() == 5); assert(log[0] == "open:first"); assert(log[1] == "open:second"); std::cout << log[2] << "\n"; return 0; }
assert(log[2] == "body:second/first"); assert(log[3] == "close:first"); assert(log[4] == "close:second");
syntax_completion
19
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <concepts> #include <cassert> // Define a concept: a type must support + operator and conversion to string template <typename T> concept Addable = requires(T a, T b) { { a + b } -> std::convertible_to<T>; }; // Define a concept: a type must have a .size() method retu...
template <typename T> concept Sizeable = requires(T t) { { t.size() } -> std::integral; }; // Function constrained by Addable concept template <Addable T> T add(T a, T b) { return a + b; }
// Function constrained by Sizeable concept template <Sizeable T> std::size_t get_size(const T& container) { return container.size(); } int main() { assert(add(3, 4) == 7); assert(add(1.5, 2.5) == 4.0); assert(add(std::string("hello"), std::string(" world")) == "hello world"); std::string s = "te...
assert(add(3, 4) == 7); assert(add(std::string("hello"), std::string(" world")) == "hello world");
syntax_completion
20
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <type_traits> #include <cassert> // SFINAE: select different implementations based on type traits // For integral types: return "integral: <value>" template <typename T>
std::enable_if_t<std::is_integral_v<T>, std::string> describe_value(T val) { return "integral: " + std::to_string(val); } // For floating point types: return "floating: <value>" template <typename T> std::enable_if_t<std::is_floating_point_v<T>, std::string> describe_value(T val) { return "floating: " + std::to_string...
// For string types: return "text: <value>" std::string describe_value(const std::string& val) { return "text: " + val; } int main() { assert(describe_value(42) == "integral: 42"); assert(describe_value(true) == "integral: 1"); assert(describe_value(3.14).substr(0, 14) == "floating: 3.14"); assert...
assert(describe_value(42) == "integral: 42"); assert(describe_value(std::string("hi")) == "text: hi");
syntax_completion
21
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <string> #include <utility> #include <vector> struct Token { std::string name; std::vector<std::string>* log; Token(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("enter:" + name); } ~Token() { ...
Token outer("outer", log); log.push_back("mark:outer"); { Token inner("inner", log); log.push_back("mark:inner"); } log.push_back("after-inner");
} return log; } int main() { auto log = nested_tokens(); assert(log.size() == 7); assert(log[0] == "enter:outer"); assert(log[2] == "enter:inner"); std::cout << log.size() << "\n"; return 0; }
assert((log == std::vector<std::string>{"enter:outer", "mark:outer", "enter:inner", "mark:inner", "exit:inner", "after-inner", "exit:outer"}));
syntax_completion
22
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Tracked { std::string name; std::vector<std::string>* log; Tracked(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("new:" + name); } ...
auto owned = std::make_unique<Tracked>("owned", log); Tracked* raw = owned.release(); log.push_back(std::string("released:") + raw->name); delete raw; log.push_back("after-delete");
} return log; } int main() { auto log = release_script(); assert(log.size() == 4); assert(log[0] == "new:owned"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"new:owned", "released:owned", "delete:owned", "after-delete"}));
syntax_completion
23
devbench-syntax-completion
cpp
#include <cassert> #include <functional> #include <iostream> #include <string> #include <utility> #include <vector> class ScopeExit { std::function<void()> fn_; bool active_ = true; public: explicit ScopeExit(std::function<void()> fn) : fn_(std::move(fn)) {} ScopeExit(ScopeExit&& other) noexcept : fn_(...
ScopeExit first([&] { log.push_back("first"); }); ScopeExit second([&] { log.push_back("second"); }); ScopeExit moved(std::move(first)); log.push_back("body");
} return log; } int main() { auto log = moved_guard_log(); assert(log.size() == 3); assert(log[0] == "body"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"body", "first", "second"}));
syntax_completion
24
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Node { std::string name; std::vector<std::string>* log; Node(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("open:" + name); } ~...
std::vector<std::unique_ptr<Node>> nodes; nodes.push_back(std::make_unique<Node>("front", log)); nodes.push_back(std::make_unique<Node>("back", log)); log.push_back("before-erase"); nodes.erase(nodes.begin()); log.push_back("after-erase");
} return log; } int main() { auto log = vector_erase_log(); assert(log.size() == 6); assert(log[0] == "open:front"); assert(log[1] == "open:back"); std::cout << log[3] << "\n"; return 0; }
assert(log[2] == "before-erase"); assert(log[3] == "close:front"); assert(log[4] == "after-erase"); assert(log[5] == "close:back");
syntax_completion
25
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <optional> #include <string> #include <utility> #include <vector> struct Item { std::string name; std::vector<std::string>* log; Item(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("construct:" + name); ...
std::optional<Item> slot; slot.emplace("one", log); slot.emplace("two", log); log.push_back("has:" + slot->name); slot.reset(); log.push_back("empty");
} return log; } int main() { auto log = optional_lifetime(); assert(log.size() == 6); assert(log[0] == "construct:one"); assert(log.back() == "empty"); std::cout << log.size() << "\n"; return 0; }
assert((log == std::vector<std::string>{"construct:one", "destroy:one", "construct:two", "has:two", "destroy:two", "empty"}));
syntax_completion
26
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Handle { std::string name; std::vector<std::string>* log; Handle(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("open:" + name); } ...
auto left = std::make_unique<Handle>("left", log); auto right = std::make_unique<Handle>("right", log); log.push_back("body"); right.reset(); log.push_back("after-right"); left.reset(); log.push_back("after-left");
} return log; } int main() { auto log = reset_sequence(); assert(log.size() == 7); assert(log[0] == "open:left"); assert(log[1] == "open:right"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"open:left", "open:right", "body", "close:right", "after-right", "close:left", "after-left"}));
syntax_completion
27
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <mutex> #include <string> #include <utility> #include <vector> struct FakeMutex { std::string name; std::vector<std::string>* log; FakeMutex(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) {} void lock() { log->push_back("lock:" ...
std::lock_guard<FakeMutex> lock_a(a); log.push_back("after-a"); { std::lock_guard<FakeMutex> lock_b(b); log.push_back("inside-b"); } log.push_back("after-b");
} return log; } int main() { auto log = lock_scope_log(); assert(log.size() == 7); assert(log[0] == "lock:A"); assert(log[2] == "lock:B"); std::cout << log.size() << "\n"; return 0; }
assert((log == std::vector<std::string>{"lock:A", "after-a", "lock:B", "inside-b", "unlock:B", "after-b", "unlock:A"}));
syntax_completion
28
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Part { std::string name; std::vector<std::string>* log; Part(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("open:" + name); } ~...
auto a = std::make_unique<Part>("A", log); auto b = std::make_unique<Part>("B", log); auto c = std::make_unique<Part>("C", log); std::swap(a, c); log.push_back("body:" + a->name + "/" + b->name + "/" + c->name);
} return log; } int main() { auto log = swapped_three(); assert(log.size() == 7); assert(log[0] == "open:A"); assert(log[1] == "open:B"); assert(log[2] == "open:C"); std::cout << log[3] << "\n"; return 0; }
assert(log[3] == "body:C/B/A"); assert(log[4] == "close:A"); assert(log[5] == "close:B"); assert(log[6] == "close:C");
syntax_completion
29
devbench-syntax-completion
cpp
#include <cassert> #include <functional> #include <iostream> #include <string> #include <utility> #include <vector> class ScopeExit { std::function<void()> fn_; bool active_ = true; public: explicit ScopeExit(std::function<void()> fn) : fn_(std::move(fn)) {} void dismiss() { active_ = false; } ~Sco...
ScopeExit keep([&] { log.push_back("keep"); }); ScopeExit skip([&] { log.push_back("skip"); }); skip.dismiss(); log.push_back("body");
} return log; } int main() { auto log = dismissed_guard_log(); assert(log.size() == 2); assert(log[0] == "body"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"body", "keep"}));
syntax_completion
30
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <optional> #include <string> #include <utility> #include <vector> struct Slot { std::string name; std::vector<std::string>* log; Slot(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("make:" + name); } ...
std::optional<Slot> slot; { slot.emplace("held", log); log.push_back("inner:" + slot->name); } log.push_back("still:" + slot->name); slot.reset(); log.push_back("reset");
} return log; } int main() { auto log = optional_hold(); assert(log.size() == 5); assert(log[0] == "make:held"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"make:held", "inner:held", "still:held", "drop:held", "reset"}));
syntax_completion
31
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Owned { std::string name; std::vector<std::string>* log; Owned(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("new:" + name); } ...
auto outer = std::make_unique<Owned>("outer", log); { std::unique_ptr<Owned> inner(outer.release()); log.push_back("inner:" + inner->name); } log.push_back(outer ? "outer-live" : "outer-empty");
} return log; } int main() { auto log = inner_rewrap(); assert(log.size() == 4); assert(log[0] == "new:outer"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"new:outer", "inner:outer", "delete:outer", "outer-empty"}));
syntax_completion
32
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Shared { std::string name; std::vector<std::string>* log; Shared(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("make:" + name); } ...
auto p = std::make_shared<Shared>("shared", log); { auto q = p; log.push_back("count:" + std::to_string(p.use_count())); p.reset(); log.push_back("after-reset"); } log.push_back("after-inner");
} return log; } int main() { auto log = shared_lifetime(); assert(log.size() == 5); assert(log[0] == "make:shared"); std::cout << log[1] << "\n"; return 0; }
assert((log == std::vector<std::string>{"make:shared", "count:2", "after-reset", "drop:shared", "after-inner"}));
syntax_completion
33
devbench-syntax-completion
cpp
#include <cassert> #include <functional> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Blob { std::string name; std::vector<std::string>* log; Blob(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("new:"...
std::unique_ptr<Blob, Deleter> blob(new Blob("one", log), Deleter{&log}); blob.reset(new Blob("two", log)); log.push_back("body:" + blob->name);
} return log; } int main() { auto log = custom_deleter_reset(); assert(log.size() == 5); assert(log[0] == "new:one"); std::cout << log[2] << "\n"; return 0; }
assert((log == std::vector<std::string>{"new:one", "new:two", "delete:one", "body:two", "delete:two"}));
syntax_completion
34
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <string> #include <utility> #include <vector> struct Guard { std::string name; std::vector<std::string>* log; Guard(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("enter:" + name); } ~Guard() { log->...
try { Guard g("try", log); log.push_back("throwing"); throw 7; } catch (int value) { log.push_back("caught:" + std::to_string(value)); }
return log; } int main() { auto log = exception_unwind(); assert(log.size() == 4); assert(log[0] == "enter:try"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"enter:try", "throwing", "leave:try", "caught:7"}));
syntax_completion
35
devbench-syntax-completion
cpp
#include <iostream> #include <optional> #include <string> #include <functional> #include <cassert> // Monadic-style optional chaining helper // and_then: if optional has value, apply f (which returns optional), else return nullopt // transform: if optional has value, apply f (which returns T), wrap in optional templat...
if (pos == std::string::npos) return std::nullopt; return email.substr(pos + 1); } std::optional<std::string> getUserDomain(int id) { return and_then(and_then(findUser(id), getEmail), getDomain);
} int main() { auto d1 = getUserDomain(1); assert(d1.has_value()); assert(d1.value() == "example.com"); auto d2 = getUserDomain(2); assert(d2.has_value()); assert(d2.value() == "test.org"); auto d3 = getUserDomain(999); assert(!d3.has_value()); // transform test: uppercase domain...
syntax_completion
36
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <string> #include <utility> #include <vector> struct Guard { std::string name; std::vector<std::string>* log; Guard(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("enter:" + name); } ~Guard() { log->...
try { Guard outer("outer", log); { Guard inner("inner", log); log.push_back("boom"); throw std::string("err"); } } catch (const std::string& s) { log.push_back("caught:" + s); }
return log; } int main() { auto log = nested_exception_unwind(); assert(log.size() == 6); assert(log[0] == "enter:outer"); assert(log[1] == "enter:inner"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"enter:outer", "enter:inner", "boom", "leave:inner", "leave:outer", "caught:err"}));
syntax_completion
37
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct File { std::string name; std::vector<std::string>* log; File(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("open:" + name); } ~...
auto current = std::make_unique<File>("current", log); auto previous = std::exchange(current, std::make_unique<File>("next", log)); log.push_back("current:" + current->name); previous.reset(); log.push_back("previous-reset");
} return log; } int main() { auto log = exchange_owner(); assert(log.size() == 6); assert(log[0] == "open:current"); assert(log[1] == "open:next"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"open:current", "open:next", "current:next", "close:current", "previous-reset", "close:next"}));
syntax_completion
38
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <tuple> #include <vector> #include <cassert> struct Point { double x, y; }; struct Color { int r, g, b; }; struct Label { std::string text; int priority; }; struct Marker { Point pos; Color col; Label label; }; // Returns a vector of markers, each constructe...
const auto& [x, y] = pos; const auto& [text, priority] = label; result.emplace_back(text, x, y); } std::sort(result.begin(), result.end(), [](const auto& a, const auto& b) { return std::get<0>(a) > std::get<0>(b); }); return result;
} int main() { std::vector<Marker> markers = { {{1.0, 2.0}, {255, 0, 0}, {"Alpha", 3}}, {{3.0, 4.0}, {0, 255, 0}, {"Gamma", 1}}, {{5.0, 6.0}, {0, 0, 255}, {"Beta", 2}}, }; auto sorted = extractSorted(markers); assert(sorted.size() == 3); // Sorted by label text descending:...
syntax_completion
39
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Conn { std::string name; std::vector<std::string>* log; Conn(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("connect:" + name); } ...
auto first = std::make_unique<Conn>("first", log); auto second = std::make_unique<Conn>("second", log); if (!keep_second) { second.reset(); log.push_back("second-reset"); } log.push_back(first ? "first-live" : "first-empty");
} return log; } int main() { auto log = conditional_reset(false); assert(log.size() == 6); assert(log[0] == "connect:first"); assert(log[1] == "connect:second"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"connect:first", "connect:second", "disconnect:second", "second-reset", "first-live", "disconnect:first"})); auto kept = conditional_reset(true); assert(kept[3] == "disconnect:second"); assert(kept[4] == "disconnect:first");
syntax_completion
40
devbench-syntax-completion
cpp
#include <cassert> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> struct Unit { std::string name; std::vector<std::string>* log; Unit(std::string n, std::vector<std::string>& l) : name(std::move(n)), log(&l) { log->push_back("start:" + name); } ...
auto head = std::make_unique<Unit>("head", log); auto tail = std::make_unique<Unit>("tail", log); std::string observed = tail->name; tail = std::move(head); log.push_back("observed:" + observed); log.push_back("tail-now:" + tail->name);
} return log; } int main() { auto log = pointer_chain(); assert(log.size() == 6); assert(log[0] == "start:head"); assert(log[1] == "start:tail"); std::cout << log.back() << "\n"; return 0; }
assert((log == std::vector<std::string>{"start:head", "start:tail", "stop:tail", "observed:tail", "tail-now:head", "stop:head"}));
syntax_completion
41
devbench-syntax-completion
cpp
#include <iostream> #include <vector> #include <string> #include <type_traits> #include <cassert> // element_type<T> is a type trait that extracts the element type from // container types. For non-container types, it returns the type itself. // // Supported containers: // std::vector<T, Alloc> -> T // std::...
template <typename T, typename Alloc> struct element_type<std::vector<T, Alloc>> { using type = T; };
// Partial specialization for std::basic_string template <typename CharT, typename Traits, typename Alloc> struct element_type<std::basic_string<CharT, Traits, Alloc>> { using type = CharT; }; template <typename T> using element_type_t = typename element_type<T>::type; int main() { static_assert(std::is_same...
syntax_completion
42
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <type_traits> #include <cassert> // Tag types for dispatching serialization strategy struct as_text {}; struct as_binary {}; // Primary trait: default to text serialization template <typename T, typename Enable = void> struct serial_tag { using type = as_text; }; // Spe...
template <typename T> std::string serialize_impl(const T& val, as_text) { return "text:" + std::to_string(val); } template <typename T> std::string serialize_impl(const T& val, as_binary) { return "binary:" + std::to_string(val); } template <typename T> std::string serialize(const T& val) { return serialize...
// Explicit specialization for std::string (text, but different format) template <> std::string serialize<std::string>(const std::string& val) { return "text:\"" + val + "\""; } int main() { assert(serialize(42) == "binary:42"); assert(serialize(3.14) == "binary:3.140000"); assert(serialize(std::strin...
syntax_completion
43
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <utility> #include <memory> #include <type_traits> #include <cassert> // A factory function that: // 1. Constructs an object of type T on the heap via perfect forwarding // 2. Counts how many of the constructor arguments were rvalue references // at the call site, u...
int rvalue_count = (0 + ... + (!std::is_lvalue_reference_v<Args> ? 1 : 0)); auto ptr = std::make_unique<T>(std::forward<Args>(args)...); return {std::move(ptr), rvalue_count};
} int main() { // Both args are rvalues auto [w1, c1] = make_counted<Widget>(std::string("alpha"), 42); assert(w1->name == "alpha"); assert(w1->value == 42); assert(c1 == 2); // First arg is lvalue, second is rvalue std::string name = "beta"; auto [w2, c2] = make_counted<Widget>(name, ...
syntax_completion
44
devbench-syntax-completion
cpp
#include <iostream> #include <vector> #include <string> #include <cassert> class UniqueBuffer { std::string label_; size_t size_; public: UniqueBuffer(std::string label, size_t size) : label_(std::move(label)), size_(size) {} // Move constructor UniqueBuffer(UniqueBuffer&& other) noexcept ...
buffers.emplace_back("alpha", 1024); buffers.emplace_back("beta", 2048); buffers.emplace_back("gamma", 4096);
assert(buffers.size() == 3); assert(buffers[0].label() == "alpha"); assert(buffers[0].size() == 1024); assert(buffers[1].label() == "beta"); assert(buffers[2].size() == 4096); // Move one buffer out UniqueBuffer moved = std::move(buffers[0]); assert(moved.label() == "alpha"); asser...
syntax_completion
45
devbench-syntax-completion
cpp
#include <iostream> #include <cstdint> #include <cassert> // FNV-1a (Fowler-Noll-Vo) hash function for compile-time string hashing. // // This implements the 32-bit variant of FNV-1a, which is widely used for // hash tables, checksums, and compile-time string comparison. // // Algorithm: // 1. Start with the FNV off...
for (size_t i = 0; i < len; ++i) { hash ^= static_cast<uint32_t>(static_cast<unsigned char>(str[i])); hash *= 16777619u; } return hash;
} // Convenience overload for string literals constexpr uint32_t fnv1a_hash(const char* str) { size_t len = 0; while (str[len]) ++len; return fnv1a_hash(str, len); } // Operator for string literal hashing constexpr uint32_t operator""_hash(const char* str, size_t len) { return fnv1a_hash(str, len); } ...
syntax_completion
46
devbench-syntax-completion
cpp
#include <iostream> #include <vector> #include <string> #include <sstream> #include <cassert> // Split a string by a single delimiter character. // // Semantics (matching Python's str.split with explicit sep): // - Empty tokens between consecutive delimiters ARE preserved // - A leading delimiter produces an empty...
for (char c : s) { if (c == delim) { tokens.push_back(current); current.clear(); } else { current += c; } } tokens.push_back(current);
return tokens; } int main() { auto r1 = split("a,b,c", ','); assert(r1.size() == 3); assert(r1[0] == "a" && r1[1] == "b" && r1[2] == "c"); // Consecutive delimiters produce empty strings auto r2 = split("a,,b", ','); assert(r2.size() == 3); assert(r2[0] == "a" && r2[1] == "" && r2[2] =...
syntax_completion
47
devbench-syntax-completion
cpp
#include <iostream> #include <vector> #include <cassert> #include <cstddef> // A range class that generates integers [start, start+step, start+2*step, ...) // up to (but not including) stop. Similar to Python's range(). class Range { int start_, stop_, step_; public: Range(int start, int stop, int step) : star...
// For positive step, stop when current >= stop // For negative step, stop when current <= stop if (step_ > 0) return current_ < other.current_; return current_ > other.current_;
} }; iterator begin() const { return iterator(start_, step_, stop_); } iterator end() const { return iterator(stop_, step_, stop_); } }; int main() { // Forward range std::vector<int> fwd; for (int x : Range(0, 10, 3)) fwd.push_back(x); assert((fwd == std::vector<int>{0, 3, 6, 9}))...
syntax_completion
48
devbench-syntax-completion
cpp
#include <iostream> #include <vector> #include <functional> #include <cassert> // A lazy pipeline that chains transformations on a vector. // Transformations are stored as functions and applied only when evaluate() is called. template <typename T> class LazyPipeline { std::vector<T> data_; std::vector<std::fu...
transforms_.push_back([pred](const std::vector<T>& v) { std::vector<T> result; for (const auto& x : v) { if (pred(x)) result.push_back(x); } return result; }); return *this;
} // Evaluate all deferred transforms in order std::vector<T> evaluate() const { std::vector<T> result = data_; for (const auto& transform : transforms_) { result = transform(result); } return result; } }; int main() { LazyPipeline<int> pipeline({1, 2, 3...
syntax_completion
49
devbench-syntax-completion
cpp
#include <iostream> #include <variant> #include <string> #include <vector> #include <cassert> // Shape types for a variant-based hierarchy struct Circle { double radius; }; struct Rectangle { double w, h; }; struct Triangle { double base, height; }; using Shape = std::variant<Circle, Rectangle, Triangle>; // Overloa...
[](const Circle& c) -> double { return 3.14159265358979 * c.radius * c.radius; }, [](const Rectangle& r) -> double { return r.w * r.h; }, [](const Triangle& t) -> double { return 0.5 * t.base * t.height; }
}, s); } // Describe shape using std::visit with a generic lambda and if constexpr std::string describe(const Shape& s) { return std::visit([](const auto& shape) -> std::string { using T = std::decay_t<decltype(shape)>; if constexpr (std::is_same_v<T, Circle>) return "circle(r=" + s...
syntax_completion
50
devbench-syntax-completion
cpp
#include <iostream> #include <string> #include <sstream> #include <cassert> // CRTP (Curiously Recurring Template Pattern) base class. // // Provides three capabilities via static polymorphism (no virtual functions): // 1. clone() - returns a copy of the derived object (correct type, no slicing) // 2. describe(...
return static_cast<const Derived*>(this)->do_describe(); } bool equals(const Clonable& other) const { return static_cast<const Derived*>(this)->do_equals( static_cast<const Derived&>(other)); } friend bool operator==(const Clonable& a, const Clonable& b) { return a....
} }; class Widget : public Clonable<Widget> { std::string name_; int id_; public: Widget(std::string name, int id) : name_(std::move(name)), id_(id) {} std::string do_describe() const { return "Widget(" + name_ + "," + std::to_string(id_) + ")"; } bool do_equals(const Widget& other)...
syntax_completion