1、从vector中删除多个元素:
#include <iostream> #include <vector> int main() { std::vector<int> vect; for(int i = 1; i <= 100; i++) { vect.push_back(i); } ///* int size = vect.size(); for(unsigned int i = 0; i < size;) { if(vect[i] % 2 == 1) { vect.erase(vect.begin() + i); size--; } else { i++; } } //*/ /* auto it = vect.begin(); while(it != vect.end()) { if(*it % 2 == 1) { vect.erase(it); } else { it++; } } */ for(auto& item : vect) { std::cout<<"item:"<<item<<std::endl; } int main() { std::vector<int> vect; for(int i = 1; i <= 100; i++) { vect.push_back(i); } ///* int size = vect.size(); for(unsigned int i = 0; i < size;) { if(vect[i] % 2 == 1) { vect.erase(vect.begin() + i); size--; } else { i++; } } //*/ /* auto it = vect.begin(); while(it != vect.end()) { if(*it % 2 == 1) { vect.erase(it); } else { it++; } } */ for(auto& item : vect) { std::cout<<"item:"<<item<<std::endl; } }
std::vector可以越界访问,如以下代码会输出0,而不会抛出异常。应该是由vector建立时的容量决定的。
#include <iostream> #include <vector> int main() { std::vector<int> vect; vect.push_back(1); vect.push_back(2); std::cout<<vect[3]<<std::endl; }
定义一个返回引用的函数,但如果接收的类型没有定义为引用类型,则仍会是复制,auto也是复制。如下:
#include <iostream> #include <vector> class Test { Test(){}; public: static Test& Instance() { static Test _instance; return _instance; } std::vector<int>& get_vect() { return vect; } std::vector<int> vect; }; int main() { Test::Instance().vect.push_back(1); Test::Instance().vect.push_back(2); std::vector<int> vect = Test::Instance().get_vect(); //复制 //std::vector<int>& vect = Test::Instance().get_vect(); //引用 vect.push_back(1); vect.push_back(2); for(auto item : Test::Instance().vect) { std::cout<<item<<std::endl; } }