CS253: Software Development with C++

Spring 2018

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() % 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 

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-11T20:00

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building