CS253

CS253: Software Development with C++

Spring 2017

Copy If

See this page as a slide show

Copy If

CS253 Copy If

First attempt

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 100);
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 << ' ';
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 
SIGSEGV: Segmentation fault

Second attempt

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 100);
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 << ' ';
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 
83 77 15 93 35 49 21 27 59 63 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() % 100);
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 << ' ';
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 
83 77 15 93 35 49 21 27 59 63 

In-place

vector<int> foo;
for (int i=1; i<=20; i++)
    foo.push_back(rand() % 100);
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 << ' ';
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 
83 77 15 93 35 49 21 27 59 63 

Modified: 2017-04-17T14:53

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building