Vector C++

Вектор является отдельно подключаемой библиотекой. Не удивляйтесь этому если Вы изучали до этого более молодой язык программирования, в котором похожие операции шли «из коробки»

Ветор содержит набор величин одного типа. То есть либо все int либо все string

Размер указывать заранее не нужно. Память будет выделяться по мере необходимости, иначе говоря, динамически.

К каждому элементу вектора легко получить доступ зная его порядковый номер.

Теорию можно изучить, например, в Википедии

#include <iostream> #include <vector> using namespace std; int main() { // 1. create a vector 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; }

1. vector vec0 size is 0 vector vec0 is empty

// 2. create vector with 5 elements each element is 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; }

2. vector vec size is 5 vector vec is not empty

// 3. go through vector elements with a standard loop cout << endl << "3. "; for (int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } cout << endl;

3. 4 4 4 4 4

// 4. go through vector elements in a shorter way cout << "4. "; for (auto item : vec) { cout << item << " "; } // 5. add new elements to the end vec.push_back(7); vec.push_back(8); vec.push_back(9); cout << endl << "5. new elements are added with push_back"; // 6. check that they are at the end cout << endl << "6. "; for (auto item : vec) { cout << item << " "; } // 7. remove elements from the end vec.pop_back(); vec.pop_back(); // 8. check that elements are removed cout << endl << "8. "; for (auto item : vec) { cout << item << " "; } // 9. copy vector vector <int> vec_two(vec); cout << endl << "9. vec_two size is " << vec_two.size() << endl; // 10. check vec_two content cout << endl << "10. "; for (auto item : vec_two) { cout << item << " "; } // 11. check if vectors are identical 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 C:\Users\ao\source\repos\vectors1.exe (process 111800) 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 от 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> // for sort and 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> // for sort and 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 две буквы о.

Видео

В видео ниже есть часть того описано в статье кроме.

Статьи о C++
Вектор. Часть 1.
Вектор. Часть 2.
Указатели
Классы
SFML
Тетрис на C++ с библиотекой SFML2
SDL
Массив Структур
Как узнать тип переменной C++
Решение задач на C++
Как создать пустую строку в C++
Errors C++
Share in social media: