c++cpp记录

珍爱生命, 远离 c++


前篇

  • a

C++11/14 使用率

11 已经普遍使用, 14 较少, 所以稳定的话还是使用 11. (2020.02.12 记录)


控制台中文乱码

1
2
3
4
int main(int argc, char *argv[]) {
system("chcp 65001"); // 防止中文乱码, 设置字符集
printf("中国智造");
}

踩坑

string 转 char* 问题

1
2
3
4
char *mystr = "hello"; // 这样声明会报 警告: ISO C++ forbids converting a string constant to 'char*'

// 应该加个 const
const char *mystr = "hello";

参考: https://stackoverflow.com/questions/20944784/why-is-conversion-from-string-constant-to-char-valid-in-c-but-invalid-in-c


extern 警告

  • 警告 Warning: initialized and declared extern`

    是因为这种声明方式导致的

    1
    extern "C" int i = 100;

    改成这种方式就不会有警告了

    1
    2
    3
    extern "C" {
    int i = 100;
    }

stl_algo.h error: no match for ‘operator-‘ 错误

可能的原因

  • list 使用了 #include <algorithm> 里的 std::stable_sort, 需要修改为 list 内置的 sort 方法

    1
    2
    3
    tmplist.sort([](const int &_a, const int &_b) { return _a > _b ? true : false; });
    // std::stable_sort(tmplist.begin(), tmplist.end(),
    // [](const int &_a, const int &_b) { return _a > _b ? true : false; });

    参考: https://www.itdaan.com/tw/f4d993ad62a8d0b11537a3a125f4c871

    std :: stable_sort 需要一個随机访问迭代器. list 的迭代器不是不是随机访问的.


warning: built-in function ‘index’ declared as non-function

声明了一个与 g++ 内置变量 同名 的变量, 重命名一下变量即可.