クラスを使用してC++でベクトル量を実装する
このチュートリアルでは、クラスを使用してC++でベクトル量を実装する方法を理解するためのプログラムについて説明します。
ベクトル量は、大きさと方向の両方を持つものです。ここでは、クラスを使用してそれらを実装してから、それらに対して基本的な操作を実行します。
例
#include <cmath>
#include <iostream>
using namespace std;
class Vector {
private:
int x, y, z;
//components of the Vector
public:
Vector(int x, int y, int z){
this->x = x;
this->y = y;
this->z = z;
}
Vector operator+(Vector v);
Vector operator-(Vector v);
int operator^(Vector v);
Vector operator*(Vector v);
float magnitude(){
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
}
friend ostream& operator<<(ostream& out, const Vector& v);
//outputting the vector
};
// Addition of vectors
Vector Vector::operator+(Vector v){
int x1, y1, z1;
x1 = x + v.x;
y1 = y + v.y;
z1 = z + v.z;
return Vector(x1, y1, z1);
}
// Subtraction of vectors
Vector Vector::operator-(Vector v){
int x1, y1, z1;
x1 = x - v.x;
y1 = y - v.y;
z1 = z - v.z;
return Vector(x1, y1, z1);
}
// Dot product of vectors
int Vector::operator^(Vector v){
int x1, y1, z1;
x1 = x * v.x;
y1 = y * v.y;
z1 = z * v.z;
return (x1 + y1 + z1);
}
// Cross product of vectors
Vector Vector::operator*(Vector v){
int x1, y1, z1;
x1 = y * v.z - z * v.y;
y1 = z * v.x - x * v.z;
z1 = x * v.y - y * v.x;
return Vector(x1, y1, z1);
}
ostream& operator<<(ostream& out, const Vector& v){
out << v.x << "i ";
if (v.y >= 0)
out << "+ ";
out << v.y << "j ";
if (v.z >= 0)
out << "+ ";
out << v.z << "k" << endl;
return out;
}
int main(){
Vector V1(3, 4, 2), V2(6, 3, 9);
cout << "V1 = " << V1;
cout << "V2 = " << V2;
cout << "V1 + V2 = " << (V1 + V2);
cout << "Dot Product is : " << (V1 ^ V2);
cout << "Cross Product is : " << (V1 * V2);
return 0;
} 出力
V1 = 3i + 4j + 2k V2 = 6i + 3j + 9k V1 + V2 = 9i + 7j + 11k Dot Product is : 48 Cross Product is : 30i -15j -15k
-
配列を使用してスタックを実装するC++プログラム
スタックは、要素のコレクションを含む抽象的なデータ構造です。スタックはLIFOメカニズムを実装します。つまり、最後にプッシュされた要素が最初にポップアウトされます。スタック内の主要な操作のいくつかは-です。 プッシュ-これにより、データ値がスタックの最上位に追加されます。 ポップ-これにより、スタックの最上位のデータ値が削除されます ピーク-これはスタックの最上位のデータ値を返します 配列を使用してスタックを実装するプログラムは次のとおりです。 例 #include <iostream> using namespace std; int stack[100]
-
C++のローカルクラス
関数内で宣言されたクラスは、その関数に対してローカルであるため、C++ではローカルクラスと呼ばれます。 ローカルクラスの例を以下に示します。 #include<iostream> using namespace std; void func() { class LocalClass { }; } int main() { return 0; } 上記の例では、func()は関数であり、クラスLocalClassは関数内で定義されています。したがって、ローカルクラスとして知られています。 ローカルクラ