Индекси на вектори
* Граници на индексите - от 0 до размерността на вектора
-1
Грешка при "излизане извън границите на вектора".
* Член-функция за получаване на размерността на вектора
vector<double> salaries(10);
...
for (i = 0; i < salaries.size(); i++)
оператор
Типичен цикъл за обхождане на елементите на вектора.
Вектор с 0 елементи:
vector<double> salaries;
* Член-функции за увеличаване и намаляване на размера на вектора
salaries.push_back(елемент);
salaries.pop_back();
Четат се заплати на служители и се чертае графика на заплатите:
#include "ccc_win.cpp"
int main()
{ vector<double> salaries;
bool more = true;
while (more)
{ double s = cwin.get_double("Please
enter a salary, 0 to quit: ");
if (s == 0) more =
false;
else salaries.push_back(s);
}
int i;
double highest = salaries[0];
for (i = 1; i < salaries.size();
i++)
if (salaries[i]
> highest) highest = salaries[i];
cwin.coord(0, 0, highest, salaries.size());
for (i = 0; i < salaries.size();
i++)
{ Point left(0, i);
Point right(salaries[i],
i);
Line bar(left,
right);
Message label(left,
salaries[i]);
cwin <<
bar << label;
}
return 0;
}
Векторите като параметри и стойности
на функции
* Средно аритметично на елементите на вектор:
#include <iostream>
#include <vector>
using namespace std;
double average(vector<double>
v)
{ if (v.size()
== 0) return 0;
int i;
double sum = 0;
for (i = 0; i < v.size();
i++) sum = sum + v[i];
return sum / v.size();
}
int main()
{ vector<double>
salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
double avgsal = average(salaries);
cout << "The average
salary is " << avgsal << "\n";
return 0;
}
* Промяна на стойностите на елементите на вектор:
#include <iostream>
#include <vector>
using namespace std;
void raise_salaries(vector<double>&
s, double p)
{ int i;
for (i = 0; i < s.size();
i++) s[i] = s[i] * (1 + p/100);
}
int main()
{ vector<double> salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
raise_salaries(salaries, 4.5);
int i;
for (i = 0; i < salaries.size();
i++)
cout <<
salaries[i] << "\n";
return 0;
}
* Функцията връща вектор - всички стойности, които попадат в определен
интервал.
#include <iostream>
#include <vector>
using namespace std;
vector<double> between(vector<double>
v, double low, double high)
{ vector<double> result;
int i;
for (i = 0; i < v.size(); i++)
if (low <= v[i] and v[i] <=
high) result.push_back(v[i]);
return result;
}
int main()
{ vector<double> salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
vector<double> midrange_salaries
= between(salaries,
45000.0, 65000.0);
int i;
for (i = 0; i < midrange_salaries.size();
i++)
cout <<
midrange_salaries[i] << "\n";
return 0;
}
Прости алгоритми за вектори: намиране
на стойност, броене и др.
* Намиране на стойност:
#include <iostream>
#include <vector>
using namespace std;
int find_first_greater(vector<double>
a, double t)
{ int i = 0;
while (i < a.size())
{ if (a[i] > t)
return i;
else
i++; }
return -1;
}
int main()
{ vector<double> salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
int i = find_first_greater(salaries, 50000);
if (i > 0)
{ cout << "The
first salary above 50000 is at index " << i
<< " and is " << salaries[i] << "\n";
}
return 0;
}
* Броене:
#include <iostream>
#include <vector>
using namespace std;
int count_greater(vector<double> a,
double t)
{ int count = 0;
int i;
for (i = 0; i < a.size();
i++)
if
(a[i] > t) count++;
return count;
}
int main()
{ vector<double> salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
int count = count_greater(salaries, 50000);
cout << count <<
" salaries are above 50000\n";
return 0;
}
* Намиране на всички съответствия:
#include <iostream>
#include <vector>
using namespace std;
#include "ccc_empl.cpp"
vector<int> find_all_greater(vector<double>
a, double t)
{ vector<int> pos;
int i;
for (i = 0; i < a.size();
i++)
{ if (a[i] > t)
pos.push_back(i); }
return pos;
}
int main()
{ vector<double> salaries(5);
salaries[0] = 35000.0;
salaries[1] = 63000.0;
salaries[2] = 48000.0;
salaries[3] = 78000.0;
salaries[4] = 51500.0;
vector<int> matches = find_all_greater(salaries, 50000);
int j;
cout << "These are
the salaries above 50000:\n";
for (j = 0; j < matches.size();
j++)
cout <<
salaries[matches[j]] << "\n";
return 0;
}
* Отстраняване на елемент от вектор:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void erase(vector<string>& a, int
pos)
{ int i;
for (i = pos; i < a.size()
- 1; i++) a[i] = a[i + 1];
a.pop_back();
}
void print(vector<string> a)
{ int i;
for (i = 0; i < a.size();
i++)
cout <<
"[" << i << "] " << a[i] << "\n";
}
int main()
{ vector<string> staff(5);
staff[0] = "Cracker, Carl";
staff[1] = "Hacker, Harry";
staff[2] = "Lam, Larry";
staff[3] = "Reindeer, Rudolf";
staff[4] = "Sandman, Susan";
print(staff);
int pos;
cout << "Remove which
element? ";
cin >> pos;
erase(staff, pos);
print(staff);
return 0;
}
* Вмъкване на елемент на вектор:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void insert(vector<string>& a, int
pos, string s)
{ int last = a.size() - 1;
a.push_back(a[last]);
int i;
for (i = last; i > pos; i--)
a[i] = a[i - 1];
a[pos] = s;
}
void print(vector<string> a)
{ int i;
for (i = 0; i < a.size();
i++)
cout <<
"[" << i << "] " << a[i] << "\n";
}
int main()
{ vector<string> staff(5);
staff[0] = "Cracker, Carl";
staff[1] = "Hacker, Harry";
staff[2] = "Lam, Larry";
staff[3] = "Reindeer, Rudolf";
staff[4] = "Sandman, Susan";
print(staff);
int pos;
cout << "Insert before
which element? ";
cin >> pos;
insert(staff, pos, "New, Nina");
print(staff);
return 0;
}
Успоредни вектори и вектор от
обекти
Задачата за най-добро отношение цена-качество на компютри.
#include "ccc_win.cpp"
int main()
{ vector<string> names;
vector<double> prices;
vector<int> scores;
string more;
do
{ string n = cwin.get_string("Product
name:");
names.push_back(n);
double
p = cwin.get_double("Price:");
prices.push_back(p);
int s =
cwin.get_int("Score:");
scores.push_back(s);
more =
cwin.get_string("More data? (y/n)");
} while (more == "y");
const double MAX_PRICE = 10000;
const double MAX_SCORE =
100;
cwin.coord(0, 0, MAX_PRICE,
MAX_SCORE);
int i;
for (i = 0; i < names.size();
i++)
{ Message label(Point(prices[i],
scores[i]), names[i]);
cwin <<
label.get_start() << label;
}
return 0;
}
Решение с използване на вектор от обекти.
#include "ccc_win.cpp"
class Product {
public:
Product();
void read();
void get_price() const;
void plot() const;
private:
double price;
int score;
string name;
};
Product::Product()
{ price = 1000; score
= 0; }
void Product::read()
{ name = cwin.get_string("Product
name:");
price = cwin.get_double("Price:");
score = cwin.get_int("Score:");
}
void Product::plot() const
{ Message label(Point(price, score),
name);
cwin << label.get_start()
<< label;
}
int main()
{ vector<Product> data;
string more;
do
{ Product c;
c.read();
data.push_back(c);
more =
cwin.get_string("More data? (y/n)");
} while (more == "y");
const double MAX_PRICE = 10000;
const double MAX_SCORE =
100;
cwin.coord(0, 0, MAX_PRICE,
MAX_SCORE);
int i;
for (i = 0; i < data.size();
i++)
data[i].plot();
return 0;
}
Векторите като данни на обект
* Програма за чертаене на многоъгълници:
#include "ccc_win.cpp"
class Polygon
{
public:
Polygon();
void add_point(Point p);
void plot() const;
private:
vector<Point> corners;
};
Polygon::Polygon() {}
void Polygon::add_point(Point p) { corners.push_back(p); }
void Polygon::plot() const
{ int i;
int n = corners.size();
for (i = 0; i < n; i++)
cwin <<
Line(corners[i], corners[(i + 1) % n]);
}
int main()
{ Polygon triangle;
triangle.add_point(Point(1,
1));
triangle.add_point(Point(3,
4));
triangle.add_point(Point(2,
6));
triangle.plot();
const double PI = 3.141592653589793;
Polygon pentagon;
int i;
for (i = 0; i < 5; i++)
pentagon.add_point(Point(cos(2
* PI * i / 5),
sin(2 * PI * i / 5)));
pentagon.plot();
return 0;
}
Обхождане на елементите на масив:
const int SAL_MAXSIZE = 10;
double sal[SAL_MAXSIZE];
int sal_size = 0;
bool more = true;
while (more and sal_size < SAL_MAXSIZE)
{ cout << "Enter salary or 0 to
quit";
double x;
cin >> x;
if (cin.fail()) more = false
else
{ sal[sal_size] = x;
sal_size++; }
}
* Mасивите като параметри на функции
Масивите винаги се предават по псевдоним.
double maximum(const double a[], int a_size)
{ if (a_size == 0) return 0;
double highest = a[0];
int i;
for (i = 1; i < a_size;
i++)
if (a[i]
> highest) highest = a[i];
return highest;
}
Следващата програма чете заплати от стандартен вход и отпечатва максималната
заплата.
#include <iostream>
using namespace std;
void read_data(double a[], int a_maxsize,
int& a_size)
{ a_size = 0;
double x;
while (a_size < a_maxsize
and (cin >> x))
{ a[a_size] = x;
a_size++; }
}
double maximum(const double a[], int a_size)
{ if (a_size == 0) return 0;
double highest = a[0];
int i;
for (i = 1; i < a_size;
i++)
if (a[i]
> highest) highest = a[i];
return highest;
}
int main()
{ const int SALARIES_MAXSIZE = 100;
double salaries[SALARIES_MAXSIZE];
int salaries_size = 0;
cout << "Please enter
all salary data: ";
read_data(salaries, SALARIES_MAXSIZE,
salaries_size);
if (salaries_size == SALARIES_MAXSIZE
and not cin.fail())
cout <<
"Sorry--extra data ignored\n";
double maxsal = maximum(salaries,
salaries_size);
cout << "The maximum
salary is " << maxsal << "\n";
return 0;
}
Масиви от символи
char input = 'y';
char greeting[6] = "Hello";
char greeting[] = "Hello";
char greeting[10] = "Hello";
Проблемът със символа за край на низ при използване на масиви от символи.
Двумерни масиви
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const int BALANCES_ROWS = 11;
const int BALANCES_COLS = 6;
double future_value(double initial_balance,
double p, int nyear)
{ double b = initial_balance * pow(1
+ p/12/100, 12*nyear);
return b; }
void print_table(const double table[][BALANCES_COLS],
int table_rows)
{ int i, j;
cout << fixed <<
setprecision(2);
for (i = 0; i < table_rows;
i++)
{ for (j = 0; j <
BALANCES_COLS; j++)
cout << setw(10) << table[i][j];
cout <<
"\n";
}
}
int main()
{ double balances[BALANCES_ROWS][BALANCES_COLS];
int i;
int j;
for (i = 0; i < BALANCES_ROWS;
i++)
for (j
= 0; j < BALANCES_COLS; j++)
balances[i][j] = future_value(10000, 5 + i * 0.5,
5 + j * 5);
print_table(balances, BALANCES_ROWS);
return 0;
}