最近使用C++开发时,遇到一些小问题,特此记录
自己定义了一个双重vector,就一直报错,例如
vector<vector<int>>vec
,一直提示cannot appear in a constant-expression
。但是这句话在Visual studio 2010 中却能正常运行。原因:在Linux下,或者C++的某些编译器或者某些版本的C++标准里(具体是因为哪个引起的,暂时没兴趣去追溯),即嵌套的模板中,最后面的两个尖括号不能挨着写。
思考:为什么?其实理由很简单,因为>>是一个运算符,它是可以被重载的,那么很可能会引起歧义,所以部分标准里就禁止这么做了。以后不论是否会报错,都应该避免这种写法,多打个空格就好啦~
修改:
vector< vector<int> >vec
使用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())
不要使用
using namespace std
在你的代码里。因为std里实现了很多常见的函数,名字也非常普通,比如sort,list等,也许有一天你自己也实现了一个类似的函数,到时候就很容易出现混乱。所以尽量自己写代码加上命名空间,也不要使用类似using namespace std
这种省事的写法。
参考:Why is “using namespace std” in C++ considered bad practice?>>
符合作为输入输出流时,如果对象是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,这些都可以哦~
- 在使用map时,需要注意,如果使用auto来遍历,如下所示,只是这样操作,改变不了map_samples的值
for (auto sample : map_samples) {
samples.second = 10;;
}
如果需要修改,则应该加上引用,如下所示
for (auto &sample : map_samples) {
samples.second = 10;;
}