vector初始化
#include
#include <string>
#include int main()
{std::vector<int> v1(10) ; //10个int数据&#xff0c;每个都为0std::vector<int> v2(10,100);//10个int数据&#xff0c;每个为100std::vector<int> v3{1,2,3,4,5};//5个int数据&#xff0c;分别为1&#xff0c;2,3,4,5
std::vectorstring> v4{"C&#43;&#43;"};std::vectorstring> v5{10};std::vectorstring> v6{10,"C&#43;&#43;"};std::vectorstring> v7(10);std::vectorstring> v8(10,"C&#43;&#43;");std::vectorstring> v9{"C&#43;&#43;","是","人类的好朋友"};std::cout<<"--------------------------------------"<<std::endl;for(auto i : v1)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v2)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v3)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v4)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v5)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v6)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v7)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v8)std::cout<" ";std::cout<<std::endl;std::cout<<"--------------------------------------"<<std::endl;for(auto i : v9)std::cout<" ";std::cout<<std::endl;return 0;
}
string和vertor下标只能访问已经存在的元素&#xff0c;不能创建元素&#xff08;编译不会出错&#xff0c;运行时出错&#xff09;
#include
#include <string>
#include int main()
{std::vector<int> i ;i[0] &#61; 10 ; //错误return 0;
}
下标越界编译运行都没有报错&#xff0c;但是已经出错
#include
#include <string>
#include int main()
{std::vector<int> i(10) ;i[100] &#61; 100 ; //错误
std::cout<100]<<std::endl;return 0;
}
向空的vector中添加元素
#include
#include <string>
#include int main()
{std::vector<int> i;for(decltype(i.size()) index&#61;0;index<&#61;100;&#43;&#43;index){i.push_back(index) ;}for(auto& re : i){re *&#61; re ;std::cout<std::endl ;}
}
统计各个分段内的人数&#xff08;0-9,10-19...90-99,100&#xff09;
#include
#include <string>
#include int main()
{std::vector num(11,0) ;//11个元素&#xff0c;每个为0
unsigned grade &#61; 0 ;while(std::cin>>grade)if(grade<&#61;100)&#43;&#43;num[grade/10] ;for(auto i : num)std::cout<" ";std::cout<<std::endl;
}
和string一样&#xff0c;vector也有size()和empty()方法