Skip to content

Instantly share code, notes, and snippets.

@isc30
Last active Dec 9, 2018
Embed
What would you like to do?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class SparseVector
{
private:
std::vector<bool> orderVec;
std::vector<int> valueVec;
public:
void initializeFromUserInput();
void printOrderVec() const;
void printValueVec() const;
float getScalarProduct(const SparseVector& sec) const;
};
void SparseVector::initializeFromUserInput()
{
int number;
while (cin >> number)
{
if (number != 0)
{
this->valueVec.push_back(number);
this->orderVec.push_back(true);
}
else
{
this->orderVec.push_back(false);
}
}
cin.clear();
cin.ignore(255,'\n');
}
void SparseVector::printOrderVec() const
{
cout << "Order vector: ";
for (auto i : this->orderVec)
{
cout << i << ',';
}
cout << endl;
}
void SparseVector::printValueVec() const
{
cout << "Value vector: ";
for (auto i : this->valueVec)
{
cout << i << ',';
}
cout << endl;
}
float SparseVector::getScalarProduct(const SparseVector& sec) const
{
if (this->orderVec.size() != sec.orderVec.size())
{
throw "The vectors have different sizes!";
}
float sum = 0;
int iValThis = 0, iValSec = 0;
for (auto i = 0; i < this->orderVec.size(); ++i)
{
if (this->orderVec[i] && sec.orderVec[i])
{
sum += this->valueVec[iValThis] * sec.valueVec[iValSec];
}
if (this->orderVec[i]) ++iValThis;
if (sec.orderVec[i]) ++iValSec;
}
return sum;
}
void lab6()
{
cout << "Please enter the first vector!" << endl;
SparseVector sv1;
sv1.initializeFromUserInput();
sv1.printOrderVec();
sv1.printValueVec();
cout << "Please enter the second vector!" << endl;
SparseVector sv2;
sv2.initializeFromUserInput();
sv2.printOrderVec();
sv2.printValueVec();
auto scalarProduct = sv1.getScalarProduct(sv2);
cout << "The scalar product is = " << scalarProduct << endl;
}
int main()
{
try
{
lab6();
}
catch (const char* ex)
{
cerr << endl << "Exception: " << ex << endl;
}
return 0;
}
@isc30

This comment has been minimized.

Copy link
Owner Author

@isc30 isc30 commented Dec 9, 2018

  • Fix brace positioning + add some newlines for readability
  • Rename class SparseVectors to SparseVector
  • Method for initializing from user input (blocking on constructor isn't a good idea)
  • Pass constant reference to getScalarProduct instead of ptr
  • Simplify logic on getScalarProduct (simpler implementation)
  • Throw exception when vector sizes differ and display it in cerr
  • Create SparseVector variables by value instead of ptr+new (also, it was lacking delete sv1; delete sv2; )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment