又被虐了,可恶的是它居然还出了几道java,jvm,web,xml的题。虽然心里面已经又准备,但心里无疑又增添了不少紧迫感。无论如何,一直总结才是前进的王道,加油呀!
先来回顾一道编程题,讲道理,这道编程题出得好烂啊,不知所云,也无法测试,而且返回什么也不说清楚。题目说,招行网络要去外面拿订单,有三个办公室,每个办公室有自己的权重:
JB01 1;
JB02 2;
JB03 1;
而且这些办公室拿一轮订单就结束了,剩下的订单可以先抛弃。要你写一个函数,实参一个订单的ID列表(我就姑且认为是顺序容器vector吧)和map的权重表,这个函数返回每个办公室的订单表。
#include <vector>
#include <iostream>
#include <string>
#include <map>
using namespace std;
void allocate(vector<string> ID, map<string,int> weight, map<string,vector<string>> &temp){
int i=0;
for(auto &w:weight){
vector<string> t;
while(w.second){
t.push_back(ID[i++]);
--w.second;
}
temp.insert(make_pair(w.first,t));
}
}
int main(){
map<string,int> weight{{"JB01",1},{"JB02",2},{"JB03",1}};
vector<string> ID{"11","22","33","44","55"};
string word;
map<string,vector<string>> temp;
allocate(ID,weight,temp);
cout<<"Please input your office:"<<endl;
cin>>word;
map<string,vector<string>>::iterator iter=temp.find(word);
if(iter!=temp.end())
{
vector<string>::iterator it = iter->second.begin();
while(it != iter->second.end())
{
cout<<(*it++)<<endl;
}
}
return 0;
}
这个题目涉及到了map嵌套vector的示例(我个人认为),关联容器有很多灵活的使用方法,先来回顾一下关联容器的insert成员:向容器中添加一个元素的四种方法
map<string,size_t> word_count;
word_count.insert({word,1});
word_count.insert(make_pair(word,1));
word_count.insert(pair<string,size_t>)(word,1));
word_count.insert(map<string,size_t>::value_type(word,1));
解法中,我直接使用了make_pair去insert成员。在这里,map嵌套vector的关键其实是要将主键和已经创建好的一组向量去make_pair,而不能直接去push_back(),我前期也犯了很大的错误。其次,我们要用迭代器作为指针,然后解指针获得map的值。