【C++】C++语法的一些小问题

最近使用C++开发时,遇到一些小问题,特此记录

  1. 自己定义了一个双重vector,就一直报错,例如vector<vector<int>>vec,一直提示cannot appear in a constant-expression。但是这句话在Visual studio 2010 中却能正常运行。

    原因:在Linux下,或者C++的某些编译器或者某些版本的C++标准里(具体是因为哪个引起的,暂时没兴趣去追溯),即嵌套的模板中,最后面的两个尖括号不能挨着写。

    思考:为什么?其实理由很简单,因为>>是一个运算符,它是可以被重载的,那么很可能会引起歧义,所以部分标准里就禁止这么做了。以后不论是否会报错,都应该避免这种写法,多打个空格就好啦~

    修改:vector< vector<int> >vec

  2. 使用ofstream时,会报错no matching function for call to std::basic_ofstream<char,
    std::char_traits<char> >::basic_ofstream(std::string&)。

    代码如下

        string path = "1.txt";
        ofstream out(path);

    同样在Visual studio 2010 中能正常运行。

    原因:在C++11标准下才支持 ofstream(std::string&)

    解决:ofstream out(path.c_str())

    参考:no matching function…,from stackoverflow

  3. 不要使用using namespace std在你的代码里。因为std里实现了很多常见的函数,名字也非常普通,比如sort,list等,也许有一天你自己也实现了一个类似的函数,到时候就很容易出现混乱。所以尽量自己写代码加上命名空间,也不要使用类似using namespace std这种省事的写法。
    参考:Why is “using namespace std” in C++ considered bad practice?

  4. >>符合作为输入输出流时,如果对象是string类型,必须添加头文件#incude<sstream>才不会报错

while (!file.eof()) {
    // A word and a double value were both read successfully
    float value_tmp;
    std::string word_tmp;
    file >> word_tmp >> value_tmp;   // >>在添加头文件sstream之后可以使用,否则会报错
    value.push_back(value_tmp);
    word.push_back(word_tmp);
}


5. 要对vector中的自定义类型进行排序,首先需要提供一个函数bool comp(const Interval & a, const Interval & b)来定义类型的排序准则 .然后调用std::sort(intervals.begin(),intervals.end(),comp)写了几个小的测试用例也都通过了,但是当集成在类中的时候编译遇到问题,

Line 30: no matching function for call to 'sort(std::vector<Interval>::iterator, std::vector<Interval>::iterator, <unresolved overloaded function type>)'

刚开始以为是类型不对,改用指针也不行,换用qsort进行排序也不行,折腾了好长时间终于找到资料http://blog.csdn.net/flybywind/article/details/7536311

原来当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样。解决方法是将comp改为非成员函数,或者改用静态函数。


6. C++11新增的 to_string函数,使用非常方便,简单查了下:C++11标准增加了全局函数std::to_string,以及std::stoi/stol/stoll等等函数(这几个就是string转int,long,以及long long啦~)
to_string这个函数还是很强大的!

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)

不仅int可以转换成string,这些都可以哦~

  1. 在使用map时,需要注意,如果使用auto来遍历,如下所示,只是这样操作,改变不了map_samples的值
for (auto sample : map_samples) {       
    samples.second = 10;;
}

如果需要修改,则应该加上引用,如下所示

for (auto &sample : map_samples) {      
    samples.second = 10;;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值