C++ vector string map 和 sort 、find 算法

vector

顺序容器 ,动态数组,访问数据速度快。

常见的操作函数如下

#include<algorithm>
#include<vector>
vector<int> num; num.push_back(1); auto it =num.begin();
while(it!=num.end()){
  cout<<*it<<endl;
  it++;
}
sort(num.begin(),num.end()); /*升序*/
sort(num.begin(),num.end(),cmp);/*降序*/
bool cmp(int a,int b){
  return a>b;
}
auot it =find(num.begin(),num.end(),1);
if(it==num.end()){
  cout<<"没找到"<<endl;
}else{
  cout<<"找到了"<<endl;
}

string  

string是C++标准库的一个重要的部分,主要用于字符串处理。可以使用输入输出流方式直接进行string操作,也可以通过文件等手段进行string操作。同时,C++的算法库对string类也有着很好的支持,并且string类还和c语言的字符串之间有着良好的接口。

#include<string>
string
str;
cin>>str;
for(int i=0;i<str.size();i++){
  cout<<str[i]<<endl;
}
size_t pos=str.find("a");
if(pos==string::npos){
  cout<<"没找到"<<end;
}
str.insert(4,"good");

size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_t n) const;
size_t find (char c, size_t pos = 0) const;

string to int :

 std::string str = "123";
 int n = atoi(str.c_str());
 cout<<n

int to string :

int num=45;

string str=to_string(num);

 

map

关联容器 ,平衡二叉树 

第一个可以称为关键字(key),每个关键字只能在map中出现一次;
第二个可能称为该关键字的值(value);

#include<map>
map<int,sting> man{{1,"aaa"},{2,"bbb"}};
man[0]=“aaaa";
man[1]="bbb“;
auto it=man.find(1);
if(it!=man.end()){
  it.erase();
  cout<<it->first<<it->second<<endl;
}
man.clear();

pair

pair的类型:pair是一种模版类型。每个pair 可以存储两个值。这两种值的类型没有限制,也可以将自己写的类放进去。经常和 map 配合使用。

pair 应用:如果一个函数有两个返回值的话,如果是相同类型,就可以用数组返回,如果是不同类型,两个属性的话,就可以用pair 进行操作,有多个属性的时候 ,可以使用tuple。

生成方法2种:

pair<int ,int >p (5,6);

pair<int ,int > p1= make_pair(5,6);

pair<string,double> p2 ("aa",5.0);

pair <string ,double> p3 = make_pair("aa",5.0);

posted @ 2021-12-25 20:37  joker_2255  阅读(102)  评论(0)    收藏  举报