0% found this document useful (0 votes)
20 views2 pages

Arrays Example

The document contains three C++ code examples: 1) An array example that calculates the sum of array elements. 2) An example demonstrating arrays as function parameters by printing two arrays. 3) A sorting algorithm example that sorts an integer vector using std::sort with different comparators.

Uploaded by

Alvin Syahputra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Arrays Example

The document contains three C++ code examples: 1) An array example that calculates the sum of array elements. 2) An example demonstrating arrays as function parameters by printing two arrays. 3) A sorting algorithm example that sorts an integer vector using std::sort with different comparators.

Uploaded by

Alvin Syahputra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

// arrays example

#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; ++n )
{
result += foo[n];
}
cout << result;
return 0;
}
// arrays as parameters
#include <iostream>
using namespace std;
void printarray (int arg[], int length) {
for (int n=0; n<length; ++n)
cout << arg[n] << ' ';
cout << '\n';
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
}

// sort algorithm example


#include <iostream>
// std::cout
#include <algorithm>
// std::sort
#include <vector>
// std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {

Edit &
Run

bool operator() (int i,int j) { return (i<j);}


} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8);
71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);
32 45 71)26 80 53 33

// 32

//(12

// using function as comp


std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12
32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);
26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!
=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
}

return 0;

//(12

You might also like