C++ 阅读时间 2 分钟

在 C++ 中抽象技术层细节,降低语言的学习曲线

分享本文
Abstracting technical layer details in C++ to mitigate the language's learning curve.

最近,我在 LinkedIn 上看到一篇帖子,展示了一位 C++ 开发者第一次看到 Python 中数组排序方式时的反应。不出所料,Python 方式的简洁性令他大为震惊。

arr=[64,12,22,55,44]
bubble_sort(arr)
print("Sorted Array:",arr)

这类观察与其说是关于语言本身,不如说是关于库和框架所提供的抽象。通过将复杂性隐藏在我们自己的框架或现有框架背后,我们也可以在 C++ 中实现类似的简洁。

与其使用这样的代码:

 std::vector<int> vec = {64, 12, 22, 55,44};
 std::sort(vec.begin(), vec.end());
 std::cout << "Sorted vector: ";
 for(const int& num : vec) {
        std::cout << num << " ";
  }
  std::cout << std::endl;

我们可以使用合适的 C++ 库,写出这样的代码:

auto arr[] = { 64, 12,22,55,44 }; 
boost::sort(arr);
boost::print(std::cout, arr);

即使知名的 C++ 库中不存在这样的便利设施,许多项目也依赖于内部库来抽象技术复杂性,无论使用何种编程语言,都能让任务变得更简单。

C++ 常被认为复杂,因为它没有为常见任务提供开箱即用的设施。例如,在使用标准模板库(STL)时,开发者必须直接使用迭代器,由于频繁使用.begin()和.end()函数,代码可能会变得复杂。

#include <iostream>
#include <vector>
#include <algorithm> // for std::sort and std::merge
#include <iterator>  // for std::back_inserter

int main() {
    std::vector<int> vec1 = {1, 4, 7, 10};
    std::vector<int> vec2 = {2, 5, 8, 11};
    std::vector<int> vec3 = {3, 6, 9, 12};

    // Merging vec1 and vec2 into vecMerged
    std::vector<int> vecMerged;
    std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(vecMerged));

    // Merging vecMerged with vec3
    std::vector<int> vecFinal;
    std::merge(vecMerged.begin(), vecMerged.end(), vec3.begin(), vec3.end(), std::back_inserter(vecFinal));

    // Sorting vecFinal
    std::sort(vecFinal.begin(), vecFinal.end());

    // Printing the sorted merged vector
    std::cout << "Sorted merged vector: ";
    for (auto it = vecFinal.begin(); it != vecFinal.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

然而,凭借 C++ 的能力,我们可以实现与任何现代编程语言相媲美的简洁、易懂的代码。要做到这一点,需要掌握通过合适的库和健壮的内部技术框架向开发者隐藏复杂性的艺术。负责这一技术层的团队在保持代码可读性和可维护性方面发挥着至关重要的作用。

结论

C++ 中技术框架提供的抽象可以通过为常见任务提供高级接口来显著简化开发。这减少了理解语言及其底层实现复杂细节的需求,使开发者更容易编写高效、可读、可维护的代码。通过利用这些抽象,开发者可以专注于解决手头的实际问题,而不是纠缠于底层细节。

分享本文