main.cpp

来自「斯坦福Energy211/CME211课《c++编程——地球科学科学家和工程师》」· C++ 代码 · 共 90 行

CPP
90
字号
#include <iostream>#include "vector.h"using namespace std;// This function sums the array of length doubles pointed // to by d, and then sets the first element equal to the// sum.  This function is passed a Vector object, but the// Vector class' double * conversion function is used to// allow the Vector to be treated as an ordinary arrayvoid test( double *d, int length ){	double sum = 0.0;	for ( int i = 0; i < length; i++ )		sum += d[i];	d[0] = sum;	cout << sum << endl;}int main() {		try	{		// Create empty vector		Vector v;		cout << "empty v = \n";		cout << v;			// Use , operator to add elements		v = ( v, 1.0 );		v = ( v, 2.0 );		cout << "new v = \n";		cout << v;				// test expects an array, but passing a Vector is		// allowed because it supplies a function for 		// converting to a double *		test( v, v.get_length() );		// test actually modifies the first element in the 		// array it is passed, and this change is reflected 		// in v too		cout << "updated v = \n";		cout << v;				// The function call operator is overloaded to allow		// passing a double argument, which is treated as an		// "index" into the vector that actually linearly		// interpolates between the values at the nearest		// integer indices		cout << "v(0.5) = " << v( 0.5 ) << endl;				// Add more elements		v = ( v, 3.0 );		v = ( v, 8.0 );		cout << "updated v = \n" << v;				// Extract a subvector containing 1st & 3rd elements		int p[] = { 0, 2 };		cout << "v([ 0 2 ]) = \n" << v( p, 2 );				// Create a 1-element vector from a double		Vector w = 4.0;		cout << "w = \n" << w;			// Because 3 is an int, the other Vector constructor		// is used, so an uninitialized vector of length 3		// is created		Vector z = 3;		cout << "z = \n" << z;				// Fill in elements		z[0] = -5;		z[1] = -4;		z[2] = -3;		cout << "z = \n" << z;					// Concatenate vectors using , operator		Vector x = ( v, z );		cout << "x = \n" << x;			}	catch(...) {		cout << "An exception was thrown.\n";	}		return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?