C++ Programming Concepts: Data Structures, File I/O, Matrix Operations
C++ Programming Examples: Data Structures, File I/O, and Matrix Operations
Data Structures and File Input/Output
This section demonstrates C++ data structures and file handling techniques. It defines structures for computers and programs, then shows how to read data from external text files into vectors of these custom types.
Computer and Program Data Structures
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
// Define Program struct first as it's used in Computer struct
struct Program {
string nameAbbreviation;
float installationMemory;
};
struct Computer {
int id;
float memory;
vector<Program> installedPrograms;
};
File Reading Function
The readData
function populates vectors of Computer
and Program
objects by reading from “aula.txt” and “programes.txt” respectively.
void readData(vector<Computer>& computers, vector<Program>& programs) {
ifstream computerFile("aula.txt");
if (!computerFile.is_open()) {
cerr << "Error: Could not open aula.txt" << endl;
return;
}
ifstream programFile("programes.txt");
if (!programFile.is_open()) {
cerr << "Error: Could not open programes.txt" << endl;
computerFile.close();
return;
}
Computer computerData;
Program programData;
// Read computer data
while (computerFile >> computerData.id >> computerData.memory) {
computers.push_back(computerData);
}
computerFile.close();
// Read program data
while (programFile >> programData.nameAbbreviation >> programData.installationMemory) {
programs.push_back(programData);
}
programFile.close();
}
Dynamic Matrix Generation and Display
This C++ program demonstrates how to create and populate a dynamic two-dimensional array (matrix) based on user-defined dimensions. It fills a central rectangular region with sequential numbers and sets the remaining elements to zero.
Main Function for Matrix Generation
#include <iostream>
using namespace std;
int main() {
int N, M;
cout << "Enter number of rows (N): ";
cin >> N;
cout << "Enter number of columns (M): ";
cin >> M;
// Note: Variable Length Arrays (VLAs) are a C99 feature and not standard C++.
// For robust C++ solutions, consider std::vector<std::vector<int>> or dynamic allocation with 'new'.
int mat[N][M];
if (N <= M) {
// Case: Number of rows is less than or equal to columns
int firstColumn = (M - N) / 2;
int lastColumn = firstColumn + N - 1;
int counter = 1;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (j < firstColumn || j > lastColumn) {
mat[i][j] = 0;
} else {
mat[i][j] = counter;
++counter;
}
}
}
} else {
// Case: Number of rows is greater than columns
int firstRow = (N - M) / 2;
int lastRow = firstRow + M - 1;
int counter = 1;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (i < firstRow || i > lastRow) {
mat[i][j] = 0;
} else {
mat[i][j] = counter;
++counter;
}
}
}
}
// Display the generated matrix
cout << "\nGenerated Matrix:\n";
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cout << mat[i][j] << ' ';
}
cout << endl;
}
return 0;
}
Fixed-Size Matrix Operations and Swapping
This section presents C++ code for handling fixed-size matrices, including reading from a file, printing to console, and performing row or column swaps interactively.
Matrix Definition and I/O Functions
#include <iostream>
#include <fstream>
using namespace std;
const int N_ROWS = 6;
const int M_COLS = 5;
typedef char Matrix[N_ROWS][M_COLS];
void readMatrix(Matrix& mat) {
ifstream file("matrix.txt");
if (!file.is_open()) {
cerr << "Error: Could not open matrix.txt" << endl;
return;
}
for (int i = 0; i < N_ROWS; ++i)
for (int j = 0; j < M_COLS; ++j)
file >> mat[i][j];
file.close();
}
void writeMatrix(const Matrix& mat) {
for (int i = 0; i < N_ROWS; ++i) {
// Display row number i
for (int j = 0; j < M_COLS; ++j)
cout << mat[i][j] << ' ';
cout << endl;
}
cout << endl;
}
Row and Column Swap Function
void swapElements(Matrix& mat, char type, int index1, int index2) {
if (type == 'F') { // 'F' for Row
// Swap rows
for (int k = 0; k < M_COLS; ++k) {
char temp = mat[index1][k];
mat[index1][k] = mat[index2][k];
mat[index2][k] = temp;
}
} else if (type == 'C') { // 'C' for Column
// Swap columns
for (int k = 0; k < N_ROWS; ++k) {
char temp = mat[k][index1];
mat[k][index1] = mat[k][index2];
mat[k][index2] = temp;
}
} else {
cerr << "Invalid swap type. Use 'F' for row or 'C' for column." << endl;
}
}
Main Function for Matrix Operations
int main() {
Matrix matrix;
readMatrix(matrix);
cout << "Initial Matrix:\n";
writeMatrix(matrix);
char operationType;
int index1, index2;
cout << "Enter operation type ('F' for row swap, 'C' for column swap, or any other key to exit): ";
cin >> operationType;
while (operationType == 'F' || operationType == 'C') {
cout << "Enter two indices to swap (e.g., 0 1): ";
cin >> index1 >> index2;
swapElements(matrix, operationType, index1, index2);
cout << "\nMatrix after swap:\n";
writeMatrix(matrix);
cout << "Enter next operation type: ";
cin >> operationType;
}
cout << "Exiting matrix operations." << endl;
return 0;
}
C++ Data Structures for Ride-Sharing Application
This section defines core data structures for a hypothetical ride-sharing or vehicle rental application, including details for motorcycles, clients, and trips. It also declares global vectors to store instances of these structures.
Ride-Sharing Application Data Structures
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; struct Motorcycle { string licensePlate; double kilometers; int batteryLevel; double longitude; double latitude; char status; // e.g., 'A' for available, 'R' for rented }; struct Client { string nationalID; int monthlyMinutes; double monthlyKilometers; double monthlyFactor; int monthlyTrips; // Facilitates factor calculation }; struct Trip { int id; int date; int startTime; int endTime; string motorcyclePlate; string clientID; double distance; }; // Global vectors to store application data vector<Motorcycle> motorcycles; vector<Client> clients; vector<Trip> trips;