CS253: Software Development with C++

Spring 2020

Copy If

Show Lecture.CopyIf as a slide show.

CS253 Copy If

Introduction

    copy_if(source-begin, source-end, dest-begin, predicate)

First attempt

Let’s ensure that we know how to use copy() before moving on to copy_if():

string foo = "This is serious—I have to ration my Diet Mountain Dew!";
cout << foo << "\n";
string bar;
copy(foo.begin(), foo.end(), bar.begin());
cout << bar << "\n";
SIGSEGV: Segmentation fault

Why did that fail? No space allocated in bar.

Second attempt

string foo = "This is serious—I have to ration my Diet Mountain Dew!";
cout << foo << "\n";
string bar(foo.size(), 'X');
copy(foo.begin(), foo.end(), bar.begin());
cout << bar << "\n";
This is serious—I have to ration my Diet Mountain Dew!
This is serious—I have to ration my Diet Mountain Dew!

Third attempt

string foo = "This is serious—I have to ration my Diet Mountain Dew!";
cout << foo << "\n";

string bar(foo.size(), 'X');
// Don’t copy vowels:
copy_if(foo.begin(), foo.end(), bar.begin(),
        [](char c){return "aeiouyAEIOUY"s.find(c)==string::npos;} );

cout << bar << "\n";
This is serious—I have to ration my Diet Mountain Dew!
Ths s srs— hv t rtn m Dt Mntn Dw!XXXXXXXXXXXXXXXXXXXXX

Fourth attempt

string foo = "This is serious—I have to ration my Diet Mountain Dew!";
cout << foo << "\n";

string bar(foo.size(), 'X');
// Don’t copy vowels:
auto it = copy_if(foo.begin(), foo.end(), bar.begin(),
                  [](char c){return "aeiouyAEIOUY"s.find(c)==string::npos;} );

// Make bar the correct size:
bar.resize(it-bar.begin());
cout << bar << "\n";
This is serious—I have to ration my Diet Mountain Dew!
Ths s srs— hv t rtn m Dt Mntn Dw!

We resized bar to the correct size.

In-place

string foo = "This is serious—I have to ration my Diet Mountain Dew!";
cout << foo << "\n";

auto it = copy_if(foo.begin(), foo.end(), foo.begin(),
                  [](char c){return "aeiouyAEIOUY"s.find(c)==string::npos;} );
// Make foo the correct size:
foo.resize(it-foo.begin());
cout << foo << "\n";
This is serious—I have to ration my Diet Mountain Dew!
Ths s srs— hv t rtn m Dt Mntn Dw!

We can copy from & to the same location.