您的位置:首页 > 编程语言 > C语言/C++

C++primer学习:标准库特殊设施:tuple

2015-12-09 15:10 423 查看

(1):tuple的定义;tuple模板可以视为一种快速随意的数据结构.

例子1:定义几个tuple;

tuple<int,int,int> a(10,20,30);
tuple<string, vector<string>, pair<string, int>> s;


例子2:编写一个findbook函数和reportresult函数,可以在许多书店的销售记录中查找到指定的书籍记录.并保存每一个存有指定书籍的书店的信息;

#include "sales.h"
#include "iostream"
#include "algorithm"
#include "vector"
#include "numeric"
#include "tuple"
using namespace std;
/*******matches中保存有三个元素,第一个为索引号,第二个,第三个分别是该书籍在相应书店里销售文件中的位置***********************/
typedef tuple<size_t, vector<Sales_data>::const_iterator, vector<Sales_data>::const_iterator> matches;

/**************查找相应书籍,返回一个保存许多matches的vector**********************************/
vector<matches> findbook(const vector<vector<Sales_data>>& files, const string&book)
{
vector<matches> ret;
size_t count = 0;
for (const auto& trans : files)//遍历所有销售记录
{
++count;
auto found = equal_range(trans.begin(), trans.end(), book, compareIsbn);//获取改书籍的位置
if (found.first != found.second)//该书籍在trans中
ret.push_back(matches(count, found.first, found.second));//保存记录
}
return ret;
}
/***********用来显示所有记录了指定书籍的书店的所有销售记录*********************************/
void report_result(istream&in,ostream&os,const vector<vector<Sales_data>>& files)
{
string book;
while (in>>book)//输入查询书籍名称
{
auto ret = findbook(files, book);
if (ret.empty())//没有结果
{
os << " nodata\n";
continue;//直接进行下一次查询
}
/*********存在销售记录**************/
for (const auto &trans : ret)
os << "index : " <<"total revenues "<< get<0>(trans) << accumulate(get<1>(trans), get<2>(trans), Sales_data(book));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: