tinycodinglm / cpp /cpp-stackoverflow-001.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
2.82 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

Common C++ patterns from Stack Overflow

Assistant

Common C++ Stack Overflow Patterns:

1. How to split a string by delimiter:

cpp
#include <sstream>
#include <vector>

std::vector<std::string> split(const std::string& s, char delim) {
    std::vector<std::string> result;
    std::istringstream iss(s);
    std::string token;
    while (std::getline(iss, token, delim)) {
        result.push_back(token);
    }
    return result;
}

2. How to convert int to string:

cpp
// C++11+
std::string s = std::to_string(42);

// Using ostringstream
std::ostringstream oss;
oss << 42;
std::string s = oss.str();

3. How to trim a string:

cpp
std::string trim(const std::string& s) {
    auto start = s.find_first_not_of(" \t\n\r");
    auto end = s.find_last_not_of(" \t\n\r");
    return (start == std::string::npos) ? "" : s.substr(start, end - start + 1);
}

4. How to check if string contains substring:

cpp
// C++23
if (str.contains("sub")) { }

// C++11
if (str.find("sub") != std::string::npos) { }

5. How to read entire file to string:

cpp
std::ifstream f("file.txt");
std::string content((std::istreambuf_iterator<char>(f)),
                     std::istreambuf_iterator<char>());

6. How to create a singleton:

cpp
class Singleton {
public:
    static Singleton& instance() {
        static Singleton inst;
        return inst;
    }
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
private:
    Singleton() = default;
};

7. How to implement a thread-safe queue:

cpp
template<typename T>
class ThreadSafeQueue {
    std::queue<T> queue_;
    mutable std::mutex mutex_;
public:
    void push(T value) {
        std::lock_guard<std::mutex> lock(mutex_);
        queue_.push(std::move(value));
    }
    bool pop(T& value) {
        std::lock_guard<std::mutex> lock(mutex_);
        if (queue_.empty()) return false;
        value = std::move(queue_.front());
        queue_.pop();
        return true;
    }
};