在Dev-C++中启用C++11标准后(通过编译器选项-std=c++11),您可以使用以下核心新特性:


1. 自动类型推导 (auto)

auto x = 5;          // x 被推导为 int
auto str = "Hello";  // str 被推导为 const char*
std::vector<int> vec = {1, 2, 3};
for (auto it = vec.begin(); it != vec.end(); ++it) {...}


2. 基于范围的循环 (range-based for)

std::vector<int> nums = {1, 2, 3};
for (int num : nums) {  // 遍历容器
    std::cout << num << " ";
}


3. Lambda表达式

std::vector<int> vec = {3, 1, 4};
std::sort(vec.begin(), vec.end(), [](int a, int b) {
    return a > b; // 降序排序
});


4. 智能指针 (unique_ptr, shared_ptr)

#include <memory>
std::unique_ptr<int> ptr(new int(10));  // 自动内存管理
std::shared_ptr<int> shared = std::make_shared<int>(20);


5. 右值引用和移动语义

std::vector<int> getVector() {
    return std::vector<int>{1, 2, 3}; // 避免拷贝
}
std::vector<int> v = getVector(); // 移动构造


6. 初始化列表 (initializer_list)

std::vector<int> nums = {1, 2, 3}; // 统一初始化
std::map<std::string, int> dict = {{"a", 1}, {"b", 2}};


7. 类型别名 (using)

using Vec = std::vector<double>; // 替代 typedef
Vec values = {1.1, 2.2};


8. nullptr 关键字

void func(int* ptr) {...}
func(nullptr); // 明确空指针


9. 强类型枚举 (enum class)

enum class Color { Red, Blue };
Color c = Color::Red; // 避免命名冲突


10. 标准库增强

  • 容器std::arraystd::unordered_map
  • 算法std::all_ofstd::any_of
  • 线程支持std::thread(需链接-lpthread
#include <array>
#include <algorithm>
std::array<int, 3> arr = {5, 2, 7};
if (std::all_of(arr.begin(), arr.end(), [](int i){ return i > 0; })) {
    std::cout << "全为正数";
}


启用步骤
在Dev-C++中,进入 工具 → 编译选项 → 编译器,勾选 "编译时加入以下命令" 并输入:

-std=c++11

注意:部分特性(如线程库)需确保编译器版本支持(如MinGW-w64)。若遇到兼容性问题,建议升级编译器工具链。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐