CS253: Software Development with C++

Fall 2019

Copy If

Show Lecture.CopyIf as a slide show.

CS253 Copy If

First attempt

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 10);
for (auto v : foo)
    cout << v << ' ';
cout << endl;

vector<int> bar;
// copy only odd numbers:
copy_if(foo.begin(), foo.end(), bar.begin(),
        [](int i){return i%2;} );

for (auto v : bar)
    cout << v << ' ';
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 
SIGSEGV: Segmentation fault

Second attempt

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 10);
for (auto v : foo)
    cout << v << ' ';
cout << endl;

vector<int> bar(foo.size());
// copy only odd numbers:
copy_if(foo.begin(), foo.end(), bar.begin(),
        [](int i){return i%2;} );

for (auto v : bar)
    cout << v << ' ';
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 
3 7 5 3 5 9 1 7 9 3 0 0 0 0 0 0 0 0 0 0 

Third attempt

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 10);
for (auto v : foo)
    cout << v << ' ';
cout << endl;

vector<int> bar(foo.size());
// copy only odd numbers:
auto it = copy_if(foo.begin(), foo.end(), bar.begin(),
                  [](int i){return i%2;} );
bar.resize(it-bar.begin());

for (auto v : bar)
    cout << v << ' ';
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 
3 7 5 3 5 9 1 7 9 3 

In-place

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 10);
for (auto v : foo)
    cout << v << ' ';
cout << endl;

// copy only odd numbers:
auto it = copy_if(foo.begin(), foo.end(), foo.begin(),
                  [](int i){return i%2;} );
foo.resize(it-foo.begin());

for (auto v : foo)
    cout << v << ' ';
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 
3 7 5 3 5 9 1 7 9 3