0% found this document useful (0 votes)
12 views3 pages

Lab 7

This document contains a C++ implementation of a templated Vector class that allows for the creation, modification, and scalar multiplication of a vector. The main function demonstrates the usage of this class by creating a vector of integers, modifying an element, and multiplying the vector by a scalar. The class includes methods for displaying the vector contents and handling out-of-bounds errors during modifications.

Uploaded by

forgeapex50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views3 pages

Lab 7

This document contains a C++ implementation of a templated Vector class that allows for the creation, modification, and scalar multiplication of a vector. The main function demonstrates the usage of this class by creating a vector of integers, modifying an element, and multiplying the vector by a scalar. The class includes methods for displaying the vector contents and handling out-of-bounds errors during modifications.

Uploaded by

forgeapex50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

#include <vector>

using namespace std;

template <typename T>

class Vector {

private:

vector<T> elements;

public:

// Constructor to create a vector of given size and optional initial value

Vector(int size, T initialValue = T()) {

elements.resize(size, initialValue);

// Modify a specific element in the vector

void modifyElement(int index, T newValue) {

if (index >= 0 && index < elements.size()) {

elements[index] = newValue;

} else {

cout << "Index out of bounds!" << endl;

// Multiply vector by a scalar value


void multiplyByScalar(T scalar) {

for (int i = 0; i < elements.size(); ++i) {

elements[i] *= scalar;

// Display the vector

void display() const {

cout << "[ ";

for (const T& element : elements) {

cout << element << " ";

cout << "]" << endl;

};

// Main function to demonstrate the class

int main() {

// Create a vector of integers with 5 elements initialized to 1

Vector<int> v(5, 1);

cout << "Initial Vector: ";

v.display();

// Modify the third element (index 2)


v.modifyElement(2, 10);

cout << "After modifying 3rd element to 10: ";

v.display();

// Multiply vector by scalar

v.multiplyByScalar(3);

cout << "After multiplying by scalar 3: ";

v.display();

return 0;

You might also like