代码片段仓库

收集、管理和分享有用的代码片段,提高开发效率

代码片段

C++异常 C++

try-catch示例

#include <iostream>
using namespace std;

float divide(float a, float b) {
    if (b == 0.0f) {
        throw "Division by zero!";
    }
    return a / b;
}

int main() {
    try {
        cout << divide(10.0f, 2.0f) << endl;
        cout << divide(5.0f, 0.0f) << endl;
    } catch (const char *msg) {
        cerr << "Error: " << msg << endl;
    }
    return 0;
}
Python装饰器 Python

函数计时装饰器

import time

def time_it(func):
    def wrapper(***args):
        start = time.time()
        result = func(***args)
        end = time.time()
        print(f"Execution time: {end - start} s")
        return result
    return wrapper

@time_it
def sleep_demo(seconds):
    time.sleep(seconds)
    return "Done"
Java反射 Java

动态调用方法

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("java.util.ArrayList");
        Object list = clazz.getDeclaredConstructor().newInstance();
        Method addMethod = clazz.getMethod("add", Object.class);
        addMethod.invoke(list, "Hello Reflection!");
        System.out.println(list);
    }
}
C++ map C++

std::map使用

#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string, int> scores;
    
    // Insert elements
    scores["Alice"] = 90;
    scores["Bob"] = 85;
    scores["Charlie"] = 95;
    
    // Access elements
    cout << "Charlie's score: " << scores["Charlie"] << endl;
    
    // Iterate over map
    for (const auto& keyValue : scores) {
        cout << keyValue.first << ": " << keyValue.second << endl;
    }
    return 0;
}
JS生成器 JavaScript

生成器函数示例

function* fibonacciSequence() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const gen = fibonacciSequence();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
PHP文件读写 PHP

读写文件内容

🔥             

为什么选择CodeSnippets?

高效管理您的代码片段,提高开发效率

智能搜索

通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能

语法高亮

支持多种编程语言的语法高亮,使代码更加清晰易读

多设备同步

随时随地访问您的代码片段库,支持桌面和移动设备

热门分类

浏览最受欢迎的代码分类