I like books with excercises, but I also want solutions to see if I got it right. When working through The Boost C++ Libraries I only found solutions that I had to pay for, so here are my own solutions if you want to compare to yours. Please let me know if you thing I got it wrong or if you have a better solution.
Chapter 2: Smart Pointers
Excercise 1

#include <iostream>
#include <cstring>
#include <boost/shared_array.hpp>

boost::shared_array<char> get(const char *s)
{
int size = std::strlen(s);
boost::shared_array<char> text(new char[size + 1]);
std::strncpy(text.get(), s, size + 1);
return text;
}

void print(boost::shared_array<char> text)
{
std::cout << text.get() << std::endl;
}

int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << argv[0] << " <data>" << std::endl;
return 1;
}

boost::shared_array<char> text = get(argv[1]);
print(text);
}

Excercise 2

#include <vector>
#include <boost/ptr_container/ptr_vector.hpp>

template <typename T>
T *create()
{
return new T;
}

int main()
{
boost::ptr_vector<int> v;
v.push_back(create<int>());
}

Chapter 3: Function Objects
Excercise 1

#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/lambda/lambda.hpp>

int divide_by(int n, int div)
{
return n / div;
}

int main()
{
std::vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

std::transform(numbers.begin(), numbers.end(), numbers.begin(),
boost::bind(divide_by, _1, 2));

std::for_each (numbers.begin(), numbers.end(), std::cout << boost::lambda::_1 << "\n");
}

Excercise 2

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/lambda/lambda.hpp>

void save_size(std::vector<int> & sizes, const std::string & s)
{
sizes.push_back(s.size());
}

int main()
{
std::vector<std::string> strings;
strings.push_back("Boost");
strings.push_back("C++");
strings.push_back("Libraries");

std::vector<int> sizes;

std::for_each (strings.begin(), strings.end(), boost::bind(save_size, boost::ref(sizes), _1));

std::for_each (sizes.begin(), sizes.end(), std::cout << boost::lambda::_1 << "\n");
}

Excercise 3

#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <boost/bind.hpp>
#include <boost/function.hpp>

void apply_fn(boost::function<int(const char*)> f, const char * data)
{
std::cout << f(data) << std::endl;
}

int main()
{
std::vector< boost::function<int(const char*)> > processors;
processors.push_back(std::atoi);
processors.push_back(std::strlen);

const char data[] = "1.23";

std::for_each(processors.begin(), processors.end(), boost::bind(apply_fn, _1, data));
}

Chapter 4: Event Handling
Excercise 1

#include <boost/signals2.hpp>
#include <iostream>

class button
{
public:
boost::signals2::connection add_handler(boost::function<void ()> h) { return handler.connect(h); }
void remove_handler(boost::signals2::connection c) { c.disconnect(); }
void click() { handler(); }

protected:
boost::signals2::signal<void ()> handler;
};

void func1()
{
std::cout << "Hello" << std::endl;
}

void func2()
{
std::cout << ", world!" << std::endl;
}

int main()
{
button btn;
btn.add_handler(func1);
boost::signals2::connection handle = btn.add_handler(func2);
btn.click();
btn.remove_handler(handle);
btn.click();
}

Chapter 5: String Handling
Excercise 1

#include <iostream>
#include <fstream>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

int main()
{
std::ifstream ifs("sol.5.37.txt");
std::string xml;
while(ifs.good()) {
std::string line;
getline(ifs, line);
xml += line;
}

std::string first_name;
std::string last_name;
std::string dob_year;
std::string dob_month;
std::string dob_day;
float amount = 0.0;
std::string currency;

boost::smatch what;
boost::regex name_regex("<name>(.+)\\s+(\\w+)</name>");
if (boost::regex_search(xml, what, name_regex)) {
first_name = what[1];
last_name = what[2];
}
boost::regex dob_regex("<dob>(\\d+)\\-(\\d+)\\-(\\d+)</dob>");
if (boost::regex_search(xml, what, dob_regex)) {
dob_year = what[1];
dob_month = what[2];
dob_day = what[3];
}
boost::regex account_regex("<account>(.+)\\s+(\\w+)</account>");
if (boost::regex_search(xml, what, account_regex)) {
std::string a = what[1];
boost::algorithm::erase_all(a, ",");
amount = std::atof(a.c_str());
currency = what[2];
}
else std::cout << "no amount found in " << xml << std::endl;

std::cout << first_name << " " << last_name
<< " DOB: " << dob_day << "." << dob_month << "." << dob_year
<< " : " << floor(amount) << " " << currency << std::endl;
}

Data

<person>
<name>Karl-Heinz Huber</name>
<dob>1970-9-30</dob>
<account>2,900.64 USD</account>
</person>

Excercise 2

#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

int main()
{
std::ifstream ifs("sol.5.38.txt");
while(ifs.good()) {
std::string line;
getline(ifs, line);
std::vector<std::string> tok;
boost::algorithm::split(tok, line, boost::algorithm::is_space());
if (tok.size() == 5)
std::cout << boost::format("%-10s -> %-10s %4.2f EUR (%05s-%05s)") % tok[0] % tok[1] % tok[2] % tok[3] % tok[4] << std::endl;
}
}

Data

Munich Hamburg 92.12 8:25 9:45

Chapter 6: Multithreading
Excercise 1

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>
#include <iostream>
#include <boost/thread.hpp>

boost::mutex mutex;
boost::uint64_t sum = 0;

void partial_sum(int from, int to)
{
boost::uint64_t local_sum = 0;
for (int i = from; i < to; ++i)
local_sum += i;

mutex.lock();
sum += local_sum;
mutex.unlock();
}

int main()
{
boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();

boost::thread t1(partial_sum, 0, 1000000000/2);
boost::thread t2(partial_sum, 1000000000/2, 1000000000);
t1.join();
t2.join();

boost::posix_time::ptime end =
boost::posix_time::microsec_clock::local_time();
std::cout << end - start << std::endl;

std::cout << sum << std::endl;
}

Excercise 2

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/cstdint.hpp>
#include <iostream>
#include <vector>
#include <boost/thread.hpp>

boost::mutex mutex;
boost::uint64_t sum = 0;

void partial_sum(int from, int to)
{
boost::uint64_t local_sum = 0;
for (int i = from; i < to; ++i)
local_sum += i;

mutex.lock();
sum += local_sum;
mutex.unlock();
}

int main()
{
boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();

std::vector<boost::thread*> threads;

int num_threads = boost::thread::hardware_concurrency();

unsigned chunk = 1000000000 / num_threads;
for(int i=0; i < num_threads; ++i) {
boost::thread *t = new boost::thread(partial_sum, i*chunk, (i+1)*chunk);
threads.push_back(t);
}
for(unsigned i=0; i < threads.size(); ++i) {
threads[i]->join();
}

boost::posix_time::ptime end =
boost::posix_time::microsec_clock::local_time();
std::cout << end - start << std::endl;

std::cout << sum << std::endl;
}

Excercise 3

#include <iostream>
#include <boost/thread.hpp>

boost::mutex calc_mutex;
boost::mutex output_mutex;
int sum = 0;

void calculate()
{
calc_mutex.lock();
sum = 0;
for (int i = 0; i < 1000; ++i)
sum += i;
calc_mutex.unlock();
}

void print()
{
output_mutex.lock();
std::cout << sum << std::endl;
output_mutex.unlock();
}

void thread()
{
calculate();
print();
}

int main()
{
boost::thread t1(thread);
boost::thread t2(thread);
t1.join();
t2.join();
}

My solutions to the exercises in "The Boost C++ Libraries"的更多相关文章

  1. The Boost C++ Libraries

    " ...one of the most highly regarded and expertly designed C++ library projects in the world.&q ...

  2. [Z]The Boost C++ Libraries

    看起来是个学习boost非常不错的材料,应该是boost的官方教程之类: http://theboostcpplibraries.com/

  3. The Boost C++ Libraries中文教程

    http://zh.highscore.de/cpp/boost/

  4. 《The Boost C++ Libraries》 第一章 智能指针

    Boost.SmartPointers中提供了多种智能指针,它们采用在智能指针析构时释放内存的方式,帮助管理动态分配的对象.由于析构函数在智能指针生命周期结束时被执行,所以由它管理的动态分配对象可以保 ...

  5. boost 文件系统

    第 9 章 文件系统 目录 9.1 概述 9.2 路径 9.3 文件与目录 9.4 文件流 9.5 练习  该书采用 Creative Commons License 授权 9.1. 概述 库 Boo ...

  6. 新手,Visual Studio 2015 配置Boost库,如何编译和选择,遇到无法打开文件“libboost_thread-vc140-mt-gd-1_63.lib“的解决办法

    1,到官网下载最新的boost,www.boost.org 这里我下载的1-63版本. 2,安装,解压后运行bootstrap.bat文件.稍等一小会就OK. 3,编译boost库.注意一定要使用VS ...

  7. Ubuntu下安装boost

    今天开始安装配置Ubuntu开发环境(Ubuntu 12.04).在干活之前就预计到会遇到很多问题,但是没想到一开始就卡壳,可能是linux中各种包的依赖关系太复杂了,决定写个帖子记录一下,免得以后再 ...

  8. linux下编译安装boost库

    linux下编译安装boost库 linux下编译安装boost库 1.下载并解压boost 1.58 源代码 下载 解压 2.运行bootstrap.sh 3.使用b2进行构建 构建成功的提示 4. ...

  9. Using Boost Libraries in Windows Store and Phone Applications

    Using Boost Libraries in Windows Store and Phone Applications RATE THIS Steven Gates 18 Jul 2014 5:3 ...

随机推荐

  1. MySQL 10章_视图、事务

    一. 视图: 视图(view)是保存了查询语句的一种数据库对象,其数据来源是查询语句对应的数据表,他的结果与数据表查询的结果一样也是一张虚拟的数据表 . 为什么需要视图: ) 不同的用户关心的数据可能 ...

  2. 什么是哈希Hash(散列函数)

    Hash(散列函数) Hash,一般翻译做散列.杂凑,或音译为哈希,是把任意长度的输入(又叫做预映射pre-image)通过散列算法变换成固定长度的输出,该输出就是散列值.这种转换是一种压缩映射,也就 ...

  3. Java面试(1)

    一.Java基础 什么是字符串常量池? Java中的字符串常量池(String Pool)是存储在Java堆内存中的字符串池: String是java中比较特殊的类,我们可以使用new运算符创建Str ...

  4. JS对象 Date 日期对象 日期对象可以储存任意一个日期,并且可以精确到毫秒数(1/1000 秒)。 定义一个时间对象 : var Udate=new Date();Date()的首字母须大写

    Date 日期对象 日期对象可以储存任意一个日期,并且可以精确到毫秒数(1/1000 秒). 定义一个时间对象 : var Udate=new Date(); 注意:使用关键字new,Date()的首 ...

  5. 关于pip安装较慢的问题解决

    在 ~/.pip/ 下创建文件 pip.conf(如果还没有的话),并填入以下内容: [global] timeout = 6000 index-url = http://pypi.douban.co ...

  6. win10安装mysql__艰难的心路历程

    俺是新系统,嘿嘿嘿 首先,把下载好的压缩包解压到安装目录中,哪个盘可以. 第二,先创建my.ini文件,不然待会忘了.在文件中添加以下内容: [mysqld] port = basedir=C:\Wi ...

  7. 云-腾讯云-云点播:云点播(VOD)

    ylbtech-云-腾讯云-云点播:云点播(VOD) 提供端到端的一站式VpaaS音视频点播解决方案 1.返回顶部 1. 云点播(Video on Demand,VOD)基于腾讯多年技术积累与基础设施 ...

  8. vue-router 基本操作

    安装 vue-router 在命令行中进入 vue 的项目目录里,运行命令 npm install vue-router --save 来进行安装   npm install vue-router - ...

  9. css3@media实现原理

    window.matchMedia() 基本用法 window.matchMedia方法用来检查CSS的mediaQuery语句.各种浏览器的最新版本(包括IE 10+)都支持该方法,对于不支持该方法 ...

  10. (function($){….})(jQuery)与$(function(){})的区别

    function fun($){…};fun(jQuery);这种方法多用于存放开发的插件,执行其中的代码时,Dom对象并不一定加载完毕. $(function(){})等价于$(document). ...