美文网首页算法和数据结构
机试常用算法和题型-容器函数使用专题

机试常用算法和题型-容器函数使用专题

作者: DecadeHeart | 来源:发表于2020-04-25 16:04 被阅读0次

    string.h库函数memset()置零

    char *strcpy(char *dest, const char *src)
    #include <stdio.h>
    #include <string.h>
     
    int main()
    {
       char src[40];
       char dest[100];
      
       memset(dest, '\0', sizeof(dest));
       strcpy(src, "This is runoob.com");
       strcpy(dest, src);
     
       printf("最终的目标字符串: %s\n", dest);
       
       return(0);
    }
    
    char *strcat(char *dest, const char *src)
       char src[50], dest[50];
     
       strcpy(src,  "This is source");
       strcpy(dest, "This is destination");
     
       strcat(dest, src);
     
       printf("最终的目标字符串: |%s|", dest);
       
       return(0);
    
    int strcmp(const char *str1, const char *str2)
         char str1[15];
       char str2[15];
       int ret;
     
     
       strcpy(str1, "abcdef");
       strcpy(str2, "ABCDEF");
     
       ret = strcmp(str1, str2);
     
       if(ret < 0)
       {
          printf("str1 小于 str2");
       }
       else if(ret > 0) 
       {
          printf("str2 小于 str1");
       }
       else 
       {
          printf("str1 等于 str2");
       }
    

    reverse()逆置函数algorithm头文件

    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    int main()
    {
        vector<int> s;
        int x;
        for(int i=0;i<10;i++){
            cin>>x;
            s.push_back(x);
        }
        reverse(s.begin(),s.end());
    
        for(int i=0;i<10;i++){
         cout <<s[i] << endl;
        }
    
        return 0;
    }
    // reverse algorithm example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::reverse
    #include <vector>       // std::vector
    
    int main () {
      std::vector<int> myvector;
    
      // set some values:
      for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9
    
      std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1
    
      // print out content:
      std::cout << "myvector contains:";
      for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '\n';
    
      return 0;
    }
    

    strrev逆置字符数组

    #include<stdio.h>
    #include<string.h>
     
    int main()
    {
         char s[]="hello";
         strrev(s);
         puts(s);
     
         return 0;
    }
    

    排序sort函数

    #include <algorithm>
    #include <vector>
    
    struct Node{
      int x;
      int y;
      //或在此处使用重载
      bool operator < (const Node &A) const{
        if(x=A.x) return x<A.x;
        else return y<A.y;
      }
    };
    
    bool com(Node &a,Node &b){
      if(a.x!=b.x) return a.x<b.x;
      else return a.y<b.y;
    }
    
    int main(){
      vector<Node> vec;
      //sort在vector容器中用法,在数组当中是sort(ans.ans+n);
      sort(vec.begin(),vec.end(),com);
      return 0;
    }
    
    //sort的其他写法,直接构造函数
    sort(raw.begin(),raw.end(),[](const string &a,const string &b)->bool{return (a+b < b+a);});
    

    stable_sort()稳定排序

    //学生成绩排序
    #include<bits/stdc++.h>
    using namespace std;
    int n, bs, score[500], r[500];
    bool cmp(int i,int j){
        return score[i]<score[j];
    }
    bool cmp1(int i,int j){
        return score[i]>score[j];
    }
    int main() {
        string name[500];
        int i,j,k;
      while(cin >>n>>bs){
        for(i=0;i<n;i++){
            r[i]=i;
            cin >>name[i]>>score[i];
        }
        if(bs==1)
            stable_sort(r,r+n,cmp);
        else
            stable_sort(r,r+n,cmp1);
        for(i=0;i<n;i++){
            int t = r[i];
            cout << name[t]<<' '<<score[t]<<endl;
        }
      }
    return 0;
    }
    

    algorithm头文件next_permulation函数(全排列)

    // next_permutation example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::next_permutation, std::sort
    
    int main () {
      int myints[] = {1,2,3};
    
      std::sort (myints,myints+3);
    
      std::cout << "The 3! possible permutations with 3 elements:\n";
      do {
        std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
      } while ( std::next_permutation(myints,myints+3) );
    
      std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
    
      return 0;
    }
    output:
    The 3! possible permutations with 3 elements:
    1 2 3
    1 3 2
    2 1 3
    2 3 1
    3 1 2
    3 2 1
    After loop: 1 2 3
      
     int main()
    {
        string temp;
        while(cin>>temp)
        {
            do{
                cout<<temp<<endl;
            }while(next_permutation(temp.begin(),temp.end()));
            cout<<endl; 
        }
        return 0;
    }
    样例输入 
    xyz
    
    样例输出 
    xyz 
    xzy 
    yxz 
    yzx 
    zxy 
    zyx
    

    vector容器insert函数

    #include <iostream>
    #include <string>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        string str;
        int n;
        while(cin>>n){
            vector<string> nameArr;
            for(int i=0;i<n;i++){
                string name;
                cin>>name;
              //头部插入,倒序输出
                nameArr.insert(nameArr.begin(),name);
                if(i<3){
                    for(int j=0;j<nameArr.size();j++){
                        cout<<j+1<<"="<<nameArr[j]<<" ";
                    }
                }else{
                    for(int j=0;j<4;j++){
                        cout<<j+1<<"="<<nameArr[j]<<" ";
                    }
                }
                cout<<endl;
            }
        }
        return 0;
    }
    
    

    vector容器pop_back(),erase()方法删除元素

    ---- 向量容器vector的成员函数pop_back()可以删除最后一个元素.
    
    ---- 而函数erase()可以删除由一个iterator指出的元素,也可以删除一个指定范围的元素。
    
    ---- 还可以采用通用算法remove()来删除vector容器中的元素.
    
    ---- 不同的是:采用remove一般情况下不会改变容器的大小,而pop_back()与erase()等成员函数会改变容器的大小。
    1、pop_back()
    
    void pop_back();
    Delete last element
    Removes the last element in the vector, effectively reducing the container size by one.
    2、erase()
    C++11
    iterator erase (const_iterator position);
    iterator erase (const_iterator first, const_iterator last);
    删除指定位置的一个元素或删除指定范围内的元素
    #include <iostream>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> vec;
        for(int i=0;i<10;i++)
        {
            vec.push_back(i);
        }
        vec.erase(vec.begin()+5);//erase the 6th element
        vec.erase(vec.begin(),vec.begin()+3);
        for(int i=0;i<vec.size();i++)
        {
            cout<<vec[i]<<' ';
        }
        cout<<endl;
        system("pause");
        return 0;
    }
    

    string容器实用函数

    #include <iostream>
    #include <string>
    #include <iterator>
    using namespace std;
    
    int main(){
      string a="xxxyyy";
      string b="zzz";
      //substr要好好研究下
      string s2=a.substr(startpos,n);//取子串
      string::size_type n=a.find("yy");
      a.find("yyx"); //返回string::npos
      string s3=a.replace(0,3,"fff"); //替换fffyyy
      string::iterator p=a.insert(a.begin(),'_');
      a.insert(a.find('y'),"_str_"); //在第一个找到"y"的下标前面插入一个指定字符
      //begin用法
      // sorts vec in "normal" order  
    sort(vec.begin(), vec.end());  
    // sorts in reverse: puts smallest element at the end of vec  
    sort(vec.rbegin(), vec.rend()); 
    }
    
     string c;
     while(1){
      cin>>c;
      if(*(c.end()-1)== '*'){  //c.end() ;是一个迭代器,是个指针,前面加个* 就0k
       break;
      }
    }
    

    string::substr方法总结

    // string::substr
    string substr (size_t pos = 0, size_t len = npos) const;
    pos:要作为子字符串复制的第一个字符的位置。如果等于字符串长度,则函数返回空字符串。如果它大于字符串长度,则抛出范围。注意:第一个字符用0(不是1)表示。
     len:要包含在子字符串中的字符数(如果字符串较短,则使用尽可能多的字符)。字符串::npos的值表示字符串结束之前的所有字符。
      
    #include <iostream>
    #include <string>
    
    int main ()
    {
      std::string str="We think in generalities, but we live in details.";
                                               // (quoting Alfred N. Whitehead)
    
      std::string str2 = str.substr (3,5);     // "think"
    
      std::size_t pos = str.find("live");      // position of "live" in str
    
      std::string str3 = str.substr (pos);     // get from "live" to the end
    
      std::cout << str2 << ' ' << str3 << '\n';
    
      return 0;
    }
    

    erase删除方法总结

        string str = "hello c++! +++";
        // 从位置pos=10处开始删除,直到结尾
        // 即: " +++"
        str.erase(10);
        cout << '-' << str << '-' << endl;
        // 从位置pos=6处开始,删除4个字符
        // 即: "c++!"
        str.erase(6, 4);
        cout << '-' << str << '-' << endl;
    
    //删除迭代器[first, last)区间的所有字符,返回一个指向被删除的最后一个元素的下一个字符的迭代器.
    
        string str = "hello c++! +++";
        // 删除"+++"前的一个空格
        str.erase(str.begin()+10);
        cout << '-' << str << '-' << endl;
        // 删除"+++"
        str.erase(str.begin() + 10, str.end());
        cout << '-' << str << '-' << endl;
    
    
    

    find方法总结

    string (1)  
    size_t find (const string& str, size_t pos = 0) const;
    c-string (2)    
    size_t find (const char* s, size_t pos = 0) const;
    buffer (3)  
    size_t find (const char* s, size_t pos, size_t n) const;
    character (4)   
    size_t find (char c, size_t pos = 0) const;
    
    str
    Another string with the subject to search for.
    pos
    Position of the first character in the string to be considered in the search.
    If this is greater than the string length, the function never finds matches.
    Note: The first character is denoted by a value of 0 (not 1): A value of 0 means that the entire string is searched.
    s
    Pointer to an array of characters.
    If argument n is specified (3), the sequence to match are the first n characters in the array.
    Otherwise (2), a null-terminated sequence is expected: the length of the sequence to match is determined by the first occurrence of a null character.
    n
    Length of sequence of characters to match.
    c
    Individual character to be searched for.
      
    // string::find
    #include <iostream>       // std::cout
    #include <string>         // std::string
    
    int main ()
    {
      std::string str ("There are two needles in this haystack with needles.");
      std::string str2 ("needle");
    
      // different member versions of find in the same order as above:
      std::size_t found = str.find(str2);
      if (found!=std::string::npos)
        std::cout << "first 'needle' found at: " << found << '\n';
    
      found=str.find("needles are small",found+1,6);
      if (found!=std::string::npos)
        std::cout << "second 'needle' found at: " << found << '\n';
    
      found=str.find("haystack");
      if (found!=std::string::npos)
        std::cout << "'haystack' also found at: " << found << '\n';
    
      found=str.find('.');
      if (found!=std::string::npos)
        std::cout << "Period found at: " << found << '\n';
    
      // let's replace the first needle:
      str.replace(str.find(str2),str2.length(),"preposition");
      std::cout << str << '\n';
    
      return 0;
    }
    
    first 'needle' found at: 14
    second 'needle' found at: 44
    'haystack' also found at: 30
    Period found at: 51
    There are two prepositions in this haystack with needles.
    

    find和erase联合使用实例

    #include <iostream>
    #include <string>
    #include <ctype.h>
    using namespace std;
    
    int main()
    {
        string key;
        char key2=' ';
        getline(cin,key);
        for(int i=0;i<key.size();i++) key[i]=toupper(key[i]);
        string str;
        while(getline(cin,str)){
            string str2=str;
            for(int i=0;i<str.size();i++) str[i]=toupper(str[i]);
            while(str.find(key)!=string::npos){
            size_t pos=str.find(key);
              //用一个找位置,不输出,但也得同步删除
            str.erase(pos,key.size());
            str2.erase(pos,key.size());
            }
            while(str2.find(key2)!=string::npos){
            size_t pos=str2.find(key2);
            str2.erase(pos,1);
            }
            cout<<str2<<endl;
        }
        return 0;
    }
    

    replace使用方法

    用法一:用str替换指定字符串从起始位置pos开始长度为len的字符 
    string& replace (size_t pos, size_t len, const string& str); 
    用法二: 用str替换 迭代器起始位置 和 结束位置 的字符 
     string& replace (const_iterator i1, const_iterator i2, const string& str);
    用法三: 用substr的指定子串(给定起始位置和长度)替换从指定位置上的字符串 
      string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
    
    

    string函数应用实例,小数指数转换

    4 00.00120 000.012345
    //stl应用,给出两个数,保留N位小数科学计数法之后是否相等,要给出转换结果
    /*
    考虑数据本身,可以按整数部分是否为两种情况讨论
    0.a1a2a3...
    从小数点后第一个非零数字开始的三位,指数则是,小数点与非零位之间0的个数的相反数
    b1b2..bm,a1a2a2...
    首先判断是哪一类数据
    在根据本体部分和指数是否都相等,判断是凑是相等的
    */
    
    #include <iostream>
    #include <string>
    using namespace std;
    int n;
    //引用也要学会使用!!,这样可以返回修改多个东西
    string dipose(string str,int &num){
    
        while(str[0]=='0') {
            //忘记一个重要的东西!!,i可以自增!!
            str.erase(0,1);
            //str.erase(str.begin())//去掉前导!!
        }
    
        if(str[0]=='.'){
            str.erase(0,1);
            //终于理顺了这个逻辑,不能用循环1!,因为每次删除的是前面
            while(str[0]=='0'){
                str.erase(0,1);
                num++;
            }
            num=-num;
        }else{
            if(str.find('.')!=string::npos){
                int pos=str.find('.');
                num=pos;
                str.erase(pos,1);
            }
            else{
                num=str.size();
            }
        }
            if(str.size()==0) num=0;
            if(str.size()<n){
            for(int i=str.size();i<n;i++)
                str=str+'0';
            }else{
                str=str.substr(0,n);
            }
        return str;
    }
    
    int main()
    {
        string str1,str2;
    
        while(cin>>n>>str1>>str2){
            int n1=0,m2=0;
            str1=dipose(str1,n1);
            str2=dipose(str2,m2);
            cout <<str1<<" "<<n1<< endl;
            cout <<str2<<" "<<m2<<  endl;
            if(n1==m2&&str1==str2){
                    cout<<"YES"<<" 0."<<str1<<"*10^"<<n1<<endl;
            }else{
                    cout<<"NO"<<" 0."<<str1<<"*10^"<<n1<<" 0."<<str2<<"*10^"<<m2<<endl;
            }
        }
    
        return 0;
    }
    
    

    reverse()函数使用方法

    #include <iostream>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        string str;
    
        while(getline(cin,str)){
            reverse(str.begin(),str.end());
            cout<<str<<endl;
        }
        return 0;
    }
    //基础逆置方法
        while(gets(str))
        {
            int len=strlen(str);
            for(int i=0;i<len/2;++i)
            {
                char temp=str[i];
                str[i]=str[len-1-i];
                str[len-1-i]=temp;
            }
            printf("%s\n",str);
        }
    
    

    swap函数使用

    C++中的swap函数:交换函数
    
    好处:不用担心交换变量精度的缺失,无需构造临时变量,不会增加空间复杂度
    
    swap 包含在命名空间std 里面
    
    swap(a,b);
    
    swap(a[i] = b[j]);
    
    leetcode的一个反转字符串举例:
    //leetcode 反转字符串
    //编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
    //不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
    //你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
     
    class Solution {
    public:
        void reverseString(vector<char>& s) {
            for(int i = 0, j = s.size() - 1; i < j; i++, j--)
                swap(s[i] = s[j]);
        }
        return;
    };
    

    set容器使用

    #include <set>
    using namespace std;
    
    int main(){
        set<int> s;
        for(int i=0;i<5;i++){
          s.insert(i*i);
        }
        s.find(4); //查找返回迭代器,找不到返回end()
        s.erase(4);
        return 0;
    }
    

    map容器使用

    #include <iostream>
    #include <map>
    #include <iterator>
    using namespace std;
    
    int main(){
      map<char,int> mp;
      mp['c']=1;
      mp['b']=2;
      mp['a']=3;
      map<char,int>::iterator p=mp.begin(); //使用迭代器遍历
      for(;p!=mp.end();++p){
      //输出顺序是a,b,c,map使用红黑树实现,自动排序的
        cout<<p->first<<" "<<p->second<<endl;
      }
      cout<<mp['b']<<endl;
      //使用下标访问,输出2
      map<char,int>::iterator it=mp.find('b');
      //it指向<'b',1>
      cout<<it->second<<endl;
      mp.erase(it);
      mp.erase('a');
      cout<<mp.size()<<endl;
      return 0;
    }
    
    //map使用方式
    int main()
    {
    
        int n;
        map<char,int> mp1;
        mp1['C']=0;
        mp1['J']=0;
        mp1['B']=0;
        map<char,int> mp2;
        mp2['C']=0;
        mp2['J']=0;
        mp2['B']=0;
        int A[3]={0},B[3]={0};
        while(cin>>n){
            char c1,c2;
            for(int i=0;i<n;i++){
                cin>>c1>>c2;
                if(c1==c2){
                    A[1]++;
                    B[1]++;
                }else if((c1=='C'&&c2=='J')||(c1=='J'&&c2=='B')||(c1=='B'&&c2=='C')){
                    A[0]++;
                    B[2]++;
                    mp1[c1]++;
                }else if((c2=='C'&&c1=='J')||(c2=='J'&&c1=='B')||(c2=='B'&&c1=='C')){
                    A[2]++;
                    B[0]++;
                    mp2[c2]++;
                }
            }
            for(int i=0;i<3;i++){
                cout<<A[i]<<" ";
            }
            cout<<endl;
            for(int i=0;i<3;i++){
                cout<<B[i]<<" ";
            }
            cout<<endl;
            map<char,int>::iterator p1=mp1.begin();
            map<char,int>::iterator p2=mp2.begin();
            cout<<p1->first<<" "<<p2->first;
        }
        return 0;
    }
    
    

    map使用实例,借用key的自动排序功能:

    #include <iostream>
    #include <bits/stdc++.h>
    using namespace std;
    
    int main()
    {
        int n;
        while(cin>>n){
            map<int,string> mp1;
            for(int i=0;i<n;i++){
                int key;
                string color;
                cin>>key>>color;
                //可以这样赋值,确实是按照key自动增序排列的
                //mp1[key]=color;
                mp1.insert(pair<int,string>(key,color));
            }
    
            /*for(auto it=mp1.begin();it!=mp1.end();it++){
                cout<<it->second<<endl;
            } 正向遍历 */
    
            for(map<int,string>::reverse_iterator rit=mp1.rbegin();rit!=mp1.rend();rit++){
                //cout<<rit->second<<endl;
                cout<<(*rit).second<<endl;
            }
        }
    
        return 0;
    }
    
    

    unorder_map容器使用(hash树)

    #include <cstdio>
    #include <unordered_map>
    using namespace std;
    int main()
    {
        int n,m,temp;
        while(~scanf("%d",&n))
        {
            unordered_map<int,bool> mp;
          /*
    bool型      default 是 false;
    bool 是基本型别,同 int;
    BOOL 是个类,同INTEGER,可以调相应的方法.
          */
            for(int i=0;i<n;i++)
            {
                scanf("%d",&temp);
                mp[temp]=true;
            }
            scanf("%d",&m);
            for(int i=0;i<m;i++)
            {
                scanf("%d",&temp);
                if(mp[temp]==false)
                    printf("NO\n");
                else
                    printf("YES\n");
            }
        }
        return 0;
    }
    //unordered_map,运用出神入化!!学生id映射结构体student,用无序是为了使用hash,不让他乱排序
    #include <cstdio>
    #include <unordered_map>
    using namespace std;
    struct student
    {
        int id,age;
        char name[100],sex[100];
    }stu;
    int main()
    {
        int n,m,temp;
        scanf("%d",&m);
        for(int i=0;i<m;i++)
        {
            unordered_map<int,student> mp;
            scanf("%d",&n);
            for(int j=0;j<n;j++)
            {
                scanf("%d %s %s %d",&stu.id,stu.name,stu.sex,&stu.age);
                mp[stu.id]=stu;
            }
            scanf("%d",&temp);
            printf("%d %s %s %d\n",mp[temp].id,mp[temp].name,mp[temp].sex,mp[temp].age);
        }
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:机试常用算法和题型-容器函数使用专题

        本文链接:https://www.haomeiwen.com/subject/bnjkwhtx.html