v_3c
main.cpp
Go to the documentation of this file.
1
// Vorlesung 23.Maerz 2018
2
// Dynamische C++-Vektoren
3
// Vektor als Funktionsargument
4
#include <iostream>
5
#include <vector>
// vector
6
#include <cmath>
// sqrt()
7
using namespace
std;
8
9
//------------------------------------------------------------------------------
10
// Drei Varianten Initialisierung eines C++-Vektors innerhalb einer Funktion
11
//------------------------------------------------------------------------------
17
vector<float>
vec_init_1
(
const
int
n)
18
{
19
vector<float> tmp(n);
// allokiert Speicher fuer n float-Zahlen
20
for
(
int
k=0; k<tmp.size(); ++k)
21
{
22
tmp.at(k) = sqrt(1.0+k);
23
}
24
return
tmp;
// nicht vergessen!
25
}
26
27
33
void
vec_init_2
(
const
int
n, vector<float>& v)
34
{
35
v.resize(n);
// allokiert Speicher fuer n float-Zahlen
36
for
(
int
k=0; k<v.size(); ++k)
37
{
38
v.at(k) = sqrt(1.0+k);
39
}
40
}
41
42
50
void
vec_init_3
(
const
int
n, vector<float>& v)
51
{
52
v.clear();
// kein Speicher allokiert
53
for
(
int
k=0; k<n; ++k)
54
{
55
v.push_back(sqrt(1.0+k));
// Element wird an das Ende angehaengt
56
}
57
}
58
62
void
print_vek
(
const
vector<float>& v)
63
{
64
for
(
size_t
k=0; k<v.size(); ++k)
65
{
66
cout <<
" "
<< v[k];
67
}
68
cout << endl;
69
}
70
71
//------------------------------------------------------------------------------
72
73
int
main
()
74
{
75
cout <<
"Hello world!"
<< endl;
76
int
n;
// variable Vektorlaenge
77
cout <<
"Anzahl der Elemente = "
;
78
cin >> n;
79
80
{
81
// Funktion 1 testen
82
vector<float> v =
vec_init_1
(n);
83
cout << v.front() <<
" "
<< v.at(n/2) <<
" "
<< v.back() << endl << endl;
84
}
// hier endet die Gueltigkeit von v
85
86
{
87
// Funktion 2 testen
88
vector<float> v;
// Vektor der Laenge 0
89
vec_init_2
(n,v);
90
cout << v.front() <<
" "
<< v.at(n/2) <<
" "
<< v.back() << endl << endl;
91
}
// hier endet die Gueltigkeit von v
92
93
{
94
// Funktion 2 testen
95
vector<float> v(20, -1.2345);
// 20 Vektorelemente, jedes mit -1.2345 initialisiert
96
vec_init_3
(n,v);
97
cout << v.front() <<
" "
<< v.at(n/2) <<
" "
<< v.back() << endl << endl;
98
99
print_vek
(v);
100
}
// hier endet die Gueltigkeit von v
101
102
103
return
0;
104
}
vec_init_3
void vec_init_3(const int n, vector< float > &v)
Definition:
main.cpp:50
main
int main()
Definition:
main.cpp:73
print_vek
void print_vek(const vector< float > &v)
Definition:
main.cpp:62
vec_init_1
vector< float > vec_init_1(const int n)
Definition:
main.cpp:17
vec_init_2
void vec_init_2(const int n, vector< float > &v)
Definition:
main.cpp:33
main.cpp
Generated by
1.9.1