Files
gpd-924-en/CPlusPlus/Collections/main.cpp
T
david d8f6014fab add collections
add pointers
2025-09-16 18:10:24 +02:00

89 lines
1.9 KiB
C++

#include <iostream>
#include <vector>
#include <list>
#include "grid.h"
using namespace std;
void printArray(int numbers[]);
void printArray(int numbers[], size_t count);
int main()
{
// C arrays
int numbers[10];
for (size_t i = 0; i < 10; i++)
{
numbers[i] = 0;
}
int numbers2[] = { 0, 1, 2, 3, 4 };
int numbers3[10] = { 0, 1, 2, 3, 4 };
numbers[0] = 10;
cout << "numbers[5]: " << numbers[5] << endl;
// 2D array - 10 columns, 5 rows
int grid[COLUMNS * ROWS] = {};
grid[calculateIndex(3, 2)] = 10; // 4th column, 3rd row
// size has to be always constant
const int count = 10;
int numbers4[count] = {};
int length = sizeof(numbers) / sizeof(numbers[0]); // works only with local constant sized arrays
for (size_t i = 0; i < size(numbers); i++) // works only with local constant sized arrays, but it is safer than sizeof
{
cout << numbers[i] << " ";
}
cout << endl;
printArray(numbers);
printArray(numbers, size(numbers));
// "dynamic" (...) arrays
// stl collections
vector<int> numbers5;
vector<int> numbers6 = { 0, 1, 2, 3, 4 };
numbers5.push_back(10); // add an item at the end
numbers5.pop_back(); // remove the last item
numbers6[1] *= 2;
vector<int> numbers7;
numbers7.reserve(100);
numbers7.shrink_to_fit();
printArray(numbers6.data(), numbers6.size());
list<int> numbersList;
numbersList.push_back(10);
numbersList.push_front(0);
//numbersList[0] = 5; // random access is not available for lists
return 0;
}
void printArray(int numbers[])
{
int length = sizeof(numbers) / sizeof(numbers[0]); // works not outside of the local scope
cout << "sizeof(numbers): " << sizeof(numbers) << endl;
//for (size_t i = 0; i < size(numbers); i++) // size is not working outside of the local scope
//{
// cout << numbers[i] << " ";
//}
//cout << endl;
}
void printArray(int numbers[], size_t count)
{
for (size_t i = 0; i < count; i++)
{
cout << numbers[i] << " ";
}
cout << endl;
}