Vectors

Hey everyone,
im trying to get to know vectors but i came to a point that my current knowledge stops and i need more help,
i found a program which i would like to understand but i couldn't figure it out.
here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<iostream>
#include<vector>
#include<string>
#include<iterator>
using namespace std;

bool islowerCase(char c)
{
  return islower(c);
}

int main()
{
  const int size=10;
  vector<char>v1;
  vector<char>::iterator lastElem;
 

  const char charList[size]={'w','W','b','B','C','E','w','F','B','m'};
 

  for(int i=0;i<size; i++)
    {
      v1.push_back(charList[i]);

    }
  lastElem =remove_if(v1.begin(), v1.end(), islowerCase);//line1
  ostream_iterator<char> screen(cout, "");//line2
 

  copy(v1.begin(), lastElem, screen);//line3
  cout<<endl;
}


can somebody explain to me line 1,2 and three (where it is shown as comments)
in detail because i am really struggling to understand how it works thanks a lot
- line 1 will iterate from the first element to the last element of v1; for each element (of type char in this case) it will call the function islowerCase() (passed as a function pointer). If islowerCase() returns true, the element will be removed from the vector; if it returns false, it will be kept. In other words, line 1 removes all the lowercase letters in the vector.

- line 2 will instantiate an ostream_iterator associated to the standard output. An ostream_iterator makes it easy to insert several elements of the same type to an output stream (here cout), as you will see in line 3

- line 3 is equivalent to this for loop:
1
2
3
4
for (size_t i = 0; i < v1.size(); ++i)
{
    screen = v1[i];  // thank to ostream_iterator, this line is equivalent to:  cout << v1[i]
}

In other words, lines 2 & 3 write the elements of v1 to the standard output.
Last edited on
Line 1: it's removing all the elements from the vector which match the condition of islowerCase -those which will make that function return true- http://www.cplusplus.com/reference/algorithm/remove_if/

Lines 2-3 simply print the elements using iterators:
http://www.cplusplus.com/reference/std/iterator/ostream_iterator/
http://www.cplusplus.com/reference/algorithm/copy/

[Edit] too slow...
Last edited on
That remove algorithm is in my opinion somewhat mis-named.
In this case it does not necessarily remove all the lower-case letters.

What happens it that the size of the vector is not changed - just (possibly) somewhat re-arranged.

After the remove is finished anything from vector.begin() up to but not including the item at lastElem is what you want.

Any item from lastItem (including lastItem) up to the end of the vector is unwanted
Last edited on
Topic archived. No new replies allowed.