vector 向量容器
C++代码功能实现
#include<vector>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
bool Comp(const int &a,const int &b)
{
if(a!=b) return a>b;
else return a>b;
}
int main()
{
vector<int> v(10);
for(int i=0;i<10;i++)
v[i]=i;
v.erase(v.begin()+2);//删除
vector<int>::iterator t;
for(t=v.begin();t!=v.end();t++)
cout<<*t<<" ";
cout<<endl;
v.erase(v.begin()+4);
for(t=v.begin();t!=v.end();t++)
cout<<*t<<" ";
cout<<endl;
v.erase(v.begin()+1,v.begin()+5);
for(t=v.begin();t!=v.end();t++)
cout<<*t<<" ";
cout<<endl<<v.size()<<endl;
// v.clear();
cout<<v.size()<<endl<<v[0]<<" "<<v[1]<<" "<<v[2]<<" "<<v[3]<<endl;
reverse(v.begin(),v.end());
for(t=v.begin();t!=v.end();t++)
cout<<*t<<" ";
cout<<endl;
vector<int> a;
for(int i=0;i<10;i++)
a.push_back(9-i);
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
sort(a.begin(),a.end());//按升序排序
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
vector<int> b;
for(int i=0;i<10;i++)
b.push_back(i);
cout<<endl;
sort(b.begin() ,b.end(),Comp);//按Comp规则排序
for(int i=0;i<10;i++)
cout<<b[i]<<" ";
cout<<endl;
cout<<b.size()<<endl;//包含多少个元素
cout<<b.empty()<<endl;//如果为0则为真,为1则为假;
b.clear();//清空
cout<<b.empty()<<endl;
cout<<endl;
return 0;
}
string 容器
C++代码实现
#include<string.h>
#include<iostream>//向量需要
#include<algorithm>//使用反向排序reverse()函数
#include<vector>
using namespace std;
int main()
{
string s;//创建字符串对象
s="zhang wei play C++.";//对象赋值
cout<<s.length()<<endl;
cout<<s<<endl; //下标从零开始计数
char ss[1000];
scanf("%s",ss);
s=ss;//把字符数组赋值给string对象
cout<<s<<endl;
s=s+'z';//string对象尾部加字符
s=s+'w';
cout<<s<<endl;
s=s+"zhangwei";//尾部加字符串
cout<<s<<endl;
s.append("iewgnahz");//与尾部加字符串一样
cout<<s<<endl;
string::iterator t;//定义迭代器
t=s.begin();
s.insert(t+5,'&');//插入第5个字符前
s.insert(t+14,'&');//插入第14个字符前
cout<<s<<endl;
cout<<s[0]<<endl;
cout<<s[0]-'1'<<endl;//两个相同的字符相减为零
t=s.begin();
s.erase(t+1);//删除1位置字符
cout<<s<<endl;
s.erase(t+1);
cout<<s<<endl;
s.erase(t+1,t+13); //删除1~13区间元素
cout<<s<<endl;
string s1;
s1=s;
cout<<s.length()<<endl;
s1=""; //清空字符串
cout<<s1.empty()<<endl;
s=s+"abcd";
s.replace(2,3,"555");//从第2个开始将连续的三个字符替换555
cout<<s<<endl;
cout<<s.find("555")<<endl;
cout<<s.find('a')<<endl;
cout<<s.find("good")<<endl;
cout<<s.find('o')<<endl;
cout<<s.compare("1234")<<endl;//比较,s大返回1;小返回-1;相同返回0;
reverse(s.begin(),s.end());//反向排序
cout<<s<<endl;
vector<string> v;//类似于字符串数组
v.push_back("jack");
v.push_back("Tom");
cout<<v[0]<<endl;
cout<<v[1]<<endl;
cout<<v[0][3]<<endl;
cout<<v[1][2]<<endl;
s="12345";
cout<<s<<endl;
int sum=0;
for(int i=0;i<s.length();i++)
{
sum+=s[i]-'0';
}
cout<<sum<<endl;
cin>>s;
reverse(s.begin(),s.end());
cout<<s<<endl;
printf(s.c_str());
cout<<endl;
return 0;
}