• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Vector类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Vector的典型用法代码示例。如果您正苦于以下问题:C++ Vector类的具体用法?C++ Vector怎么用?C++ Vector使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Vector类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: MaintainEnemy

//-----------------------------------------------------------------------------
// Purpose: Think while actively tracking a target.
//-----------------------------------------------------------------------------
void CNPC_CombineCamera::ActiveThink()
{
	// Allow descended classes a chance to do something before the think function
	if (PreThink(CAMERA_ACTIVE))
		return;

	// No active target, look for suspicious characters.
	CBaseEntity *pTarget = MaintainEnemy();
	if ( !pTarget )
	{
		// Nobody suspicious. Go back to being idle.
		m_hEnemyTarget = NULL;
		EmitSound("NPC_CombineCamera.BecomeIdle");
		SetAngry(false);
		SetThink(&CNPC_CombineCamera::SearchThink);
		SetNextThink( gpGlobals->curtime );
		return;
	}

	// Examine the target until it reaches our inner radius
	if ( pTarget != m_hEnemyTarget )
	{
		Vector vecDelta = pTarget->GetAbsOrigin() - GetAbsOrigin();
		float flDist = vecDelta.Length();
		if ( (flDist < m_nInnerRadius) && FInViewCone(pTarget) )
		{
			m_OnFoundEnemy.Set(pTarget, pTarget, this);

			// If it's a citizen, it's ok. If it's the player, it's not ok.
			if ( pTarget->IsPlayer() )
			{
				SetEyeState(CAMERA_EYE_FOUND_TARGET);

				if (HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY))
				{
					SetAngry(true);
				}
				else
				{
					EmitSound("NPC_CombineCamera.Active");
				}

				m_OnFoundPlayer.Set(pTarget, pTarget, this);
				m_hEnemyTarget = pTarget;
			}
			else
			{
				SetEyeState(CAMERA_EYE_HAPPY);
				m_flEyeHappyTime = gpGlobals->curtime + 2.0;

				// Now forget about this target forever
				AddEntityRelationship( pTarget, D_NU, 99 );
			}
		}
		else
		{
			// If we get angry automatically, we get un-angry automatically
			if ( HasSpawnFlags(SF_COMBINE_CAMERA_BECOMEANGRY) && m_bAngry )
			{
				SetAngry(false);
			}
			m_hEnemyTarget = NULL;

			// We don't quite see this guy, but we sense him.
			SetEyeState(CAMERA_EYE_SEEKING_TARGET);
		}
	}

	// Update our think time
	SetNextThink( gpGlobals->curtime + 0.1f );

	TrackTarget(pTarget);
	MaintainEye();
}
开发者ID:0xFEEDC0DE64,项目名称:UltraGame,代码行数:77,代码来源:npc_combinecamera.cpp


示例2: writeUInt16

static bool writeUInt16(Vector<char>& vector, uint16_t value)
{
    uint16_t bigEndianValue = htons(value);
    return vector.tryAppend(reinterpret_cast<char*>(&bigEndianValue), sizeof(bigEndianValue));
}
开发者ID:1833183060,项目名称:wke,代码行数:5,代码来源:WOFFFileFormat.cpp


示例3: sortByPriority

void SMILTimeContainer::sortByPriority(Vector<SVGSMILElement*>& smilElements, SMILTime elapsed)
{
    if (m_documentOrderIndexesDirty)
        updateDocumentOrderIndexes();
    std::sort(smilElements.begin(), smilElements.end(), PriorityCompare(elapsed));
}
开发者ID:jiezh,项目名称:h5vcc,代码行数:6,代码来源:SMILTimeContainer.cpp


示例4: main

int main(int argc, char *argv[]){
	Network yarp;
	//Port<Bottle> armPlan;
	//Port<Bottle> armPred;
	Port armPlan;
	Port armPred;
	armPlan.open("/randArm/plan");
	armPred.open("/randArm/pred");
	bool fwCvOn = 0;
	fwCvOn = Network::connect("/randArm/plan","/fwdConv:i");
	fwCvOn *= Network::connect("/fwdConv:o","/randArm/pred");
	if (!fwCvOn){
		printf("Please run command:\n ./fwdConv --input /fwdConv:i --output /fwdConv:o");
		return 1;
	}

	const gsl_rng_type *T;
	gsl_rng *r;
	gsl_rng_env_setup();
	T = gsl_rng_default;
	r = gsl_rng_alloc(T);

	Property params;
	params.fromCommand(argc,argv);

	if (!params.check("robot")){
		fprintf(stderr, "Please specify robot name");
		fprintf(stderr, "e.g. --robot icub");
		return -1;
	}
	std::string robotName = params.find("robot").asString().c_str();
	std::string remotePorts = "/";
	remotePorts += robotName;
	remotePorts += "/";
	if (params.check("side")){
		remotePorts += params.find("side").asString().c_str();
	}
	else{
		remotePorts += "left";
	}
	remotePorts += "_arm";
	std::string localPorts = "/randArm/cmd";

	Property options;
	options.put("device", "remote_controlboard");
	options.put("local", localPorts.c_str());
	options.put("remote", remotePorts.c_str());

	PolyDriver robotDevice(options);
	if (!robotDevice.isValid()){
		printf("Device not available. Here are known devices: \n");
		printf("%s", Drivers::factory().toString().c_str());
		Network::fini();
		return 1;
	}

	IPositionControl *pos;
	IEncoders *enc;

	bool ok;
	ok = robotDevice.view(pos);
	ok = ok && robotDevice.view(enc);

	if (!ok){
		printf("Problems acquiring interfaces\n");
		return 0;
	}

	int nj = 0;
	pos->getAxes(&nj);
	Vector encoders;
	Vector command;
	Vector commandCart;
	Vector tmp;
	encoders.resize(nj);
	tmp.resize(nj);
	command.resize(nj);
	commandCart.resize(nj);

    for (int i = 0; i < nj; i++) {
         tmp[i] = 25.0;
    }
    pos->setRefAccelerations(tmp.data());

    for (int i = 0; i < nj; i++) {
        tmp[i] = 5.0;
        pos->setRefSpeed(i, tmp[i]);
    }

    command = 0;

    //set the arm joints to "middle" values
    command[0] = -45;
    command[1] = 45;
    command[2] = 0;
    command[3] = 45;
    pos->positionMove(command.data());

    bool done = false;
    while (!done){
//.........这里部分代码省略.........
开发者ID:oosuagwu,项目名称:uiuc-lar,代码行数:101,代码来源:randArmExplore.cpp


示例5: setChildren

void TextureMapperLayer::setChildren(const Vector<TextureMapperLayer*>& newChildren)
{
    removeAllChildren();
    for (size_t i = 0; i < newChildren.size(); ++i)
        addChild(newChildren[i]);
}
开发者ID:MYSHLIFE,项目名称:webkit,代码行数:6,代码来源:TextureMapperLayer.cpp


示例6: TEST_F

TEST_F(AnimationInterpolationEffectTest, MultipleInterpolations)
{
    InterpolationEffect interpolationEffect;
    interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(10), InterpolableNumber::create(15)),
        RefPtr<TimingFunction>(), 1, 2, 1, 3);
    interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(0), InterpolableNumber::create(1)),
        LinearTimingFunction::shared(), 0, 1, 0, 1);
    interpolationEffect.addInterpolation(SampleInterpolation::create(InterpolableNumber::create(1), InterpolableNumber::create(6)),
        CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease), 0.5, 1.5, 0.5, 1.5);

    Vector<RefPtr<Interpolation>> activeInterpolations;
    interpolationEffect.getActiveInterpolations(-0.5, duration, activeInterpolations);
    EXPECT_EQ(0ul, activeInterpolations.size());

    interpolationEffect.getActiveInterpolations(0, duration, activeInterpolations);
    EXPECT_EQ(1ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(0, getInterpolableNumber(activeInterpolations.at(0)));

    interpolationEffect.getActiveInterpolations(0.5, duration, activeInterpolations);
    EXPECT_EQ(2ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(0.5f, getInterpolableNumber(activeInterpolations.at(0)));
    EXPECT_FLOAT_EQ(1, getInterpolableNumber(activeInterpolations.at(1)));

    interpolationEffect.getActiveInterpolations(1, duration, activeInterpolations);
    EXPECT_EQ(2ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(10, getInterpolableNumber(activeInterpolations.at(0)));
    EXPECT_FLOAT_EQ(5.0282884f, getInterpolableNumber(activeInterpolations.at(1)));

    interpolationEffect.getActiveInterpolations(1, duration * 1000, activeInterpolations);
    EXPECT_EQ(2ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(10, getInterpolableNumber(activeInterpolations.at(0)));
    EXPECT_FLOAT_EQ(5.0120168f, getInterpolableNumber(activeInterpolations.at(1)));

    interpolationEffect.getActiveInterpolations(1.5, duration, activeInterpolations);
    EXPECT_EQ(1ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(12.5f, getInterpolableNumber(activeInterpolations.at(0)));

    interpolationEffect.getActiveInterpolations(2, duration, activeInterpolations);
    EXPECT_EQ(1ul, activeInterpolations.size());
    EXPECT_FLOAT_EQ(15, getInterpolableNumber(activeInterpolations.at(0)));
}
开发者ID:aobzhirov,项目名称:ChromiumGStreamerBackend,代码行数:41,代码来源:InterpolationEffectTest.cpp


示例7: Quaternion

	/// Construct q Quaternion from the @p real and @p imag parts
	Quaternion(T real, const Vector<T, 3>& imag)
	 : _a(real)
	 , _x(imag.x())
	 , _y(imag.y())
	 , _z(imag.z())
	{ }
开发者ID:James-Z,项目名称:oglplus,代码行数:7,代码来源:quaternion.hpp


示例8: main

void main ()
{
	
	try 
	{
		Vector<float> v;
		v.Add(10);
		v.Add(3.4);
		v.Add(6.2);
		v.Add(9.3);
		v.Add(1.8);
		v.Add(6.7);
		v.Add(1.6);
		v.Add(3.5);
		v.Add(4);
		v.Add(8.3); //10
		v.Add(7.1);
		v.Add(8.4);
		v.Add(5.3);
		v.Add(2.6);
		v.Add(3.8);
		v.Add(6.7);
		v.Add(2.5);
		v.Add(8.4);
		v.Add(2.7);
		v.Add(9.5); // 20
		v.Add(3.9);
		cout << "Should print 10...3.9: " << endl;
		cout << v << endl;

		v.Add(5);
		v.Add(2.9);
		cout << "Should print 10...2.9: " << endl;
		cout << v << endl;

		v.Remove(0);
		cout << "Should remove 10, so should print 3.4...3.9: " << endl;
		cout << v << endl;

		// Copy constructor test
		CopyTest(v);


		Vector<float> aVector;
		aVector = v;

		cout << "Should print 3.4...3.9: " << endl;
		cout << aVector << endl;
	}

	catch (string error)
	{
		cout << error << endl;
	}
	
	system("pause");
}
开发者ID:bgold09,项目名称:psu_cmpsc,代码行数:57,代码来源:main.cpp


示例9: EDITOR_DEF

bool CollisionPolygon2DEditor::forward_gui_input(const Ref<InputEvent> &p_event) {

	if (!node)
		return false;

	Ref<InputEventMouseButton> mb = p_event;

	if (mb.is_valid()) {
		Transform2D xform = canvas_item_editor->get_canvas_transform() * node->get_global_transform();

		Vector2 gpoint = mb->get_position();
		Vector2 cpoint = canvas_item_editor->get_canvas_transform().affine_inverse().xform(gpoint);
		cpoint = canvas_item_editor->snap_point(cpoint);
		cpoint = node->get_global_transform().affine_inverse().xform(cpoint);

		Vector<Vector2> poly = node->get_polygon();

		//first check if a point is to be added (segment split)
		real_t grab_threshold = EDITOR_DEF("editors/poly_editor/point_grab_radius", 8);

		switch (mode) {

			case MODE_CREATE: {

				if (mb->get_button_index() == BUTTON_LEFT && mb->is_pressed()) {

					if (!wip_active) {

						wip.clear();
						wip.push_back(cpoint);
						wip_active = true;
						edited_point_pos = cpoint;
						canvas_item_editor->get_viewport_control()->update();
						edited_point = 1;
						return true;
					} else {

						if (wip.size() > 1 && xform.xform(wip[0]).distance_to(gpoint) < grab_threshold) {
							//wip closed
							_wip_close();

							return true;
						} else {

							wip.push_back(cpoint);
							edited_point = wip.size();
							canvas_item_editor->get_viewport_control()->update();
							return true;

							//add wip point
						}
					}
				} else if (mb->get_button_index() == BUTTON_RIGHT && mb->is_pressed() && wip_active) {
					_wip_close();
				}

			} break;

			case MODE_EDIT: {

				if (mb->get_button_index() == BUTTON_LEFT) {
					if (mb->is_pressed()) {

						if (mb->get_control()) {

							if (poly.size() < 3) {

								undo_redo->create_action(TTR("Edit Poly"));
								undo_redo->add_undo_method(node, "set_polygon", poly);
								poly.push_back(cpoint);
								undo_redo->add_do_method(node, "set_polygon", poly);
								undo_redo->add_do_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->add_undo_method(canvas_item_editor->get_viewport_control(), "update");
								undo_redo->commit_action();
								return true;
							}

							//search edges
							int closest_idx = -1;
							Vector2 closest_pos;
							real_t closest_dist = 1e10;
							for (int i = 0; i < poly.size(); i++) {

								Vector2 points[2] = { xform.xform(poly[i]),
									xform.xform(poly[(i + 1) % poly.size()]) };

								Vector2 cp = Geometry::get_closest_point_to_segment_2d(gpoint, points);
								if (cp.distance_squared_to(points[0]) < CMP_EPSILON2 || cp.distance_squared_to(points[1]) < CMP_EPSILON2)
									continue; //not valid to reuse point

								real_t d = cp.distance_to(gpoint);
								if (d < closest_dist && d < grab_threshold) {
									closest_dist = d;
									closest_pos = cp;
									closest_idx = i;
								}
							}

							if (closest_idx >= 0) {

//.........这里部分代码省略.........
开发者ID:GalanCM,项目名称:godot,代码行数:101,代码来源:collision_polygon_2d_editor_plugin.cpp


示例10: normalize

Vector normalize(const Vector &v)
{
	float l = v.length();
	return v / l;
}
开发者ID:bmabey,项目名称:cs6620-raytracer,代码行数:5,代码来源:Vector.cpp


示例11: Assert

void C_Hairball::ClientThink()
{
	// Do some AI-type stuff.. move the entity around.
	//C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
	//m_vecAngles = SetAbsAngles( pPlayer->GetAbsAngles() ); // copy player angles.

	Assert( !GetMoveParent() );

	// Sophisticated AI.
	m_flCurSpinTime += gpGlobals->frametime;
	if ( m_flCurSpinTime < m_flSpinDuration )
	{
		float div = m_flCurSpinTime / m_flSpinDuration;

		QAngle angles = GetLocalAngles();

		angles.x += m_flSpinRateX * SmoothCurve( div );
		angles.y += m_flSpinRateY * SmoothCurve( div );

		SetLocalAngles( angles );
	}
	else
	{
		// Flip between stopped and starting.
		if ( fabs( m_flSpinRateX ) > 0.01f )
		{
			m_flSpinRateX = m_flSpinRateY = 0;

			m_flSpinDuration = RandomFloat( 1, 2 );
		}
		else
		{
			static float flXSpeed = 3;
			static float flYSpeed = flXSpeed * 0.1f;
			m_flSpinRateX = RandomFloat( -M_PI*flXSpeed, M_PI*flXSpeed );
			m_flSpinRateY = RandomFloat( -M_PI*flYSpeed, M_PI*flYSpeed );

			m_flSpinDuration = RandomFloat( 1, 4 );
		}

		m_flCurSpinTime = 0;
	}

	
	if ( m_flSitStillTime > 0 )
	{
		m_flSitStillTime -= gpGlobals->frametime;

		if ( m_flSitStillTime <= 0 )
		{
			// Shoot out some random lines and find the longest one.
			m_vMoveDir.Init( 1, 0, 0 );
			float flLongestFraction = 0;
			for ( int i=0; i < 15; i++ )
			{
				Vector vDir( RandomFloat( -1, 1 ), RandomFloat( -1, 1 ), RandomFloat( -1, 1 ) );
				VectorNormalize( vDir );

				trace_t trace;
				UTIL_TraceLine( GetAbsOrigin(), GetAbsOrigin() + vDir * 10000, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace );

				if ( trace.fraction != 1.0 )
				{
					if ( trace.fraction > flLongestFraction )
					{
						flLongestFraction = trace.fraction;
						m_vMoveDir = vDir;
					}
				}
			}

			m_vMoveDir *= 650; // set speed.
			m_flSitStillTime = -1; // Move in this direction..
		}
	}
	else
	{
		// Move in the specified direction.
		Vector vEnd = GetAbsOrigin() + m_vMoveDir * gpGlobals->frametime;

		trace_t trace;
		UTIL_TraceLine( GetAbsOrigin(), vEnd, MASK_SOLID, NULL, COLLISION_GROUP_NONE, &trace );

		if ( trace.fraction < 1 )
		{
			// Ok, stop moving.
			m_flSitStillTime = RandomFloat( 1, 3 );
		}
		else
		{
			SetLocalOrigin( GetLocalOrigin() + m_vMoveDir * gpGlobals->frametime );
		}
	}

	
	// Transform the base hair positions so we can lock them down.
	VMatrix mTransform;
	mTransform.SetupMatrixOrgAngles( GetLocalOrigin(), GetLocalAngles() );

	for ( int i=0; i < m_HairPositions.Count(); i++ )
//.........这里部分代码省略.........
开发者ID:1n73rf4c3,项目名称:source-sdk-2013,代码行数:101,代码来源:c_hairball.cpp


示例12: main

int main() 
{
  // Time measurement.
  TimePeriod cpu_time;
  cpu_time.tick();

  // Create coarse mesh, set Dirichlet BC, enumerate basis functions.
  Space* space = new Space(A, B, NELEM, DIR_BC_LEFT, DIR_BC_RIGHT, P_INIT, NEQ, NEQ);

  // Enumerate basis functions, info for user.
  int ndof = Space::get_num_dofs(space);
  info("ndof: %d", ndof);

  // Initialize the weak formulation.
  WeakForm wf;
  wf.add_matrix_form(jacobian);
  wf.add_vector_form(residual);

  // Initialize the FE problem.
  bool is_linear = false;
  DiscreteProblem *dp_coarse = new DiscreteProblem(&wf, space, is_linear);

  // Newton's loop on coarse mesh.
  // Fill vector coeff_vec using dof and coeffs arrays in elements.
  double *coeff_vec_coarse = new double[Space::get_num_dofs(space)];
  get_coeff_vector(space, coeff_vec_coarse);

  // Set up the solver, matrix, and rhs according to the solver selection.
  SparseMatrix* matrix_coarse = create_matrix(matrix_solver);
  Vector* rhs_coarse = create_vector(matrix_solver);
  Solver* solver_coarse = create_linear_solver(matrix_solver, matrix_coarse, rhs_coarse);

  int it = 1;
  while (1) 
  {
    // Obtain the number of degrees of freedom.
    int ndof_coarse = Space::get_num_dofs(space);

    // Assemble the Jacobian matrix and residual vector.
    dp_coarse->assemble(coeff_vec_coarse, matrix_coarse, rhs_coarse);

    // Calculate the l2-norm of residual vector.
    double res_l2_norm = get_l2_norm(rhs_coarse);

    // Info for user.
    info("---- Newton iter %d, ndof %d, res. l2 norm %g", it, Space::get_num_dofs(space), res_l2_norm);

    // If l2 norm of the residual vector is within tolerance, then quit.
    // NOTE: at least one full iteration forced
    //       here because sometimes the initial
    //       residual on fine mesh is too small.
    if(res_l2_norm < NEWTON_TOL_COARSE && it > 1) break;

    // Multiply the residual vector with -1 since the matrix 
    // equation reads J(Y^n) \deltaY^{n+1} = -F(Y^n).
    for(int i=0; i<ndof_coarse; i++) rhs_coarse->set(i, -rhs_coarse->get(i));

    // Solve the linear system.
    if(!solver_coarse->solve())
      error ("Matrix solver failed.\n");

    // Add \deltaY^{n+1} to Y^n.
    for (int i = 0; i < ndof_coarse; i++) coeff_vec_coarse[i] += solver_coarse->get_solution()[i];

    // If the maximum number of iteration has been reached, then quit.
    if (it >= NEWTON_MAX_ITER) error ("Newton method did not converge.");
    
    // Copy coefficients from vector y to elements.
    set_coeff_vector(coeff_vec_coarse, space);

    it++;
  }
  
  // Cleanup.
  delete matrix_coarse;
  delete rhs_coarse;
  delete solver_coarse;
  delete [] coeff_vec_coarse;
  delete dp_coarse;

  // DOF and CPU convergence graphs.
  SimpleGraph graph_dof_est, graph_cpu_est;
  SimpleGraph graph_dof_exact, graph_cpu_exact;

  // Adaptivity loop:
  int as = 1;
  bool done = false;
  do
  {
    info("---- Adaptivity step %d:", as); 

    // Construct globally refined reference mesh and setup reference space.
    Space* ref_space = construct_refined_space(space);

    // Initialize the FE problem.
    bool is_linear = false;
    DiscreteProblem* dp = new DiscreteProblem(&wf, ref_space, is_linear);

    // Set up the solver, matrix, and rhs according to the solver selection.
    SparseMatrix* matrix = create_matrix(matrix_solver);
//.........这里部分代码省略.........
开发者ID:andreslsuave,项目名称:hermes,代码行数:101,代码来源:main.cpp


示例13: Title

void DlgSqlExport::Run(Sql& cursor, String command, String tablename)
{
	Title(Nvl(tablename, t_("SQL query")) + t_(" export"));
	object_name <<= tablename;
	if(!cursor.Execute(command)) {
		Exclamation(NFormat(t_("Error executing [* \1%s\1]: \1%s"), command, cursor.GetLastError()));
		return;
	}
	for(int i = 0; i < cursor.GetColumns(); i++) {
		const SqlColumnInfo& sci = cursor.GetColumnInfo(i);
		String type;
		switch(sci.type) {
			case BOOL_V:
			case INT_V: type = t_("integer"); break;
			case DOUBLE_V: type = t_("real number"); break;
			case STRING_V:
			case WSTRING_V: type = t_("string"); break;
			case DATE_V: type = t_("date"); break;
			case TIME_V: type = t_("date/time"); break;
			case /*ORA_BLOB_V*/-1: type = t_("BLOB"); break;
			case /*ORA_CLOB_V*/-2: type = t_("CLOB"); break;
			default: type = FormatInt(sci.type); break;
		}
		columns.Add(sci.name, sci.type, sci.width, 1);
	}
	static String cfg;
	LoadFromString(*this, cfg);
	SyncUI();
	while(TopWindow::Run() == IDOK)
		try {
			String out_table = ~object_name;
			String delim;
			switch((int)~delimiters) {
				case DELIM_TAB: delim = "\t"; break;
				case DELIM_SEMICOLON: delim = ";"; break;
			}
			Vector<int> out;
			String colstr;
			String title;
			for(int i = 0; i < columns.GetCount(); i++)
				if(columns.Get(i, 3)) {
					out.Add(i);
					String cname = cursor.GetColumnInfo(i).name;
					colstr << (i ? ", " : "") << cname;
					if(i) title << delim;
					title << cname;
				}
			if(out.IsEmpty()) {
				throw Exc(t_("No columns selected!"));
				continue;
			}
			String rowbegin, rowend;
			int fmt = ~format;
			FileSel fsel;
			String ext;
			switch(fmt) {
				case FMT_TEXT: {
					rowend = "";
					ext = ".txt";
					fsel.Type(t_("Text files (*.txt)"), "*.txt");
					break;
				}
				case FMT_SQL: {
					if(identity_insert)
						rowbegin << "set identity_insert " << out_table << " on ";
					rowbegin << "insert into " << out_table << "(" << colstr << ") values (";
					rowend = ");";
					ext = ".sql";
					fsel.Type(t_("SQL scripts (*.sql)"), "*.sql");
					break;
				}
			}
			fsel.AllFilesType().DefaultExt(ext.Mid(1));
			if(!IsNull(recent_file))
				fsel <<= ForceExt(recent_file, ext);
			if(!fsel.ExecuteSaveAs(t_("Save export as")))
				continue;
			recent_file = ~fsel;
			FileOut fo;
			if(!fo.Open(recent_file)) {
				Exclamation(NFormat(t_("Error creating file [* \1%s\1]."), recent_file));
				continue;
			}
			if(fmt == FMT_TEXT)
				fo.PutLine(title);
			Progress progress(t_("Exporting row %d"));
			while(cursor.Fetch()) {
				String script = rowbegin;
				for(int i = 0; i < out.GetCount(); i++) {
					Value v = cursor[out[i]];
					switch(fmt) {
						case FMT_TEXT: {
							if(i)
								script.Cat(delim);
							if(IsString(v) && quote) {
								String s = v;
								script << '\"';
								for(const char *p = s, *e = s.End(); p < e; p++)
									if(*p == '\"')
										script.Cat("\"\"");
//.........这里部分代码省略.........
开发者ID:AbdelghaniDr,项目名称:mirror,代码行数:101,代码来源:SqlObjectTree.cpp


示例14: SetDirection

void Light::SetDirection(Vector v){
	m_direction = v.d3dvector();
}
开发者ID:steve7987,项目名称:Stick,代码行数:3,代码来源:light.cpp


示例15: check

double RootMeanSquaredError::calculate_performance(const Vector<double>& parameters) const
{
   // Control sentence (if debug)

   #ifdef __OPENNN_DEBUG__ 
   
   check();

   #endif

   #ifdef __OPENNN_DEBUG__ 

   std::ostringstream buffer;

   const size_t size = parameters.size();

   const size_t parameters_number = neural_network_pointer->count_parameters_number();

   if(size != parameters_number)
   {
      buffer << "OpenNN Exception: RootMeanSquaredError class.\n"
             << "double calculate_performance(const Vector<double>&) const method.\n"
             << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n";

      throw std::logic_error(buffer.str());	  
   }

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const size_t inputs_number = multilayer_perceptron_pointer->get_inputs_number();
   const size_t outputs_number = multilayer_perceptron_pointer->get_outputs_number();

   // Data set stuff

   const Instances& instances = data_set_pointer->get_instances();

   const size_t training_instances_number = instances.count_training_instances_number();

   const Vector<size_t> training_indices = instances.arrange_training_indices();

   size_t training_index;

   const Variables& variables = data_set_pointer->get_variables();

   const Vector<size_t> inputs_indices = variables.arrange_inputs_indices();
   const Vector<size_t> targets_indices = variables.arrange_targets_indices();

   // Root mean squared error

   Vector<double> inputs(inputs_number);
   Vector<double> outputs(outputs_number);
   Vector<double> targets(outputs_number);

   double sum_squared_error = 0.0;

   int i = 0;

   #pragma omp parallel for private(i, training_index, inputs, outputs, targets) reduction(+:sum_squared_error)

   for(i = 0; i < (int)training_instances_number; i++)
   {
       training_index = training_indices[i];

      // Input vector

      inputs = data_set_pointer->get_instance(training_index, inputs_indices);

      // Output vector

      outputs = multilayer_perceptron_pointer->calculate_outputs(inputs, parameters);

      // Target vector

      targets = data_set_pointer->get_instance(training_index, targets_indices);

      // Sum squaresd error

      sum_squared_error += outputs.calculate_sum_squared_error(targets);
   }

   return(sqrt(sum_squared_error/(double)training_instances_number));
}
开发者ID:Grace,项目名称:OpenNN,代码行数:86,代码来源:root_mean_squared_error.cpp


示例16:

Vector::Vector(const Vector& v) :  s{v.s}, max{v.max}, elementen{new double[v.s]} {
	for(int i=0; i<v.s; i++){
		elementen[i]=v.get(i);
	}
}
开发者ID:MatthijsLasure,项目名称:InleidingProgrammeren,代码行数:5,代码来源:vector_7.cpp


示例17: sortByZOrder

void TextureMapperLayer::sortByZOrder(Vector<TextureMapperLayer* >& array)
{
    qsort(array.data(), array.size(), sizeof(TextureMapperLayer*), compareGraphicsLayersZValue);
}
开发者ID:MYSHLIFE,项目名称:webkit,代码行数:4,代码来源:TextureMapperLayer.cpp


示例18: ComputeIntersection

/**
 * Compute the intersection between the line segment and the capped cylinder.
 *
 * Site from is ALWAYS fluid
 * Site to is ALWAYS solid
 *
 * Therefore we expect exactly one intersection. Due to floating point errors,
 * we can't guarantee this. So, we search for intersections with some
 * tolerance (macro TOL) and pick the closest to fluid site (as given by the
 * parametic line coordinate t. We use a priority_queue to keep the hits in
 * order.
 */
Hit ComputeIntersection(CylinderData* cyl, std::vector<Iolet*>& iolets,
		Site& from, Site& to) {
	HitList hitList = HitList();
	/*
	 * The equation of the line segment is:
	 * x(t) = a + t (b - a)		t E (0, 1)
	 */
	Vector& n = cyl->Axis;
	double& r = cyl->Radius;
	Vector& c = cyl->Centre;
	double& h = cyl->Length;

	{
		/*
		 * The equation determining intersection with an INFINITE cylinder of
		 * radius r is:
		 * [(b-a)^2 - ((b-a).n)^2] t^2 + [2 a.(b - a) - 2 (a.n)((b-a).n)] t + [a^2 - (a.n)^2 - r^2] = 0
		 * So first compute the coefficients and then the discriminant of the eqn
		 */
		Vector a = from.Position - c;
		Vector b = to.Position - c;
		Vector b_a = b - a;

		double b_aDOTn = Vector::Dot(b_a, n);
		double aDOTn = Vector::Dot(a, n);

		double A = (b_a.GetMagnitudeSquared() - b_aDOTn * b_aDOTn);
		double B = 2. * (Vector::Dot(a, b_a) - aDOTn * b_aDOTn);
		double C = a.GetMagnitudeSquared() - aDOTn * aDOTn - r * r;

		double discriminant = B * B - 4 * A * C;

		if (discriminant < 0.) {
			// No real solutions.
		} else if (discriminant == 0) {
			// Exactly one solution, i.e. line segment just brushes the cylinder.
			// This means the line must be outside the cylinder everywhere else,
			// so we will count this as no intersection.
		} else {
			// Two real solutions. So we have two intersections between the
			// infinite line and infinite cylinder.
			// If t outside (0,1), then the intersection isn't on the line segment
			// we care about.
			std::vector<double> ts(2);
			ts[0] = (-B + std::sqrt(discriminant)) / (2 * A);
			ts[1] = (-B - std::sqrt(discriminant)) / (2 * A);
			for (std::vector<double>::iterator tIt = ts.begin(); tIt
					!= ts.end(); ++tIt) {
				double t = *tIt;
				if (t > 0. && t < 1. + TOL) {
					// Hit in part of line we care about.
					// Now check if it's on the finite cylinder. This requires that
					// x.n E (-h/2, h/2)
					double xDOTn = aDOTn + t * b_aDOTn;
					if (xDOTn >= -0.5 * h - TOL && xDOTn <= 0.5 * h + TOL) {
						// Real cylinder hit!
						Hit hit;
						hit.t = t;
						hit.pt = from.Position + b_a * t;
						hit.cellId = -1;
						hitList.push(hit);
					}
				}
			}
		}
	}
	/*
	 * Now we want to look for intersections with the capping planes.
	 */
	Vector& a = from.Position;
	Vector& b = to.Position;
	Vector b_a = b - a;
	for (std::vector<Iolet*>::iterator iIt = iolets.begin(); iIt
			!= iolets.end(); ++iIt) {
		Iolet* iolet = *iIt;
		/*
		 * Plane equation is x.p = q.p (p = plane normal, q = point on plane)
		 * Line is x = a + t(b-a)
		 */
		Vector& q = iolet->Centre;
		Vector& p = iolet->Normal;

		double t = Vector::Dot(q - a, p) / Vector::Dot(b_a, p);
		if (t > 0. && t < 1. + TOL) {
			// Intersection within the line segment. Now check within cap.
			Vector x = a + b_a * t;
			Vector x_c = x - c;
			double x_cDOTn = Vector::Dot(x_c, n);
//.........这里部分代码省略.........
开发者ID:jenshnielsen,项目名称:hemelb,代码行数:101,代码来源:CylinderGenerator.cpp


示例19: sendOutgoingMessage

bool Connection::sendOutgoingMessage(MessageID messageID, PassOwnPtr<MessageEncoder> encoder)
{
    Vector<Attachment> attachments = encoder->releaseAttachments();

    size_t numberOfPortDescriptors = 0;
    size_t numberOfOOLMemoryDescriptors = 0;
    for (size_t i = 0; i < attachments.size(); ++i) {
        Attachment::Type type = attachments[i].type();
        if (type == Attachment::MachPortType)
            numberOfPortDescriptors++;
        else if (type == Attachment::MachOOLMemoryType)
            numberOfOOLMemoryDescriptors++;
    }

    size_t messageSize = machMessageSize(encoder->bufferSize(), numberOfPortDescriptors, numberOfOOLMemoryDescriptors);
    char buffer[inlineMessageMaxSize];

    bool messageBodyIsOOL = false;
    if (messageSize > sizeof(buffer)) {
        messageBodyIsOOL = true;

        attachments.append(Attachment(encoder->buffer(), encoder->bufferSize(), MACH_MSG_VIRTUAL_COPY, false));
        numberOfOOLMemoryDescriptors++;
        messageSize = machMessageSize(0, numberOfPortDescriptors, numberOfOOLMemoryDescriptors);
    }

    bool isComplex = (numberOfPortDescriptors + numberOfOOLMemoryDescriptors > 0);

    mach_msg_header_t* header = reinterpret_cast<mach_msg_header_t*>(&buffer);
    header->msgh_bits = isComplex ? MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND | MACH_MSGH_BITS_COMPLEX, 0) : MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0);
    header->msgh_size = messageSize;
    header->msgh_remote_port = m_sendPort;
    header->msgh_local_port = MACH_PORT_NULL;
    header->msgh_id = messageID.toInt();
    if (messageBodyIsOOL)
        header->msgh_id |= MessageBodyIsOOL;

    uint8_t* messageData;

    if (isComplex) {
        mach_msg_body_t* body = reinterpret_cast<mach_msg_body_t*>(header + 1);
        body->msgh_descriptor_count = numberOfPortDescriptors + numberOfOOLMemoryDescriptors;

        uint8_t* descriptorData = reinterpret_cast<uint8_t*>(body + 1);
        for (size_t i = 0; i < attachments.size(); ++i) {
            Attachment attachment = attachments[i];

            mach_msg_descriptor_t* descriptor = reinterpret_cast<mach_msg_descriptor_t*>(descriptorData);
            switch (attachment.type()) {
            case Attachment::MachPortType:
                descriptor->port.name = attachment.port();
                descriptor->port.disposition = attachment.disposition();
                descriptor->port.type = MACH_MSG_PORT_DESCRIPTOR;

                descriptorData += sizeof(mach_msg_port_descriptor_t);
                break;
            case Attachment::MachOOLMemoryType:
                descriptor->out_of_line.address = attachment.address();
                descriptor->out_of_line.size = attachment.size();
                descriptor->out_of_line.copy = attachment.copyOptions();
                descriptor->out_of_line.deallocate = attachment.deallocate();
                descriptor->out_of_line.type = MACH_MSG_OOL_DESCRIPTOR;

                descriptorData += sizeof(mach_msg_ool_descriptor_t);
                break;
            default:
                ASSERT_NOT_REACHED();
            }
        }

        messageData = descriptorData;
    } else
        messageData = (uint8_t*)(header + 1);

    // Copy the data if it is not being sent out-of-line.
    if (!messageBodyIsOOL)
        memcpy(messageData, encoder->buffer(), encoder->bufferSize());

    ASSERT(m_sendPort);

    // Send the message.
    kern_return_t kr = mach_msg(header, MACH_SEND_MSG, messageSize, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
    if (kr != KERN_SUCCESS) {
        // FIXME: What should we do here?
    }

    return true;
}
开发者ID:jiezh,项目名称:h5vcc,代码行数:88,代码来源:ConnectionMac.cpp


示例20: SpotlightCreate

//------------------------------------------------------------------------------
// Purpose : Update the direction and position of my spotlight
// Input   :
// Output  :
//------------------------------------------------------------------------------
void CPointSpotlight::SpotlightUpdate(void)
{
	// ---------------------------------------------------
	//  If I don't have a spotlight attempt to create one
	// ---------------------------------------------------
	if ( !m_hSpotlight )
	{
		if ( m_bSpotlightOn )
		{
			// Make the spotlight
			SpotlightCreate();
		}
		else
		{
			return;
		}
	}
	else if ( !m_bSpotlightOn )
	{
		SpotlightDestroy();
		return;
	}
	
	if ( !m_hSpotlightTarget )
	{
		DevWarning( "**Attempting to update point_spotlight but target ent is NULL\n" );
		SpotlightDestroy();
		SpotlightCreate();
		if ( !m_hSpotlightTarget )
			return;
	}

	m_vSpotlightCurrentPos = SpotlightCurrentPos();

	//  Update spotlight target velocity
	Vector vTargetDir;
	VectorSubtract( m_vSpotlightCurrentPos, m_hSpotlightTarget->GetAbsOrigin(), vTargetDir );
	float vTargetDist = vTargetDir.Length();

	// If we haven't moved at all, don't recompute
	if ( vTargetDist < 1 )
	{
		m_hSpotlightTarget->SetAbsVelocity( vec3_origin );
		return;
	}

	Vector vecNewVelocity = vTargetDir;
	VectorNormalize(vecNewVelocity);
	vecNewVelocity *= (10 * vTargetDist);

	// If a large move is requested, just jump to final spot as we probably hit a discontinuity
	if (vecNewVelocity.Length() > 200)
	{
		VectorNormalize(vecNewVelocity);
		vecNewVelocity *= 200;
		VectorNormalize(vTargetDir);
		m_hSpotlightTarget->SetAbsOrigin( m_vSpotlightCurrentPos );
	}
	m_hSpotlightTarget->SetAbsVelocity( vecNewVelocity );
	m_hSpotlightTarget->m_vSpotlightOrg = GetAbsOrigin();

	// Avoid sudden change in where beam fades out when cross disconinuities
	VectorSubtract( m_hSpotlightTarget->GetAbsOrigin(), m_hSpotlightTarget->m_vSpotlightOrg, m_hSpotlightTarget->m_vSpotlightDir );
	float flBeamLength	= VectorNormalize( m_hSpotlightTarget->m_vSpotlightDir );
	m_flSpotlightCurLength = (0.60*m_flSpotlightCurLength) + (0.4*flBeamLength);

	ComputeRenderInfo();

	//NDebugOverlay::Cross3D(GetAbsOrigin(),Vector(-5,-5,-5),Vector(5,5,5),0,255,0,true,0.1);
	//NDebugOverlay::Cross3D(m_vSpotlightCurrentPos,Vector(-5,-5,-5),Vector(5,5,5),0,255,0,true,0.1);
	//NDebugOverlay::Cross3D(m_vSpotlightTargetPos,Vector(-5,-5,-5),Vector(5,5,5),255,0,0,true,0.1);
}
开发者ID:Adidasman1,项目名称:source-sdk-2013,代码行数:77,代码来源:point_spotlight.cpp



注:本文中的Vector类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ Vector2类代码示例发布时间:2022-05-31
下一篇:
C++ Vecteur类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap