Vector C++
Введение
Вектор является отдельно подключаемой библиотекой. Не удивляйтесь этому если Вы
изучали до этого более молодой язык программирования, в котором похожие
операции шли «из коробки»
Ветор содержит набор величин одного типа. То есть либо все
int
либо все
string
Размер указывать заранее не нужно. Память будет выделяться по мере необходимости,
иначе говоря, динамически.
К каждому элементу вектора легко получить доступ зная его порядковый номер.
Теорию можно изучить, например, в
Википедии
Пример
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 1. создаём вектор
vector <int> vec0;
cout << endl << "1. vector vec0 size is " << vec0.size();
if (vec0.empty())
{
cout << endl << "vector vec0 is empty" << endl;
}
else
{
cout << endl << "vector vec0 is not empty" << endl;
}
// 2. вектор из 5 элементов, каждый равен 4
vector <int> vec(5, 4);
cout << endl << "2. vector vec size is " << vec.size();
if (vec.empty())
{
cout << endl << "vector vec is empty" << endl;
}
else
{
cout << endl << "vector vec is not empty" << endl;
}
// 3. обходим вектор обычным циклом
cout << endl << "3. ";
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
cout << endl;
// 4. обходим вектор короче
cout << "4. ";
for (auto item : vec)
{
cout << item << " ";
}
// 5. добавляем элементы в конец
vec.push_back(7);
vec.push_back(8);
vec.push_back(9);
cout << endl << "5. new elements are added with push_back";
// 6. проверяем, что они в конце
cout << endl << "6. ";
for (auto item : vec)
{
cout << item << " ";
}
// 7. удаляем элементы с конца
vec.pop_back();
vec.pop_back();
// 8. проверяем, что элементы удалены
cout << endl << "8. ";
for (auto item : vec)
{
cout << item << " ";
}
// 9. копируем вектор
vector <int> vec_two(vec);
cout << endl << "9. vec_two size is " << vec_two.size() << endl;
// 10. проверяем содержимое vec_two
cout << endl << "10. ";
for (auto item : vec_two)
{
cout << item << " ";
}
// 11. проверяем, что векторы одинаковы
cout << endl << "11. ";
if (vec == vec_two)
{
cout << "identical";
}
else {
cout << "not identical";
}
cout << endl;
return 0;
}
1. vector vec0 size is 0 vector vec0 is empty 2. vector vec size is 5 vector vec is not empty 3. 4 4 4 4 4 4. 4 4 4 4 4 5. new elements are added with push_back 6. 4 4 4 4 4 7 8 9 8. 4 4 4 4 4 7 9. vec_two size is 6 10. 4 4 4 4 4 7 11. identical
Задача
Создать вектор целых чисел vi от 0 до 9 и вывести на экран.
Вывести на экран размер вектора vi.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> vi;
for (int i = 0; i < 10; i++)
{
vi.push_back(i);
}
for (auto item : vi)
{
cout << item << " ";
}
cout << endl << endl;
cout << "int vector vi has " << vi.size() << " elements. " << endl;
cout << endl;
return 0;
}
Результат:
0 1 2 3 4 5 6 7 8 9 int vector vi has 10 elements. C:\Users\ao\source\repos\vector_00.exe (process 101408) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Вручную меняем значения нескольких элементов
vi[5] = 3;
vi[6] = -1;
vi[1] = 99;
Выведем изменённый вектор на экран другим способом:
for (unsigned int i = 0; i < vi.size(); i++)
{
cout << vi[i] << " ";
}
cout << endl;
Результат:
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 C:\Users\ao\source\repos\vector_00.exe (process 101408) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Вычислим сколько элементов вектора равны 3. Для вывода вектора на экран воспользуемся новым способом.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // для sort и count
using namespace std;
int main()
{
vector<int> vi;
for (int i = 0; i < 10; i++)
{
vi.push_back(i);
}
vi[5] = 3;
vi[6] = -1;
vi[1] = 99;
for (auto i = begin(vi); i != end(vi); i++)
{
cout << *i << " ";
}
cout << endl;
int threes = count(begin(vi), end(vi), 3);
cout << "vector of ints has " << threes << " elements with value 3";
cout << endl;
return 0;
}
Результат:
0 99 2 3 4 3 -1 7 8 9 vector of ints has 2 elements with value 3 C:\Users\ao\source\repos\vector_00.exe (process 4108) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Задача
Записать три слова, введённые с клавиатуры в вектор, вывести их на экран, отсортировать по алфавиту, определить сколько в первом слове букв о.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // для sort и count
using namespace std;
int main()
{
vector<string> vs;
cout << "enter three words ";
for (int i = 0; i < 3; i++)
{
string s;
cin >> s;
vs.push_back(s);
}
for (auto item : vs)
{
cout << item << " ";
}
cout << endl;
sort(begin(vs), end(vs));
for (auto item : vs)
{
cout << item << " ";
}
cout << endl;
int os = count(begin(vs[0]), end(vs[0]), 'o');
cout << "first word has " << os << " letter o's ";
return 0;
}
Результат:
enter three words heihei andreyolegovich topbicycle heihei andreyolegovich topbicycle andreyolegovich heihei topbicycle first word has 2 letter o's C:\Users\wd973579\source\repos\Plural_02\Debug\Plural_02.exe (process 93128) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Как Вы можете увидеть слова отсортированы по алфавиту. В названии сайта andreyolegovich две буквы о.
Вывести по отдельности элементы
Задача: дана строка с числами через запятую.
Нужно:
вывести числа на экран по отдельности.
вычислить сумму чисел
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str = "12,1,214,3234";
string s;
vector <int> vec;
int x;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != )
{
s = s + str[i];
}
else
{
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
}
}
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
int sum = 0;
for (auto item : vec)
{
sum = sum + item;
cout << item << " ";
}
cout << endl << "Сумма чисел в строке = " << sum << endl;
return 0;
}
После запуска программы результат будет таким:
12 1 214 3234 12 1 214 3234 Сумма чисел в строке = 3461 C:\Users\ao\source\repos\vector_01.exe (process 144128) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Сумма чисел в строке
Задача: дана строка чисел, разделённых запятыми.
Нужно:
вывести числа на экран по одному.
посчитать сумму чисел
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string str = "12,1,214,3234";
string s;
vector <int> vec;
int x;
for (int i = 0; i < str.length(); i++)
{
if (str[i] != ',')
{
s = s + str[i];
}
else
{
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
}
}
cout << s << endl;
x = atoi(s.c_str());
s.clear();
vec.push_back(x);
int sum = 0;
for (auto item : vec)
{
sum = sum + item;
cout << item << " ";
}
cout << endl << "Sum of numbers in the string = " << sum << endl;
return 0;
}
12 1 214 3234 12 1 214 3234 Sum of numbers in the string = 3461
Create a two-dimensional vector
Task: create a two-dimensional vector 3 by 5 and fill it with random numbers from 0 to 9
#include <iostream>
#include <vector>
#include <cstdlib> // для rand()
using namespace std;
int main() {
vector<vector<int>> vec;
for (int i = 0; i < 3; i++)
{
vector <int> temp;
for (int j = 0; j < 5; j++)
{
temp.push_back(rand()%10);
}
vec.push_back(temp);
}
cout << endl;
for (int vecline = 0; vecline < 3; vecline++)
{
for (int vecelem = 0; vecelem < 5; vecelem++)
{
cout << vec[vecline][vecelem] << " ";
}
cout << endl;
}
return 0;
}
12 1 214 3234 12 1 214 3234 Sum of numbers in the string = 3461
Создать двухмерный Vector C++
Задача: создать двухмерный вектор 3 на 5 и заполнить его случайными числами от 0 до 9
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<vector<int>> vec;
for (int i = 0; i < 3; i++)
{
vector <int> temp;
for (int j = 0; j < 5; j++)
{
temp.push_back(rand()%10);
}
}
cout << endl;
for (int vecline = 0; vecline < 3; vecline++)
{
for (int vecelem = 0; vecelem < 5; vecelem++)
{
cout << vec[vecline][vecelem] << " ";
}
cout << endl;
}
return 0;
}
После запуска программы результат будет таким:
1 7 4 0 9 4 8 8 2 4 5 5 1 7 1 C:\Users\ao\source\repos\vector_02.exe (process 145912) exited with code 0. To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops. Press any key to close this window . . .
Видео
В видео ниже есть всё, что описано в статье кроме более быстрого перебора элеметов вектора.
Автор статьи: Андрей Олегович