首页 > 代码库 > 使用tuple返回多个值

使用tuple返回多个值

17.4编写并测试findbook函数

#include<iostream>#include<vector>#include<string>#include<tuple>#include<algorithm>#include"Sales_data.h"using namespace std;typedef tuple<vector<Sales_data>::size_type,vector<Sales_data>::const_iterator,vector<Sales_data>::const_iterator> matches;vector<matches> findbook(const vector<vector<Sales_data>> &files,const string &book){    vector<matches> ret;    for(auto it=files.begin();it!=files.end();++it)    {        auto found=equal_range(it->begin(),it->end(),book,compareIsbn);        if(found.first!=found.second)            ret.push_back(make_tuple(it-files.begin(),found.first,found.second));    }    return ret;}void reportResult(istream &in,ostream &os,const vector<vector<Sales_data>> &files){    string s;    while(in>>s)    {        auto trans=findbook(files,s);        if(trans.empty())        {            cout<<s<<" not found in any stores "<<endl;            continue;        }        for(const auto &store:trans)        {            os<<"stores "<<get<0>(store)<<" sales: "                <<accumulate(get<1>(store),get<2>(store),Sales_data(s))                <<endl;        }    }}int main(){}

17.5重写findbook,令其返回一个pair,包含一个索引和一个迭代器pair。

typedef pair<vector<Sales_data>::size_type,pair<vector<Sales_data>::const_iterator,vector<Sales_data>::const_iterator>> match;vector<match> findbook1(const vector<vector<Sales_data>> &files,const string &book){    vector<match> ret;    for(auto it=files.begin();it!=files.end();++it)    {        auto found=equal_range(it->begin(),it->end(),book,compareIsbn);        if(found.first!=found.second)            ret.push_back(make_pair(it-files.begin(),make_pair(found.first,found.second)));    }    return ret;}

 

使用tuple返回多个值