pair长大之后成为tuple。当函数想返回多个不同类型值的时候,一般有两种,定义一个结构体,把值写进去,返回结构体;也可以通过函数参数指针列表取值。函数参数太多不好看,临时定义一个结构体太浪费。tuple适合应用在这种情况下。实现复杂,用起来却很简单。这里用他来实现一个小功能:文件内容排序。
现在假定文件每一行有如下格式数据[张三 , 1989,6327 ] ,这个格式是三段数据,用逗号隔开,第一个字段是名字,字符串类型,其他都是整数,年龄和工号。当格式化的时候 tuple库的实现我感觉有一个bug,那就是碰到逗号不会停止解析,而是把整个字符串都解析了。所以我在逗号前面加个空格,解决这个bug。
#include "boost/tuple/tuple_io.hpp"
#include "boost/tuple/tuple_comparison.hpp"
#include <fstream>
#include <algorithm>
#include <string>
#include <sstream>
void sort_file( const char *pfilename )
{
std::locale::global( std::locale( "" ) );
using namespace boost;
using boost::tuples::set_close;
using boost::tuples::set_open;
using boost::tuples::set_delimiter;
typedef tuple<std::string, int, int> Tuple;
typedef std::vector<Tuple> Vector;
// 从文件读取数据并格式化到tuple
std::ifstream ifs( pfilename );
Vector vlist;
Tuple t;
// 格式设定,以[zhang,1,2]的形式读取。
// 默认是(zhang 1 2)的形式
ifs >> set_delimiter( ',' )
>> set_open( '[' )
>> set_close( ']' );
// 如果碰到格式不对或者读取完毕就返回false
while ( bool( ifs >> t ) )
{
vlist.push_back( t );
}
ifs.close();
// 按第二字段降序排序
sort( vlist.begin(), vlist.end(),
[]( const Tuple& lhv, const Tuple& rhv )
{
return get<1>( lhv ) > get<1>( rhv );
} );
// 输出到文件,可以自定义输出格式,这里原样输出
std::ofstream ofs( "E://2.txt" );
ofs << set_open( '[' )
<< set_close( ']' )
<< set_delimiter( ',' );
Vector::iterator itor = vlist.begin();
while ( itor != vlist.end() )
{
ofs << *itor++ << std::endl;
}
ofs.close();
setlocale( LC_ALL, "C" );
}
输入文件如下:
[张三 ,1990,31]
[李四 ,1978,234]
[王五 ,1987,2]
[陈六 ,2000,001]
[刘七 ,1966,6555]
[王八 ,1989,6327]
我按照年龄降序排列。输出到文件里。
输出:
[陈六,2000,1]
[张三,1990,31]
[王八,1989,6327]
[王五,1987,2]
[李四,1978,234]
[刘七,1966,6555]
整个过程还是很简单的。