Question

28. Implement an overloaded member function of the IntVector class named assign. This version of assign passes in an array of

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//IntVector.h

#pragma once
#include<iostream>

using namespace std;

class IntVector
{
   int unsigned sz;
   int unsigned cap;
   int *data;
   void expand();
   void expand(unsigned int amount);
public:
   IntVector();
   IntVector(unsigned size);
   IntVector(unsigned size, int value);
   void assign(unsigned n, int value);
   void assign(int a[], unsigned begin, unsigned end);
   void print();
};

=============================

//IntVector.cpp

#include"IntVector.h"

IntVector::IntVector()
{
   sz=0;
   //default capacity
   cap=2;
   data=new int[cap];
}
IntVector::IntVector(unsigned size)
{
   sz = 0;
   cap = size;
   data = new int[cap];
}
IntVector::IntVector(unsigned size, int value)
{
   sz = 0;
   cap = size;
   for (int i = 0; i < size; i++)
       data[i] = value;
}
void IntVector::assign(unsigned n, int value)
{
   expand(n);
   for (int i = 0; i < n; i++)
       data[sz++] = value;
}
void IntVector::assign(int a[], unsigned begin, unsigned end)
{
   expand(end);

   for (int i = begin; i <= end; i++)
   {
       data[sz++] = a[i];
   }
}
void IntVector::expand()
{
   cap = cap*2;
   int *tmp = new int[cap];
   for (int i = 0; i < sz; i++)
   {
       tmp[i] = data[i];
   }
   data = tmp;
}
void IntVector::expand(unsigned int amount)
{
   cap = amount;
   int *tmp = new int[cap];
   for (int i = 0; i < sz; i++)
   {
       tmp[i] = data[i];
   }
   data = tmp;
}
void IntVector::print()
{
   for (int i = 0; i < sz; i++)
   {
       cout << data[i] << " ";
   }
   cout << endl;
}

================

//Main.cpp for testing

#include"IntVector.h"

int main()
{
   int iarr[] = { 1,2,3,4,5,6,7,8,9,10 };
   IntVector v;
   v.assign(iarr, 1, 5);
   //print vector
   cout << "vector is : ";
   v.print();
}

/*Output
vector is : 2 3 4 5 6
*/

Add a comment
Know the answer?
Add Answer to:
28. Implement an overloaded member function of the IntVector class named assign. This version of assign passes in an ar...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT