Skip to content

Instantly share code, notes, and snippets.

@isc30
Last active December 9, 2018 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isc30/54c28e2c921ec175751779800b2a0d3a to your computer and use it in GitHub Desktop.
Save isc30/54c28e2c921ec175751779800b2a0d3a to your computer and use it in GitHub Desktop.
#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
Copy link
Author

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