C++ 代码与众不同最全指南

· · 算法·理论

C++ 代码装逼与众不同超强指南

为了让 C++ 代码更加高效、易读 、好装逼 且与众不同,可以采用多种现代C++特性与最佳实践。

下面我将列举一些技巧 (指寄巧),并给出相应的示例。

满满的干货!非常实用哦。

★使用 std::unordered_map★

基本用法

使用 std::unordered_map 而不是 std::map 可以在很多情况下提高性能,尤其是在查找操作频繁而键的顺序不重要的情况下。std::unordered_map 基于哈希表实现,平均情况下提供接近 O(1) 的查找时间复杂度。

示例:

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> fruitCounts;

    fruitCounts["apple"] = 5;
    fruitCounts["banana"] = 3;
    fruitCounts["cherry"] = 10;

    // 查找元素
    auto it = fruitCounts.find("banana");
    if (it != fruitCounts.end()) {
        std::cout << "Count of bananas: " << it->second << '\n';
    }

    // 更新元素
    ++fruitCounts["apple"];

    // 迭代所有元素
    for (const auto& pair : fruitCounts) {
        std::cout << "Fruit: " << pair.first << ", Count: " << pair.second << '\n';
    }

    return 0;
}

在这个例子中,我们创建了一个 std::unordered_map 来存储水果名称及其对应的数量。我们使用 find 方法来查找元素,operator[] 来插入或更新元素,并通过范围 for 循环来遍历整个映射。

定义自定义哈希函数

为了进一步说明如何使用自定义哈希函数,假设我们需要将 std::pair<int, int> 作为键存储在 std::unordered_map 中。我们可以定义一个简单的哈希函数来实现这一点:

示例:

#include <iostream>
#include <unordered_map>
#include <utility>
#include <functional>

struct PairHash {
    template <class T1, class T2>
    std::size_t operator()(const std::pair<T1, T2>& p) const {
        auto hash1 = std::hash<T1>{}(p.first);
        auto hash2 = std::hash<T2>{}(p.second);
        return hash1 ^ hash2; // 或者使用更复杂的组合方式
    }
};

int main() {
    std::unordered_map<std::pair<int, int>, int, PairHash> map;

    map[{1, 2}] = 10;
    map[{2, 3}] = 20;

    for (const auto& pair : map) {
        std::cout << "Key: (" << pair.first.first << ", " << pair.first.second << "), Value: " << pair.second << '\n';
    }

    return 0;
}

在这个例子中,我们定义了一个 PairHash 结构体来作为自定义哈希函数。它接受 std::pair<int, int> 作为参数,并返回一个 std::size_t 类型的哈希值。然后我们将这个哈希函数传递给 std::unordered_map 的构造函数。

当处理大量数据时,这些技巧尤其有用。

使用 std::numeric_limits

std::numeric_limits 提供了关于数值类型的信息,比如最大值、最小值、精度等。

示例:

#include <iostream>
#include <limits>

int main() {
    std::cout << "Maximum value of int: "
              << std::numeric_limits<int>::max() << '\n';
    std::cout << "Minimum value of float: "
              << std::numeric_limits<float>::min() << '\n';
    return 0;
}

使用 constexpr

constexpr 允许您声明一个表达式或函数可以在编译时计算出结果的常量。

示例:

#include <iostream>

constexpr int square(int x) {
    return x * x;
}

int main() {
    constexpr int result = square(5);
    std::cout << "Square of 5 is: " << result << '\n';
    return 0;
}

使用 std::tuple 或 std::pair

在某些情况下,使用 std::tuple 或 std::pair 可以比使用 struct 更简洁。

示例:

#include <iostream>
#include <tuple>

int main() {
    auto [x, y] = std::make_tuple(10, 20);
    std::cout << "x: " << x << ", y: " << y << '\n';

    // 使用 std::pair
    auto p = std::make_pair("Hello", 42);
    std::cout << "Pair: " << p.first << ", " << p.second << '\n';
    return 0;
}

使用 union

union 可以用来表示同一段内存中存储不同类型的变量。这在处理低级编程时很有用。

示例:

#include <iostream>

union MyUnion {
    int i;
    char c;
    double d;

    MyUnion(int ii) : i(ii) {}
    MyUnion(char cc) : c(cc) {}
    MyUnion(double dd) : d(dd) {}
};

int main() {
    MyUnion u(123);
    std::cout << "Integer value: " << u.i << '\n';

    u.c = 'A';
    std::cout << "Char value: " << u.c << '\n';

    return 0;
}

使用 auto

auto 关键字可以让编译器推导出变量的类型,使得代码更简洁。

示例:

#include <iostream>
#include <vector>

int main() {
    auto numbers = std::vector<int>{1, 2, 3, 4, 5};
    for (auto& n : numbers) {
        std::cout << n << ' ';
    }
    std::cout << '\n';
    return 0;
}

使用 Lambda 表达式

Lambda 表达式允许您定义匿名函数,这在需要简短的函数对象时非常有用。

示例:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> vec{1, 2, 3, 4, 5};
    std::sort(vec.begin(), vec.end(), [](int a, int b) { return a > b; });

    for (auto v : vec) {
        std::cout << v << ' ';
    }
    std::cout << '\n';

    return 0;
}

使用 Range-based for 循环

Range-based for 循环简化了迭代容器的过程。

示例:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec{1, 2, 3, 4, 5};
    for (auto elem : vec) {
        std::cout << elem << ' ';
    }
    std::cout << '\n';

    return 0;
}

使用 std::variant

std::variant 是一个可以保存多个类型之一的容器,类似于 union,但提供了更好的类型安全性和异常安全性。

示例:

#include <iostream>
#include <variant>

int main() {
    std::variant<int, std::string> data = 42;
    if (std::holds_alternative<int>(data)) {
        std::cout << "Integer value: " << std::get<int>(data) << '\n';
    } else if (std::holds_alternative<std::string>(data)) {
        std::cout << "String value: " << std::get<std::string>(data) << '\n';
    }

    return 0;
}

使用 std::any

std::any 是一个可以保存任何类型的容器。

示例:

#include <iostream>
#include <any>

int main() {
    std::any any_data = 42;
    if (any_data.type() == typeid(int)) {
        std::cout << "Integer value: " << std::any_cast<int>(any_data) << '\n';
    }

    any_data = "Hello, world!";
    if (any_data.type() == typeid(std::string)) {
        std::cout << "String value: " << std::any_cast<std::string>(any_data) << '\n';
    }

    return 0;
}

使用 std::string_view

std::string_view 是一个不拥有数据的字符串视图,适用于不需要修改字符串的情况。

示例:

#include <iostream>
#include <string_view>

void print_string(std::string_view str) {
    std::cout << "String: " << str << '\n';
}

int main() {
    print_string("Hello, world!");
    return 0;
}

使用结构化绑定

结构化绑定允许您从一个容器或函数中直接解构值到多个变量。

示例:

#include <iostream>
#include <utility>

std::pair<int, std::string> get_data() {
    return {42, "Hello"};
}

int main() {
    auto [number, text] = get_data();
    std::cout << "Number: " << number << ", Text: " << text << '\n';

    return 0;
}

使用 std::span

std::span 是一个非拥有性的数组视图,它可以替代裸指针和整数长度。

示例:

#include <iostream>
#include <span>

void process(std::span<int> data) {
    for (auto& elem : data) {
        elem *= 2;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    process(std::span(arr));

    for (auto elem : arr) {
        std::cout << elem << ' ';
    }
    std::cout << '\n';

    return 0;
}

使用 C++20 的 std::format

std::format 类似于 Python 的 str.format() 方法,提供了一个强大的格式化输出方法。

示例:

#include <iostream>
#include <format>

int main() {
    std::cout << std::format("Formatted string: {} and {}\n", 42, "hello");
    return 0;
}

使用 using 代替 typedef

using 关键字可以用于创建类型别名,取代了传统的 typedef。

using IntVec = std::vector<int>;
IntVec vec = {1, 2, 3};

使用 decltype

decltype 关键字用于获取表达式的类型。

int x = 5;
decltype(x) y = 10;

以上就是一些可以让你的 C++ 代码更加现代化和高效的技巧。每种技术都有其适用场景,请根据实际需求选择合适的工具。