Using the STL Library in C++, part 2 – extension

Last time I wrote something about creating dynamic arrays by using the STL. Today I am going to write more.

You already know that to create an array we have to write:



#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()

{
vector <float> myDynamicArray;

myDynamicArray.push_back(32);

myDynamicArray.push_back(13);

myDynamicArray.push_back(22);

myDynamicArray.push_back(19);

And then we want to see what is inside, so:

vector <float>::iterator iIterator;  //here we create an iterator

for (iIterator = myDynamicArray.begin(); iIterator = myDynamicArray.end(); iIterator ++ )  //when the value of iIterator is equal to the beginning of array, so when it is "0" -> till it is the end of our array it increases by one

{

cout << *iIterator<< endl;

}

We can also display the size of our array:

cout << " The size of our array is:" << myDynamicArray.size() << endl;

And then for example sort numbers inside our array:

sort(myDynamicArray.begin(), myDynamicArray.end());  //we have to sort all of the values from the beginning till the end of an array
return 0;
}

There is a problem, because when we want to display array after modifications, we have to do this every time:

for (iIterator = myDynamicArray.begin(); iIterator = myDynamicArray.end(); iIterator ++ )

cout << *iIteratorv<< endl;

So why not to use functions?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void iItem(const vector <float>& listArray); // function declaration

int main()

{
 vector <float> myDynamicArray;

myDynamicArray.push_back(32);

myDynamicArray.push_back(13);

myDynamicArray.push_back(22);

myDynamicArray.push_back(19);

cout << "Array elements: \n";
iItem(myDynamicArray);
cout << endl;

sort(myDynamicArray.begin(), myDynamicArray.end());
cout << "Sorted elements: \n";

iItem(myDynamicArray);

cout << endl;

cout << " The size of our array is:" << myDynamicArray.size() << endl;

return 0;

}

void iItem(const vector <float>& listArray) // function definition
{
vector <float>::const_iterator iIterator;
for (iIterator = listArray.begin(); iIterator != listArray.end(); iIterator ++)
{
cout << *iIterator << endl;
}
}

After compilation it looks exactly like this:

There are a lot of the STL algorithms which you can use in your applications, and I really recommend it.

MJ

2 uwagi do wpisu “Using the STL Library in C++, part 2 – extension

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

Connecting to %s