天天看點

13 标準模闆庫STL【C++】

13 标準模闆庫STL

  • ​​13-​​
  • ​​判斷題​​
  • ​​單選題​​
  • ​​填空題​​
  • ​​程式填空題​​
  • ​​函數題​​
  • ​​7-1 .查找電話号碼​​
  • ​​7-2 姓名排序​​
  • ​​7-3 Score Processing​​
  • ​​13+​​
  • ​​程式設計題​​
  • ​​7-1 查找成績并折算後輸出​​
  • ​​7-2 電話号碼同步​​
  • ​​7-3 姓名排序​​
  • ​​STL測試​​

13-

判斷題

1-1 可以通過下标随機通路向量vector中的元素。T

1-2 當向量對象的記憶體用完之後,就會産生越界錯誤。F

單選題

2-1 若有下面的語句:

vector<int> v;
for (int i = 0; i < 4; i++)
    v.push_back(i + 1);
cout << v.size() << endl;      

執行後程式的輸出結果是 D

A. 1

B. 2

C. 3

D. 4

2-2 設有定義 vector< string > v(10);執行下列哪條語句時會調用構造函數? C

A. v[0] += “abc”;

B. v[0] = “2018”;

C. v.push_back(“ZUCC”);

D. cout << (v[1] == “def”);

2-3 .設有如下代碼段:

std::map<char *, int> m;
const int MAX_SIZE = 100;
int main() {
    char str[MAX_SIZE];
    for (int i = 0; i < 10; i++) {
        std::cin >> str;
        m[str] = i;
    }
    std::cout << m.size() << std::endl;
}      

讀入10個字元串,則輸出的 m.size() 為 B

A. 0

B. 1

C. 10

填空題

4-1(6分)

A container holds a sequence of objects.Containers can be categorized like this:

• Sequence containers provide access to (half-open) ​​

​sequence ​

​​ of elements.

• Associative containers provide ​​

​value​

​​ lookup based on a ​

​key​

​.

4-2(8分)

An iterator is akin to a ​​

​pointer​

​​ in that it provides operations for ​

​dereferencing​

​​access (e.g., ∗ for dereferencing) and for moving to point to a new element (e.g., ++ for moving to the ​

​next​

​ element). A sequence is defined by a pair of iterators defining a half-open range [begin:end):

13 标準模闆庫STL【C++】

That is, begin points to the ​

​first​

​ element of the sequence, and end points to the one-beyond-the-last element of the sequence. Never read from or write to ∗end. Note that the empty sequence has begin==end; that is, [p:p) is the empty sequence for any iterator p.

程式填空題

5-1.查找雇員資訊(關聯容器map)

閱讀程式并填空。

#include < iostream >

#include < cstdlib >

#include < map >

#include < string >

using namespace std;

class employee{

public:

employee(string name,string phoneNumber,string address){

this->name=name;

this->phoneNumber=phoneNumber;

this->address=address;

}

string name;

string phoneNumber;

string address;

};

int main()

{

map<int,employee*> employeeMap;

typedef pair<int,employee*>employeePair;

for(int employIndex=1001;employIndex<=1003;employIndex++){

char temp[10]; //臨時存儲單元

sprintf(temp,“%d”,employIndex);//将轉化為字元串存儲在temp中

string tmp( temp ); // 通過temp構造string對象

employee* p= new employee(2分)(“employee-”+tmp,“85523927-”+tmp, “address-”+tmp);

employeeMap.insert(2分)(employeePair(employIndex,p));//将員工編号和員工資訊插入到employeeMap對象中

}

int employeeNo=0;

cout<<“請輸入員工編号:”;

cin>>employeeNo; // 從标準輸入獲得員工号

map<int, employee*>(2分) ::iterator it;

it=employeeMap.find(employeeNo); // 根據員工編号查找員工資訊

if(it==employeeMap.end()(2分)){

cout<<“該員工編号不存在!”<<endl;

return -1;

}

cout<<“你所查詢的員工編号為:”<<it ->first<<endl;

cout<<“該員工姓名:”<<it ->second->name<<endl;

cout<<“該員工電話:”<<it -> second -> phonrNumber(2分)<<endl;

cout<<“該員工位址:”<<it ->second->address<<endl;

return 0;

}

5-2 檔案目錄樹

閱讀下列說明和C++代碼,将應填入 (n) 處的字句寫在答題紙的對應欄内。

【說明】現欲構造一檔案/目錄樹,采用組合(Composite)設計模式來設計,得到的類圖如下所示

13 标準模闆庫STL【C++】

【C++代碼】

#include

#include

#include

using namespace std;

class AbstractFile {

protected :

string name; // 檔案或目錄名稱

public:

void printName(){cout << name;} // 列印檔案或目錄名稱

virtual void addChild(AbstractFile *file)=0; // 給一個目錄增加子目錄或檔案

virtual void removeChild(AbstractFile file)=0;// 删除一個目錄的子目錄或檔案

virtual list<AbstractFile> *getChildren()=0;// 獲得一個目錄的子目錄或檔案

};

class File : public AbstractFile {

public :

File(string name) {

this->name = name; }

void addChild(AbstractFile *file) { return ; }

void removeChild(AbstractFile *file) { return ; }

函數題

7-1 .查找電話号碼

7-1 .查找電話号碼
檔案phonebook1.txt中有若幹聯系人的姓名和電話号碼。
高富帥 13312342222
白富美 13412343333
孫悟空 13512345555
唐三藏 13612346666
豬悟能 13712347777
沙悟淨 13812348888
請你編寫一個簡單的通信錄程式,當從鍵盤輸入一個姓名時查找到對應的電話号碼并輸出。如果沒找到則顯示Not found.
由于目前的自動裁判系統暫時不能支援使用者讀入檔案,我們編寫程式從鍵盤輸入檔案中的姓名和電話号碼,當輸入的名字為noname時,表示結束。noname後面有一個名字,需要查找其對應的電話号碼。
輸入格式:
高富帥 13312342222
白富美 13412343333
孫悟空 13512345555
唐三藏 13612346666
豬悟能 13712347777
沙悟淨 13812348888
noname (表示結束)
唐三藏 (需要查找此人的電話号碼)
輸出格式:
13612346666 (輸出對應的電話号碼)
輸入樣例:
白富美 13412343333
孫悟空 13512345555
唐三藏 13612346666
豬悟能 13712347777
沙悟淨 13812348888
noname
白骨精

輸出樣例:
Not found.      
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
int main() {
    map<string, string> m;
    string a;
    string b;
    while(1) {
        cin >> a;
        if (a == "noname")
            break;
        cin >> b;
            m.insert(pair<string, string>(a, b));
    }
    map<string, string> :: iterator p;
    string s;
    cin >> s;
    p = m.find(s);
    if (p != m.end())
        cout << p -> second << endl;
    else
        cout << "Not found." << endl;
    return 0;
}      

7-2 姓名排序

7-2 姓名排序
從指定文本檔案中讀入若幹學生姓名并按照拼音順序排序後輸出。
由于目前的OJ系統暫時不能支援使用者讀入檔案和寫檔案,我們編寫程式從鍵盤輸入檔案中的姓名,當輸入的單詞為end時,表示檔案結束。将按照姓名拼音順序排序後輸出。
輸入格式:
張三
李四
王五
馬六
陳七
孫悟空
end
輸出格式:
陳七 李四 馬六 孫悟空 王五 張三
輸入樣例:
白富美
孫悟空
唐三藏
豬悟能
沙悟淨
end

輸出樣例:      
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main() {
    string name;
    set<string> m;
    getline(cin, name);
    while (name != "end") {
        m.insert(name);
        getline(cin, name);
    }
    set<string> :: iterator p = m.begin();
    while (p != m.end())
        cout << *p++ << " ";
}      

7-3 Score Processing

7-3 Score Processing
Write a program to process students score data.

The input of your program has lines of text, in one of the two formats:

Student's name and student id, as <student id>, <name>, and
Score for one student of one course, as <student id>, <course name>, <marks>.
Example of the two formats are:

3190101234, Zhang San
3190101111, Linear Algebra, 89.5
Comma is used as the seperator of each field, and will never be in any of the fields. Notice that there are more than one word for name of the person and name of the course. To make your code easier, the score can be treated as double.

The number of the students and the number of the courses are not known at the beginning. The number of lines are not known at the beginning either. The lines of different format appear in no order. One student may not get enrolled in every course.

Your program should read every line in and print out a table of summary in .csv format.

The first line of the output is the table head, consists fields like this:

student id, name, <course name 1>, <course name 2>, ..., average
where the course names are all the courses read, in alphabet order. There should be one space after each comma.

Then each line of the output is data for one student, in the ascended order of their student id, with score of each course, like:

3190101234, Zhang San, 85.0, , 89.5, , , 87.3
For the course that hasn't been enrolled, leave a blank before the comma, and should not get included in the average. The average has one decimal place. There should be one space after each comma.

And the last line of the output is a summary line for average score of every course, like:

, , 76.2, 87.4, , , 76.8
All the number output, including the averages have one decimal place.

Input Format
As described in the text above.

Output Format
As described in the text above.
The standard output is generated by a program compiled by gcc, that the round of the first decimal place is in the "gcc way".

Sample Input
3180111435, Operating System, 34.5
3180111430, Linear Algebra, 80
3180111435, Jessie Zhao
3180111430, Zhiwen Yang
3180111430, Computer Architecture, 46.5
3180111434, Linear Algebra, 61.5
3180111434, Anna Teng
Sample Output
student id, name, Computer Architecture, Linear Algebra, Operating System, average
3180111430, Zhiwen Yang, 46.5, 80.0, , 63.2
3180111434, Anna Teng, , 61.5, , 61.5
3180111435, Jessie Zhao, , , 34.5, 34.5
, , 46.5, 70.8, 34.5, 50.6      
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstdlib>
#include<cstdio>
#include<string>
#include<vector>
#include<set>
#include<map>
using namespace std;
class student{
  public:
    string id, name;
    map<string, double> course;
    student() : id(""), name("") {
      course.clear();
    }
    void set1(string id_, string name_) {
      id = id_;
      name = name_;
    }
    void set2(string a, double b) {
      course[a] = b;
    }
    bool operator < (const student& tmp) const {
      return id < tmp.id;
    }
};
int main() {
  string in;
  set<string> s;
  vector<student> res;
  map<string, int> mp;
  while (getline(cin, in)) {
    int n = 0;
    for (int i = 0; i < in.size(); i++) {
      if (in[i] == ',') {
        n++;
      }
    }
    switch (n) {
      case 1: {
        int ad = -1;
        for (int i = 0; i < in.size(); i++) {
          if (in[i] == ',') {
            ad = i;
            break;
          }
        }
        string id, name;
        id = in.substr(0, ad);
        name = in.substr(ad+2);
        if (!mp.count(id)) {
          mp[id] = res.size();
          student tmp;
          tmp.set1(id, name);
          res.push_back(tmp);
        } else {
          ad = mp[id];
          res[ad].set1(id, name);
        }
        break;
      }
      case 2: {
        int ad1 = -1, ad2 = -1;
        for (int i = 0; i < in.size(); i++) {
          if (in[i] == ',') {
            if (ad1 == -1) {
              ad1 = i;
            } else {
              ad2 = i;
              break;
            }
          }
        }
        string id, course, grade;
        id = in.substr(0, ad1);
        course = in.substr(ad1+2, ad2-ad1-2);
        grade = in.substr(ad2+2);
        s.insert(course);
        if (!mp.count(id)) {
          mp[id] = res.size();
          student tmp;
          tmp.set2(course, atof(grade.c_str()));
          res.push_back(tmp);
        } else {
          int ad = mp[id];
          res[ad].set2(course, atof(grade.c_str()));
        }
        break;
      }
    }
  }
  cout << "student id, name";
  for (auto i: s) {
    cout << ", " << i;
  }
  cout << ", average" << endl;
  vector<double> sum(s.size(), 0), cnt(s.size(), 0);
  sort(res.begin(), res.end());
  int tot = 0;
  double ave = 0;
  for (int i = 0; i < res.size(); i++) {
    cout << res[i].id << ", "<< res[i].name;
    int ad = 0;
    tot = 0;
    ave = 0;
    for (auto j: s) {
      cout << ", ";
      if (res[i].course.count(j)) {
        cout << fixed << setprecision(1) << res[i].course[j];
        sum[ad] += res[i].course[j];
        cnt[ad]++;
        ave += res[i].course[j];
        tot++;
      }
      ad++;
    }
    cout << ", " << fixed << setprecision(1) << ave/tot << endl;
  }
  cout << ", ";
  tot = 0;
  ave = 0;
  for (int i = 0; i < sum.size(); i++) {
    tot++;
    ave += sum[i]/cnt[i];
    cout << ", " << fixed << setprecision(1) << sum[i]/cnt[i];
  }
  cout << ", " << fixed << setprecision(1) << ave/tot << endl;
  return 0;
}      

13+

程式設計題

7-1 查找成績并折算後輸出

7-1 查找成績并折算後輸出
檔案:期中考試成績.txt中有若幹學生的姓名和數學期中考試成績。
Smith 67
Anderson 75
Lewis 83
Cook 58
David 96
請你編寫一個簡單的查詢成績程式,當從鍵盤輸入一個姓名時查找到他的數學期中考試分數并按照21%折算後輸出。如果沒找到則顯示Not found.
由于目前的OJ系統暫時不能支援使用者讀入檔案,我們編寫程式從鍵盤輸入檔案中的姓名和成績,當輸入的名字為noname時,表示結束。noname後面有一個名字,需要查找其成績。

輸入格式:
Smith 67

Anderson 75

Lewis 83

Cook 58

David 96

noname (表示結束)

Bill

輸出格式:
Not found.

輸入樣例:
Smith  67
Anderson  75
Lewis  83
Cook  58
David  96
noname
Lewis
輸出樣例:
17.43      
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() 
{
    map<string, int> m;
    string a;
    int b;
    while(1) 
    {
        cin >> a;
        if (a == "noname")
            break;
        cin >> b;
        m.insert(pair<string, int>(a, b));
    }
    string s;
    cin >> s;
    map<string, int> :: iterator p = m.begin();
    p = m.find(s);
    if (p != m.end())
        cout << (p -> second) * 0.21 << endl;
    else
        cout << "Not found." << endl;
    return 0;
}      

7-2 電話号碼同步

7-2 電話号碼同步
檔案phonebook1.txt和phonebook2.txt中有若幹聯系人的姓名和電話号碼。請你設計一個程式,将這兩個檔案中的電話号碼同步。(所謂同步,就是将兩個檔案中的電話号碼合并後剔除相同的人名和電話号碼。請将同步後的電話号碼按照姓名拼音順序排序後儲存到檔案phonebook3.txt中。)

由于目前的OJ系統暫時不能支援使用者讀入檔案和寫檔案,我們編寫程式從鍵盤輸入檔案中的姓名和電話号碼,當輸入的單詞為end時,表示檔案結束。将同步後的電話号碼按照姓名拼音順序排序後輸出。

輸入格式:
張三 13012345678

李四 13112340000

王五 13212341111

馬六 13312342222

陳七 13412343333

孫悟空 13512345555

end (表示檔案phonebook1.txt結束)
張三 13012345678

孫悟空 13512345555

王五 13212341111

陳七 13412343333

唐三藏 13612346666

豬悟能 13712347777

沙悟淨 13812348888

end (表示檔案phonebook2.txt結束)

輸出格式:
陳七 13412343333

李四 13112340000

馬六 13312342222

沙悟淨 13812348888

孫悟空 13512345555

唐三藏 13612346666

王五 13212341111

張三 13012345678

豬悟能 13712347777

輸入樣例:
Zhang3 13012345678
Li4 13112340000
Wang5 13212341111
Ma6 13312342222
Chen7 13412343333
SunWuKong 13512345555
end
Zhang3 13012345678
SunWuKong 13512345555
Wang5 13212341111
Chen7 13412343333
TangSanZang 13612346666
ZhuWuneng 13712347777
ShaWuJing 13812348888
end
輸出樣例:
Chen7 13412343333
Li4 13112340000
Ma6 13312342222
ShaWuJing 13812348888
SunWuKong 13512345555
TangSanZang 13612346666
Wang5 13212341111
Zhang3 13012345678
ZhuWuneng 13712347777      
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
    set<string> s;
    string s1;
     for(int i=0;i<2;i++)
    {
        getline(cin,s1);
        while(s1!="end")
        {
            s.insert(s1);
            getline(cin,s1);
        }
    }    
    
    set<string>::iterator iter;
    for (iter = s.begin(); iter != s.end(); ++iter) 
        cout << *iter << endl;

    return 0;
}      

7-3 姓名排序

7-3 姓名排序
從指定文本檔案中讀入若幹學生姓名并按照拼音順序排序後輸出。
由于目前的OJ系統暫時不能支援使用者讀入檔案和寫檔案,我們編寫程式從鍵盤輸入檔案中的姓名,當輸入的單詞為end時,表示檔案結束。将按照姓名拼音順序排序後輸出。

輸入格式:
張三
李四
王五
馬六
陳七
孫悟空
end

輸出格式:
陳七 李四 馬六 孫悟空 王五 張三

輸入樣例:
白富美
孫悟空
唐三藏
豬悟能
沙悟淨
end
輸出樣例:      
#include <iostream>
#include <set>
#include <string>
using namespace std;

int main() {
    set<string> s;
    string s1;
     for(int i=0;i<2;i++)
    {
        getline(cin,s1);
        while(s1!="end")
        {
            s.insert(s1);
            getline(cin,s1);
        }
    }    
    
    set<string>::iterator iter;
    for (iter = s.begin(); iter != s.end(); ++iter) 
        cout << *iter<<" ";

    return 0;
}      

STL測試

#include <iostream>
#include <vector>
#include <set>
#include <map>
using namespace std;


void testVector(){
    vector<int> v;
    for(int i=0;i<5;i++){
        v.push_back(i);
    }
    for(int i=0;i<5;i++){
        cout<<v[i]<<" ";//i
    }
    cout<<"\n";
}

void testSet(){
    set<int> s;
    for(int i=0;i<5;i++){
        s.insert(i);
    }
    set<int>:: iterator item;
    item=s.begin();
//  while(item!=s.end()){
//      cout<<*item<<" ";//i
//      item++;
//  }
    for(item=s.begin();item!=s.end();item++) cout<<(*item)<<" ";//i
    cout<<"\n";
}

void testMap(){
    map<int,int> m;
    for(int i=0;i<5;i++){
        m.insert(pair<int,int>(i,i));
    }
    for(int i=0;i<5;i++){
//      cout<<m[i]<<" ";//i
        cout<<m.at(i)<<" ";//i
    }
    cout<<"\n";
}

int main(){
    void (*test)();         //一個函數指針
    void(*funs[])() =    //一個函數指針數組 
    {
        testVector,
        testSet,
        testMap 
    };

    for(int i=0;i<3;i++){
        test=funs[i];    
        test();
    } 

}