Statistics
2
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-04-21

AuthorJacek Galowicz

Key Features • Learn the latest features of C++ and how to write better code by using the Standard Library (STL). Reduce the development time for your applications. • Understand the scope and power of STL features to deal with real-world problems. • Compose your own algorithms without forfeiting the simplicity and elegance of the STL way. Book Description C++ has come a long way and is in use in every area of the industry. Fast, efficient, and flexible, it is used to solve many problems. The upcoming version of C++ will see programmers change the way they code. If you want to grasp the practical usefulness of the C++17 STL in order to write smarter, fully portable code, then this book is for you. Beginning with new language features, this book will help you understand the language's mechanics and library features, and offers insight into how they work. Unlike other books, ours takes an implementation-specific, problem-solution approach that will help you quickly overcome hurdles. You will learn the core STL concepts, such as containers, algorithms, utility classes, lambda expressions, iterators, and more, while working on practical real-world recipes. These recipes will help you get the most from the STL and show you how to program in a better way. By the end of the book, you will be up to date with the latest C++17 features and save time and effort while solving tasks elegantly using the STL. What you will learn • Learn about the new core language features and the problems they were intended to solve • Understand the inner workings and requirements of iterators by implementing them • Explore algorithms, functional programming style, and lambda expressions • Leverage the rich, portable, fast, and well-tested set of well-designed algorithms provided in the STL • Work with strings the STL way instead of handcrafting C-style code • Understand standard support classes for concurrency and synchronization, and how to put them to work • Use the filesystem library addition

Tags
No tags
ISBN: 178712049X
Publisher: Packt Publishing
Publish Year: 2017
Language: 英文
Pages: 523
File Format: PDF
File Size: 9.1 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
C++17 STL Cookbook Over 90 recipes that leverage the powerful features of the standard library in C++17 Jacek Galowicz BIRMINGHAM - MUMBAI
C++17 STL Cookbook Copyright © 2017 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2017 Production reference: 1230617 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78712-049-5 www.packtpub.com
Credits Author Jacek Galowicz Copy Editor Muktikant Garimella Reviewer Arne Mertz Project Coordinator Ulhas Kambali Commissioning Editor Aaron Lazar Proofreader Safis Editing Acquisition Editor Nitin Dasan Indexer Francy Puthiry Content Development Editor Vikas Tiwari Graphics Abhinash Sahu Technical Editor Hussain Kanchwala Production Coordinator Shantanu Zagade  
About the Author Jacek Galowicz obtained his master of science in electrical engineering/computer engineering at RWTH Aachen University, Germany. While at university, he enjoyed working as a student assistant in teaching and research, and he participated in several scientific publications. During and after his studies, he worked as a freelancer and implemented applications as well as kernel drivers in C and C++, touching various areas, including 3D graphics programming, databases, network communication, and physics simulation. In recent years, he has been programming performance- and security-sensitive microkernel operating systems for Intel x86 virtualization at Intel and FireEye in Braunschweig, Germany. He has a strong passion for modern C++ implementations of low- level software, and he tries hard to combine high performance with an elegant coding style. Learning purely functional programming and Haskell in recent years triggered his drive to implement generic code with the aid of meta programming. Writing a book and founding a company at the same time was a great and interesting experience in my life and a lot of fun. The fun aspects, however, were only possible because of the support and patience of my wonderful girlfriend Viktoria, my fellow co-founders, and all my friends. Special thanks go to Arne Mertz for his invaluable and meticulous review suggestions, as well as Torsten Robitzki and Oliver Bruns from the C++ user group Hannover for their great feedback.
About the Reviewer Arne Mertz is a C++ expert with over a decade of experience. He studied physics at the university of Hamburg, and he switched careers to become a software developer. His main background is in financial enterprise applications written in C++. Arne works at Zühlke Engineering, Germany and is known for his blog, Simplify C++! (h t t p s ://a r n e - m e r t z . d e ) on clean and maintainable C++.
www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. h t t p s ://w w w . p a c k t p u b . c o m /m a p t Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
Customer Feedback Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at h t t p s ://w w w . a m a z o n . c o m /d p /178712049X . If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Table of Contents Preface 1 Chapter 1: The New C++17 Features 10 Introduction 10 Using structured bindings to unpack bundled return values 11 How to do it... 11 How it works... 13 There's more... 13 Limiting variable scopes to if and switch statements 15 How to do it... 16 How it works... 16 There's more... 18 Profiting from the new bracket initializer rules 19 How to do it... 19 How it works... 20 Letting the constructor automatically deduce the resulting template class type 21 How to do it... 21 How it works... 22 There's more... 23 Simplifying compile time decisions with constexpr-if 24 How to do it... 24 How it works... 25 There's more... 26 Enabling header-only libraries with inline variables 28 How it's done... 28 How it works... 29 There's more... 31 Implementing handy helper functions with fold expressions 31 How to do it... 32 How it works... 32 There's more... 33 Match ranges against individual items 35 Check if multiple insertions into a set are successful 36 Check if all the parameters are within a certain range 37 Pushing multiple items into a vector 38
[ ii ] Chapter 2: STL Containers 39 Introduction 40 Contiguous storage 40 List storage 41 Search trees 41 Hash tables 42 Container adapters 42 Using the erase-remove idiom on std::vector 42 How to do it... 43 How it works... 45 There's more... 46 Deleting items from an unsorted std::vector in O(1) time 47 How to do it... 47 How it works... 50 Accessing std::vector instances the fast or the safe way 51 How to do it... 51 How it works... 52 There's more... 53 Keeping std::vector instances sorted 53 How to do it... 53 How it works... 55 There's more... 56 Inserting items efficiently and conditionally into std::map 56 How to do it... 57 How it works... 59 There's more... 60 Knowing the new insertion hint semantics of std::map::insert 60 How to do it... 60 How it works... 61 There's more... 62 Efficiently modifying the keys of std::map items 63 How to do it... 64 How it works... 66 There's more... 66 Using std::unordered_map with custom types 67 How to do it... 67 How it works... 69 Filtering duplicates from user input and printing them in alphabetical order with std::set 70
[ iii ] How to do it... 71 How it works... 72 std::istream_iterator 72 std::inserter 73 Putting it together 74 Implementing a simple RPN calculator with std::stack 74 How to do it... 75 How it works... 78 Stack handling 78 Distinguishing operands from operations from user input 79 Selecting and applying the right mathematical operation 80 There's more... 80 Implementing a word frequency counter with std::map 81 How to do it... 81 How it works... 84 Implement a writing style helper tool for finding very long sentences in text with std::multimap 85 How to do it... 86 How it works... 89 There's more... 90 Implementing a personal to-do list using std::priority_queue 90 How to do it... 91 How it works... 93 Chapter 3: Iterators 94 Introduction 94 Iterator categories 96 Input iterator 97 Forward iterator 97 Bidirectional iterator 97 Random access iterator 98 Contiguous iterator 98 Output iterator 98 Mutable iterator 98 Building your own iterable range 98 How to do it... 99 How it works... 101 Making your own iterators compatible with STL iterator categories 102 How to do it... 102 How it works... 105 There's more... 105 Using iterator adapters to fill generic data structures 106
[ iv ] How to do it... 106 How it works... 108 std::back_insert_iterator 108 std::front_insert_iterator 108 std::insert_iterator 109 std::istream_iterator 109 std::ostream_iterator 109 Implementing algorithms in terms of iterators 109 How to do it... 110 There's more... 113 Iterating the other way around using reverse iterator adapters 113 How to do it... 114 How it works... 115 Terminating iterations over ranges with iterator sentinels 116 How to do it... 117 Automatically checking iterator code with checked iterators 119 How to do it... 120 How it works... 122 There's more... 123 Building your own zip iterator adapter 124 How to do it... 126 There's more... 129 Ranges library 130 Chapter 4: Lambda Expressions 131 Introduction 131 Defining functions on the run using lambda expressions 133 How to do it... 133 How it works... 136 Capture list 137 mutable (optional) 138 constexpr (optional) 138 exception attr (optional) 138 return type (optional) 138 Adding polymorphy by wrapping lambdas into std::function 138 How to do it... 139 How it works... 141 Composing functions by concatenation 142 How to do it... 143 How it works... 145 Creating complex predicates with logical conjunction 146 How to do it... 146
[ v ] There's more... 148 Calling multiple functions with the same input 149 How to do it... 149 How it works... 151 Implementing transform_if using std::accumulate and lambdas 153 How to do it... 153 How it works... 156 Generating cartesian product pairs of any input at compile time 159 How to do it... 160 How it works... 162 Chapter 5: STL Algorithm Basics 164 Introduction 165 Copying items from containers to other containers 167 How to do it... 168 How it works... 170 Sorting containers 172 How to do it... 172 How it works... 176 Removing specific items from containers 176 How to do it... 177 How it works... 180 Transforming the contents of containers 180 How to do it... 181 How it works... 183 Finding items in ordered and unordered vectors 183 How to do it... 184 How it works... 188 Limiting the values of a vector to a specific numeric range with std::clamp 190 How to do it... 191 How it works... 194 Locating patterns in strings with std::search and choosing the optimal implementation 194 How to do it... 195 How it works... 197 Sampling large vectors 199 How to do it... 200 How it works... 203 Generating permutations of input sequences 204
[ vi ] How to do it... 204 How it works... 205 Implementing a dictionary merging tool 206 How to do it... 207 How it works... 209 Chapter 6: Advanced Use of STL Algorithms 210 Introduction 210 Implementing a trie class using STL algorithms 211 How to do it... 212 How it works... 216 Implementing a search input suggestion generator with tries 217 How to do it... 218 How it works... 222 There's more... 223 Implementing the Fourier transform formula with STL numeric algorithms 223 How to do it... 224 How it works... 230 Calculating the error sum of two vectors 232 How to do it... 232 How it works... 235 Implementing an ASCII Mandelbrot renderer 236 How to do it... 237 How it works... 241 Building our own algorithm - split 242 How to do it... 243 How it works... 245 There's more... 246 Composing useful algorithms from standard algorithms - gather 246 How to do it... 247 How it works... 249 Removing consecutive whitespace between words 251 How to do it... 252 How it works... 253 Compressing and decompressing strings 254 How to do it... 255 How it works... 257 There's more... 258
[ vii ] Chapter 7: Strings, Stream Classes, and Regular Expressions 260 Introduction 261 Creating, concatenating, and transforming strings 262 How to do it... 263 How it works... 265 Trimming whitespace from the beginning and end of strings 266 How to do it... 266 How it works... 268 Getting the comfort of std::string without the cost of constructing std::string objects 269 How to do it... 270 How it works... 272 Reading values from user input 273 How to do it... 273 How it works... 275 Counting all words in a file 276 How to do it... 277 How it works... 279 Formatting your output with I/O stream manipulators 279 How to do it... 280 How it works... 284 Initializing complex objects from file input 286 How to do it... 286 How it works... 288 Filling containers from std::istream iterators 289 How to do it... 290 How it works... 293 Generic printing with std::ostream iterators 294 How to do it... 295 How it works... 298 Redirecting output to files for specific code sections 299 How to do it... 300 How it works... 303 Creating custom string classes by inheriting from std::char_traits 304 How to do it... 305 How it works... 309 Tokenizing input with the regular expression library 310 How to do it... 311 How it works... 313
[ viii ] Comfortably pretty printing numbers differently per context on the fly 315 How to do it... 316 Catching readable exceptions from std::iostream errors 318 How to do it... 319 How it works... 321 Chapter 8: Utility Classes 322 Introduction 323 Converting between different time units using std::ratio 323 How to do it... 324 How it works... 327 There's more... 329 Converting between absolute and relative times with std::chrono 329 How to do it... 330 How it works... 332 Safely signalizing failure with std::optional 333 How to do it... 334 How it works... 336 Applying functions on tuples 338 How to do it... 338 How it works... 340 Quickly composing data structures with std::tuple 341 How to do it... 341 How it works... 346 operator< 346 The zip function for tuples 347 Replacing void* with std::any for more type safety 349 How to do it... 349 How it works... 352 Storing different types with std::variant 352 How to do it... 353 How it works... 357 Automatically handling resources with std::unique_ptr 358 How to do it... 359 How it works... 362 Automatically handling shared heap memory with std::shared_ptr 363 How to do it... 363 How it works... 366 There's more... 368 Dealing with weak pointers to shared objects 369
[ ix ] How to do it... 370 How it works... 372 Simplifying resource handling of legacy APIs with smart pointers 374 How to do it... 375 How it works... 377 Sharing different member values of the same object 378 How to do it... 379 How it works... 380 Generating random numbers and choosing the right random number engine 382 How to do it... 382 How it works... 387 Generating random numbers and letting the STL shape specific distributions 389 How to do it... 389 How it works... 396 Chapter 9: Parallelism and Concurrency 398 Introduction 398 Automatically parallelizing code that uses standard algorithms 399 How to do it... 400 How it works... 402 Which STL algorithms can we parallelize this way? 402 How do those execution policies work? 403 What does vectorization mean? 405 Putting a program to sleep for specific amounts of time 406 How to do it... 406 How it works... 407 Starting and stopping threads 408 How to do it... 409 How it works... 411 Performing exception safe shared locking with std::unique_lock and std::shared_lock 413 How to do it... 414 How it works... 417 Mutex classes 417 Lock classes 418 Avoiding deadlocks with std::scoped_lock 421 How to do it... 422 How it works... 424 Synchronizing concurrent std::cout use 425
[ x ] How to do it... 426 How it works... 428 Safely postponing initialization with std::call_once 429 How to do it... 430 How it works... 431 Pushing the execution of tasks into the background using std::async 432 How to do it... 433 How it works... 436 There's more... 437 Implementing the producer/consumer idiom with std::condition_variable 438 How to do it... 438 How it works... 441 Implementing the multiple producers/consumers idiom with std::condition_variable 443 How to do it... 444 How it works... 448 Parallelizing the ASCII Mandelbrot renderer using std::async 450 How to do it... 451 How it works... 454 Implementing a tiny automatic parallelization library with std::future 455 How to do it... 456 How it works... 460 Chapter 10: Filesystem 465 Introduction 465 Implementing a path normalizer 466 How to do it... 466 How it works... 468 There's more... 468 Getting canonical file paths from relative paths 469 How to do it... 470 How it works... 472 Listing all files in directories 473 How to do it... 473 How it works... 477 Implementing a grep-like text search tool 478 How to do it... 479 How it works... 481 There's more... 482
[ xi ] Implementing an automatic file renamer 482 How to do it... 483 Implementing a disk usage counter 485 How to do it... 486 How it works... 488 Calculating statistics about file types 488 How to do it... 489 Implementing a tool that reduces folder size by substituting duplicates with symlinks 492 How to do it... 492 How it works... 496 There's more... 496 Index 498
Preface The C++17 STL Cookbook will teach you how to get the most out of C++17 by providing coding recipes that combine the C++ language and its standard library, the STL. Indeed, this book uses as much STL as possible, which is worth a bit of explanation. C++ is such a great and powerful language. It allows us to hide complex solutions behind simple high-level interfaces but, at the same time, to write low-level code where high performance and low overhead really matter. The ISO C++ Standard Committee works hard on improving the C++ standard. C++11 brought a lot of great features to C++, and so did C++14 and C++17. As of today, C++ is a language that provides language features and standard library facilities for sophisticated standard data structures and algorithms, automatic resource management pointers, lambda expressions, constant expressions, portable thread control for concurrent programming, regular expressions, random number generators, exceptions, variadic templates (the part of C++ for expressing template types is even Turing-complete!), user-defined literals, portable filesystem traversal, and so much more. This giant bunch of features makes it a general-purpose language ideal for implementing high-quality and high-performance software in all fields of the software industry. However, many C++ programmers eagerly learn C++ as a language but put its standard library, the STL, in the second place. Using the C++ language without the help that the standard library provides often leads to programs that look like C with classes, but not what modern programs in the 21st century should look like. This is very sad because using C++ like that means dropping half its strength. In the C++11 edition of his book, The C++ Programming Language, Bjarne Stroustrup writes, "Please remember that those libraries and language features exist to support programming techniques for developing quality software. They are meant to be used in combination--as bricks in a building set--rather than to be used individually in relative isolation to solve a specific problem." This is exactly what this book and its recipes are about. All the recipes in this book are designed to be as near as possible to real-life problems, while at the same time, they do not rely on any external libraries other than the STL. This way, it is very simple to play around with each of them, without having to do confusing setup work. I really hope that you find inspiration in the recipes and, maybe, find some of them to be nice standard building blocks for solving higher-level problems with this great programming language.