vector.cpp 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "vector.hpp"
  2. #include "matrix.hpp"
  3. Vector::Vector(const Vector& u){
  4. n=u.n;
  5. data=new double[n];
  6. memcpy(data,u.data,n*sizeof(double));
  7. }
  8. const Vector&
  9. Vector::operator=(const Vector& u){
  10. assert(n==u.n);
  11. memcpy(data,u.data,n*sizeof(double));
  12. return *this;
  13. }
  14. void
  15. Vector::resize(size_t _n){
  16. if(data!=nullptr){
  17. delete[] data;
  18. }
  19. n=_n;
  20. data=new double[n];
  21. }
  22. size_t
  23. Vector::argmax() const{
  24. double m=data[0];
  25. size_t res=0;
  26. for(size_t i=1;i<n;++i){
  27. double t=data[i];
  28. if(t>m){
  29. m=t;
  30. res=i;
  31. }
  32. }
  33. return res;
  34. }
  35. void
  36. Vector::softmax(){
  37. double s=0;
  38. for(size_t i=0;i<n;++i){
  39. s+=Math::exp(data[i]);
  40. }
  41. for(size_t i=0;i<n;++i){
  42. data[i]=Math::exp(data[i])/s;
  43. }
  44. }
  45. void
  46. Vector::clear(){
  47. for(size_t i=0;i<n;++i){
  48. data[i]=0;
  49. }
  50. }
  51. ostream& operator<<(ostream& os,const Vector& v){
  52. if(v.n==0) return os<<"[]";
  53. os<<'['<<v.data[0];
  54. for(size_t i=1;i<v.n;++i){
  55. os<<", "<<v.data[i];
  56. }
  57. return os<<']';
  58. }