C++排雷:20.写代码时,对各类容器的输出、索引的访问需要注意的

    技术2022-07-21  88

    一定要考虑安全性,不能越界! 所以读取、输出一定要嵌套在合理判断内部: 比如,在下列将string加入vector的代码中,输出vector内部的内容时,if (vec_str.size()>0)判断:

    #include<iostream> #include<string> #include<vector> using namespace std; int main() { string a; char back; vector<string> vec_str; cout << "please enter a integer"; while (cin >> a) { vec_str.push_back(a); cout << "if continue to push? n to break\n"; cin >> back; if (back=='n') { break; } cout << "please enter a integer"; } //这类判断是十分有必要的!!!! if (vec_str.size()>0) { for (auto it : vec_str) { cout << it << endl; } } return 0; }
    Processed: 0.014, SQL: 9