Esempi: Appendice 3
Contents
Esempi: Appendice 3¶

A3.1 esempio di utilizzo di `std::find`
¶
main_01.cpp
/*
c++ -o main_04 main_04.cpp
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std ;
int main (int argc, char ** argv)
{
vector<float> v ;
for (int i = 0 ; i < 10 ; ++i) v.push_back (0.5 * i) ;
vector<float>::iterator risultato =
find (v.begin (), v.end (), 3.5) ;
if (risultato != v.end ()) cout << "trovato " << *risultato << endl ;
return 0 ;
}

A3.2 esempio di utilizzo di `std::sort`
¶
main_02.cpp
/*
c++ -o main_05 main_05.cpp
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std ;
int main (int argc, char ** argv)
{
vector<int> v ;
v.push_back (3) ;
v.push_back (2) ;
v.push_back (10) ;
v.push_back (-1) ;
for (int i = 0 ; i < v.size () - 1 ; ++i) cout << v.at (i) << ", " ;
cout << v.at (v.size () - 1) << endl ;
sort (v.begin (), v.end ()) ;
for (int i = 0 ; i < v.size () - 1 ; ++i) cout << v.at (i) << ", " ;
cout << v.at (v.size () - 1) << endl ;
return 0 ;
}

A3.1 esempio di utilizzo di `std::sort`
con un algoritmo di ordinamento fornito dall’utente¶
main_03.cpp
/*
c++ -o main_06 main_06.cpp
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std ;
bool confronto (int i, int j)
{
if (i % 2 == 0)
{
if (j % 2 != 0) return true ;
else return (i < j) ;
}
else
{
if (j % 2 == 0) return false ;
else return (i < j) ;
}
}
int main (int argc, char ** argv)
{
vector<int> v ;
v.push_back (3) ;
v.push_back (2) ;
v.push_back (10) ;
v.push_back (-1) ;
for (int i = 0 ; i < v.size () - 1 ; ++i) cout << v.at (i) << ", " ;
cout << v.at (v.size () - 1) << endl ;
sort (v.begin (), v.end (), confronto) ;
for (int i = 0 ; i < v.size () - 1 ; ++i) cout << v.at (i) << ", " ;
cout << v.at (v.size () - 1) << endl ;
return 0 ;
}
