fork download
  1. #include <iostream>
  2. //#include <iomanip>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. template <size_t N>
  7. class Vector { public:
  8. float Components[N];
  9. void Add(const Vector & right) {
  10. for(size_t i = 0; i < N; ++i) {
  11. Components[i] += right.Components[i];
  12. }
  13. }
  14. void Subtract(const Vector & right) {
  15. for(size_t i = 0; i < N; ++i) {
  16. Components[i] -= right.Components[i];
  17. }
  18. }
  19. float LengthSquared() const {
  20. float result = 0.0f;
  21. for(auto component : Components) {
  22. result += component * component;
  23. }
  24. return result;
  25. }
  26. float Length() const {
  27. return sqrt(LengthSquared());
  28. }
  29. };
  30.  
  31. template <size_t N>
  32. ostream & operator<<(ostream & left, const Vector<N> & right) {
  33. left<<"{";
  34. for(auto component : right.Components) {
  35. left<<component<<",";
  36. }
  37. left<<"}";
  38. return left;
  39. }
  40.  
  41. int main() {
  42. // /O2 /Oi /MACHINE:X64
  43. // MSC 1800
  44. // call 命令が含まれる箇所が
  45. // cout の部分だけにまで展開?された
  46.  
  47. Vector<3> v1 = {2.0f,3.0f,0.0f};
  48. Vector<3> v2 = {1.0f,5.0f,1.0f}; v2.Subtract(v1);
  49. Vector<3> v3 = v1; v3.Add(v2);
  50.  
  51. float l1 = v1.Length();
  52. float l2 = v2.Length();
  53. float l3 = v3.Length();
  54.  
  55. cout<<v1<<" "<<l1<<endl;
  56. cout<<v2<<" "<<l2<<endl;
  57. cout<<v3<<" "<<l3<<endl;
  58. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
{2,3,0,} 3.60555
{-1,2,1,} 2.44949
{1,5,1,} 5.19615