当前位置: 首页>>代码示例>>C++>>正文


C++ vector::erase方法代码示例

本文整理汇总了C++中std::vector::erase方法的典型用法代码示例。如果您正苦于以下问题:C++ vector::erase方法的具体用法?C++ vector::erase怎么用?C++ vector::erase使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在std::vector的用法示例。


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

示例1: solve2Quads

bool solve2Quads(const double a20, const double a02, const double a11, const double a10, const double a01, const double a00,
                const double b20, const double b02, const double b11, const double b10, const double b01, const double b00,
                std::vector<double>& E1, std::vector<double>& E2,
                bool verbose){

  // The procedure used in this function relies on a20 != 0 or b20 != 0
  if(a20 == 0. && b20 == 0.){
    
    if(a02 != 0. || b02 != 0.){
      // Swapping E1 <-> E2 should suffice!
      return solve2Quads(a02, a20, a11, a01, a10, a00,
                          b02, b20, b11, b01, b10, b00,
                          E2, E1, verbose);
    }else{
      return solve2QuadsDeg(a11, a10, a01, a00,
                            b11, b10, b01, b00,
                            E1, E2, verbose);
    }
  
  }

  const double alpha = b20*a02-a20*b02;
  const double beta = b20*a11-a20*b11;
  const double gamma = b20*a10-a20*b10;
  const double delta = b20*a01-a20*b01;
  const double omega = b20*a00-a20*b00;

  const double a = a20*SQ(alpha) + a02*SQ(beta) - a11*alpha*beta;
  const double b = 2.*a20*alpha*delta - a11*( alpha*gamma + delta*beta ) - a10*alpha*beta + 2.*a02*beta*gamma + a01*SQ(beta);
  const double c = a20*SQ(delta) + 2.*a20*alpha*omega - a11*( delta*gamma + omega*beta ) - a10*( alpha*gamma + delta*beta )
  + a02*SQ(gamma) + 2.*a01*beta*gamma + a00*SQ(beta);
  const double d = 2.*a20*delta*omega - a11*omega*gamma - a10*( delta*gamma + omega*beta ) + a01*SQ(gamma) + 2.*a00*beta*gamma;
  const double e = a20*SQ(omega) - a10*omega*gamma + a00*SQ(gamma);

  solveQuartic(a, b, c, d, e, E2, verbose);

  for(unsigned short i = 0; i < E2.size(); ++i){

    const double e2 = E2[i];
    
    if(beta*e2 + gamma != 0.){
      // Everything OK
      
      const double e1 = -(alpha * SQ(e2) + delta*e2 + omega)/(beta*e2 + gamma);
      E1.push_back(e1);
    
    }else if(alpha*SQ(e2) + delta*e2 + omega == 0.){
      // Up to two solutions for e1
      
      std::vector<double> e1;
      
      if( !solveQuadratic(a20, a11*e2 + a10, a02*SQ(e2) + a01*e2 + a00, e1, verbose) ){
        
        if( !solveQuadratic(b20, b11*e2 + b10, b02*SQ(e2) + b01*e2 + b00, e1, verbose) ){
          cout << "Error in solve2Quads: there should be at least one solution for e1!" << endl;
          E1.clear();
          E2.clear();
          return false;
        }
      
      }else{
        // We have either a double, or two roots for e1
        // In this case, e2 must be twice degenerate!
        // Since in E2 degenerate roots are grouped, E2[i+1] shoud exist and be equal to e2
        // We then go straight for i+2.
        
        if(i < E2.size() - 1){
          
          if(e2 != E2[i+1]){
            cout << "Error in solve2Quads: if there are two solutions for e1, e2 should be degenerate!" << endl;
            E1.clear();
            E2.clear();
            return false;
          }
          
          E1.push_back(e1[0]);
          E1.push_back(e1[1]);
          ++i;
          continue;
        
        }else{
          cout << "Error in solve2Quads: if there are two solutions for e1, e2 should be degenerate!" << endl;
          E1.clear();
          E2.clear();
          return false;
        }
      
      }
    
    }else{
      // There is no solution given this e2
      E2.erase(E2.begin() + i);
      --i;
    }
  
  }

  return true;
}
开发者ID:AlexandreMertens,项目名称:MEMcpp,代码行数:99,代码来源:utils.cpp

示例2: SimplifyGridPath

void Level::SimplifyGridPath(std::vector<PathFinder::SimpleNode>& path)
{
	// This function will remove nodes from a grid path to simplify the path.
	// Nodes that are directly visible to each other (the level is not obstructing view)
	// can be removed up until two nodes that can't see each other directly anylonger.
	// Nodes that are marked as unpassable on the navigation grid are also not removed.
	// This is to prevent the avatar from getting stuck at a corner.


	if (path.size() < 3)
	{
		return;
	}

	std::vector<PathFinder::SimpleNode>::iterator it = path.begin();

	while (it < (path.end() - 2))
	{
		// Check the grid-based x and y distance between this node, and the next one.
		int dX;
		int dY;

		dX = (it + 1)->x - it->x;
		dY = (it + 1)->y - it->y;

		// If it is already a diagonal-based movement, we can skip the node
		if ((std::abs(dX) == 1) && (std::abs(dY) == 1))
		{
			++it;
			continue;
		}

		// If we get here, it is not a diagonal-based movement.
		// When the node afterwards, however, is a diagonal one,
		// and no corner is in the way, then we can erase the node in between
		dX = (it + 2)->x - it->x;
		dY = (it + 2)->y - it->y;

		if ((std::abs(dX) == 1) && (std::abs(dY) == 1) &&
			m_NavigationGrid[it->y + dY][it->x] &&
			m_NavigationGrid[it->y][it->x + dX])
		{
			it = path.erase(it + 1);
		}
		else
		{
			++it;
		}
	}

	// Recurring raycast parameters
	/*DOUBLE2 intersectionRef(0, 0);
	DOUBLE2 normalRef(0, 0);
	double levelFraction = 0;
	bool levelHit = false;

	size_t currentIndex = 0;
	std::vector<PathFinder::SimpleNode>::iterator it1 = path.begin();
	while (it1 < (path.end() - 2))
	{
		DOUBLE2 rayStart = Level::GridToWorld(*it1);

		std::vector<PathFinder::SimpleNode>::iterator it2 = it1 + 1;
		while (it2 != path.end())
		{
			// First check whether the grid point is passable on the navigation grid
			if (!m_NavigationGrid[(*it2).y][(*it2).x])
			{
				break;
			}

			// Check whether the level does not obstruct the path
			DOUBLE2 rayEnd = Level::GridToWorld(*it2);
			levelHit = m_ActorLayoutPtr->Raycast(rayStart, rayEnd, intersectionRef, normalRef, levelFraction);

			if (levelHit)
			{
				break;
			}

			++it2;
		}

		// If a hit has been registered, then we can delete the nodes
		// between it1 and it2 (excluding both)
		if ((it2 - it1) > 1)
		{
			if (it2 == path.end())
			{
				path.erase(it1 + 1, it2 - 1);
			}
			else
			{
				path.erase(it1 + 1, it2);
			}

			it1 = path.begin() + currentIndex;
		}


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

示例3: path_search

int path_search()
{
	//printf("Mapping_Node Path Search Started\r\n");
	try
	{
		OPEN_LIST.clear();
		CLOSED_LIST.clear();
		PATH.clear();
		Node NewNode;
		
		/*
		double p_x = distance*sin(angle) + RoverPose.x;
			double p_y = distance*cos(angle) + RoverPose.y;
			int j = round((p_x/grid_resolution) + grid_width/2.0)-1;
			int i = round((p_y/grid_resolution) + grid_height/2.0)-1;
		*/
		NewNode.x = RoverPose.x;
		NewNode.y = RoverPose.y;
		NewNode.i = round((NewNode.y/grid_resolution) + grid_height/2.0)-1;
		NewNode.j = round((NewNode.x/grid_resolution) + grid_width/2.0)-1;
		NewNode.ID = (NewNode.i*grid_width) + NewNode.j;
		NewNode.Parent_ID = -1; //No Parent here
		NewNode.f = 0.0;
		NewNode.g = 0.0;
		NewNode.h = 0.0;
		OPEN_LIST.push_back(NewNode);
		int Goal_i = round((GoalPose.y/grid_resolution) + grid_height/2.0) -1;
		int Goal_j = round((GoalPose.x/grid_resolution) + grid_width/2.0) -1;
		//int Goal_i = 80;
		//int Goal_j = 50;
		int Start_ID = NewNode.ID;
		//printf("Si: %d Sj: %d SID: %d Gi: %d Gj: %d\r\n",NewNode.i,NewNode.j,NewNode.ID,Goal_i,Goal_j);
		int iteration_counter = 0;
		int path_found = 0;
		while(OPEN_LIST.size() > 0)
		{
			//printf("\r\n\r\n\r\nI: %d OPEN:\r\n",iteration_counter);
			/*for(int l = 0; l < OPEN_LIST.size();l++)
			{
				printf(" ID: %d i: %d j: %d\r\n",OPEN_LIST.at(l).ID,OPEN_LIST.at(l).i,OPEN_LIST.at(l).j);
			}*/
			/*printf("I: %d CLOSED:\r\n",iteration_counter);
			for(int l = 0; l < CLOSED_LIST.size();l++)
			{
				printf(" ID: %d i: %d j: %d P: %d\r\n",CLOSED_LIST.at(l).ID,CLOSED_LIST.at(l).i,CLOSED_LIST.at(l).j,CLOSED_LIST.at(l).Parent_ID);
			}*/
			if(iteration_counter > (10*grid_width*grid_width))//I SEARCHED WAY TOO MANY CELLS
			{
				printf("NO PATH FOUND!\r\n");
				return 0;
			}
			//Assume the lowest f Node is the first one, and search the rest to see if there is anyone better.
			double min_f = OPEN_LIST.at(0).f;
			int index = 0;
			for(int i = 0; i < OPEN_LIST.size();i++)
			{
				if(OPEN_LIST.at(i).f < min_f) 
				{ 
					min_f = OPEN_LIST.at(i).f;
					index = i;
				}
			}
			Node q = OPEN_LIST.at(index);
			OPEN_LIST.erase(OPEN_LIST.begin()+index);
			//printf("OPEN LIST SIZE: %d\r\n",OPEN_LIST.size());
			//printf("OPENING ID: %d P: %d\r\n",q.ID,q.Parent_ID);
			std::vector<Node> SUCCESSORS;
			//Add Successors
			if((q.i == 0) || (q.i == grid_width) || (q.j == 0) || (q.j == grid_width)) 
			{ 
				//printf("Border cell, don't check this.\r\n");
				break; 
			} //Check if cell is on border.
			Node NewNode;
			//Add Successor 0
			
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j-1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 1
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 2
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i+1;
			NewNode.j = q.j+1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 3
			NewNode.Parent_ID = q.ID;
			NewNode.i = q.i;
			NewNode.j = q.j+1;
			NewNode.ID = (NewNode.i * grid_width) + NewNode.j;
			SUCCESSORS.push_back(NewNode);
			//Add Successor 4
//.........这里部分代码省略.........
开发者ID:dgitz,项目名称:icarus_rover_rc,代码行数:101,代码来源:Mapping_Node.cpp

示例4: refresh_devices

// This function is called every frame
// If between the frames there was an asyncronous connect/disconnect event
// the function will pick up on this and add the device to the viewer
void refresh_devices(std::mutex& m,
    context& ctx,
    device_changes& devices_connection_changes,
    std::vector<device>& current_connected_devices,
    std::vector<std::pair<std::string, std::string>>& device_names,
    std::vector<device_model>& device_models,
    viewer_model& viewer_model,
    std::string& error_message)
{
    event_information info({}, {});
    if (devices_connection_changes.try_get_next_changes(info))
    {
        try
        {
            auto prev_size = current_connected_devices.size();

            //Remove disconnected
            auto dev_itr = begin(current_connected_devices);
            while (dev_itr != end(current_connected_devices))
            {
                auto dev = *dev_itr;
                if (info.was_removed(dev))
                {
                    //Notify change
                    viewer_model.not_model.add_notification({ get_device_name(dev).first + " Disconnected\n",
                        0, RS2_LOG_SEVERITY_INFO, RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR });

                    viewer_model.ppf.depth_stream_active = false;

                    // Stopping post processing filter rendering thread in case of disconnection
                    viewer_model.ppf.stop();

                    //Remove from devices
                    auto dev_model_itr = std::find_if(begin(device_models), end(device_models),
                        [&](const device_model& other) { return get_device_name(other.dev) == get_device_name(dev); });

                    if (dev_model_itr != end(device_models))
                    {
                        for (auto&& s : dev_model_itr->subdevices)
                            s->streaming = false;

                        device_models.erase(dev_model_itr);
                    }
                    auto dev_name_itr = std::find(begin(device_names), end(device_names), get_device_name(dev));
                    if (dev_name_itr != end(device_names))
                        device_names.erase(dev_name_itr);

                    dev_itr = current_connected_devices.erase(dev_itr);
                    continue;
                }
                ++dev_itr;
            }

            //Add connected
            static bool initial_refresh = true;
            for (auto dev : info.get_new_devices())
            {
                auto dev_descriptor = get_device_name(dev);
                device_names.push_back(dev_descriptor);
                if (!initial_refresh)
                    viewer_model.not_model.add_notification({ dev_descriptor.first + " Connected\n",
                        0, RS2_LOG_SEVERITY_INFO, RS2_NOTIFICATION_CATEGORY_UNKNOWN_ERROR });

                current_connected_devices.push_back(dev);
                for (auto&& s : dev.query_sensors())
                {
                    s.set_notifications_callback([&, dev_descriptor](const notification& n)
                    {
                        if (n.get_category() == RS2_NOTIFICATION_CATEGORY_HARDWARE_EVENT)
                        {
                            auto data = n.get_serialized_data();
                            if (!data.empty())
                            {
                                auto dev_model_itr = std::find_if(begin(device_models), end(device_models),
                                    [&](const device_model& other) { return get_device_name(other.dev) == dev_descriptor; });

                                if (dev_model_itr == end(device_models))
                                    return;

                                dev_model_itr->handle_harware_events(data);
                            }
                        }
                        viewer_model.not_model.add_notification({ n.get_description(), n.get_timestamp(), n.get_severity(), n.get_category() });
                    });
                }

                if (device_models.size() == 0 &&
                    dev.supports(RS2_CAMERA_INFO_NAME) && std::string(dev.get_info(RS2_CAMERA_INFO_NAME)) != "Platform Camera")
                {
                    device_models.emplace_back(dev, error_message, viewer_model);
                    viewer_model.not_model.add_log(to_string() << device_models.rbegin()->dev.get_info(RS2_CAMERA_INFO_NAME) << " was selected as a default device");
                }
            }
            initial_refresh = false;
        }
        catch (const error& e)
        {
//.........这里部分代码省略.........
开发者ID:dragonNLC,项目名称:librealsense,代码行数:101,代码来源:realsense-viewer.cpp

示例5: checkAction


//.........这里部分代码省略.........
		ActionData action;
		action.hotkey = i;
		bool have_aim = false;
		slot_activated[i] = false;

		if (!slots[i]) continue;

		if (slot_enabled[i]) {
			// part two of two step activation
			if (static_cast<unsigned>(twostep_slot) == i && inpt->pressing[MAIN1] && !inpt->lock[MAIN1]) {
				have_aim = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
				inpt->lock[MAIN1] = true;
			}

			// mouse/touch click
			else if (!NO_MOUSE && slots[i]->checkClick() == ACTIVATED) {
				have_aim = false;
				slot_activated[i] = true;
				action.power = hotkeys_mod[i];

				// if a power requires a fixed target (like teleportation), break up activation into two parts
				// the first step is to mark the slot that was clicked on
				if (action.power > 0) {
					const Power &power = powers->getPower(action.power);
					if (power.starting_pos == STARTING_POS_TARGET || power.buff_teleport) {
						twostep_slot = i;
						action.power = 0;
					}
					else {
						twostep_slot = -1;
					}
				}
			}

			// joystick/keyboard action button
			else if (inpt->pressing[ACTIONBAR_USE] && static_cast<unsigned>(tablist.getCurrent()) == i) {
				have_aim = false;
				slot_activated[i] = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
			}

			// pressing hotkey
			else if (i<10 && inpt->pressing[i+BAR_1]) {
				have_aim = true;
				action.power = hotkeys_mod[i];
				twostep_slot = -1;
			}
			else if (i==10 && inpt->pressing[MAIN1] && !inpt->lock[MAIN1] && !isWithin(window_area, inpt->mouse)) {
				have_aim = true;
				action.power = hotkeys_mod[10];
				twostep_slot = -1;
			}
			else if (i==11 && inpt->pressing[MAIN2] && !inpt->lock[MAIN2] && !isWithin(window_area, inpt->mouse)) {
				have_aim = true;
				action.power = hotkeys_mod[11];
				twostep_slot = -1;
			}
		}

		// a power slot was activated
		if (action.power > 0 && static_cast<unsigned>(action.power) < powers->powers.size()) {
			const Power &power = powers->getPower(action.power);
			bool can_use_power = true;
			action.instant_item = (power.new_state == POWSTATE_INSTANT && power.requires_item > 0);

			// check if we can add this power to the action queue
			for (unsigned j=0; j<action_queue.size(); j++) {
				if (action_queue[j].hotkey == i) {
					// this power is already in the action queue, update its target
					action_queue[j].target = setTarget(have_aim, power.aim_assist);
					can_use_power = false;
					break;
				}
				else if (!action.instant_item && !action_queue[j].instant_item) {
					can_use_power = false;
					break;
				}
			}
			if (!can_use_power)
				continue;

			// set the target depending on how the power was triggered
			action.target = setTarget(have_aim, power.aim_assist);

			// add it to the queue
			action_queue.push_back(action);
		}
		else {
			// if we're not triggering an action that is currently in the queue,
			// remove it from the queue
			for (unsigned j=0; j<action_queue.size(); j++) {
				if (action_queue[j].hotkey == i)
					action_queue.erase(action_queue.begin()+j);
			}
		}
	}
}
开发者ID:mactec0,项目名称:flare-engine,代码行数:101,代码来源:MenuActionBar.cpp

示例6: configureGpu

bool configureGpu(bool use_gpu_acceleration, std::vector<int> &valid_devices, int use_all_gpus, 
  int &numBkgWorkers_gpu) {
#ifdef ION_COMPILE_CUDA
  const unsigned long long gpu_mem = 2.5 * 1024 * 1024 * 1024;

  if (!use_gpu_acceleration)
    return false;

  // Get number of GPUs in system
  int num_gpus = 0;
  cudaError_t err = cudaGetDeviceCount( &num_gpus );

  if (err != cudaSuccess) {
    printf("CUDA: No GPU device available. Defaulting to CPU only computation\n");
    return false;
  }

  if ( use_all_gpus )
  {
    // Add all GPUs to the valid device list
    for ( int dev = 0; dev < num_gpus;  dev++ )
      valid_devices.push_back(dev);
  }
  else
  {
    // Only add the highest compute devices to the compute list
    int version = 0;
    int major = 0;
    int minor = 0;
    cudaDeviceProp dev_props;

    // Iterate over GPUs to find the highest compute device
    for ( int dev = 0; dev < num_gpus;  dev++ )
    {
      cudaGetDeviceProperties( &dev_props, dev );
      if ( (dev_props.major*10) + dev_props.minor > version )
      {
        version = (dev_props.major*10) + dev_props.minor;
        major = dev_props.major;
        minor = dev_props.minor;
      }
    }

    for ( int dev = 0; dev < num_gpus;  dev++ )
    {
      cudaGetDeviceProperties(&dev_props, dev);
      if (dev_props.major == major && dev_props.minor == minor) {
        if (dev_props.totalGlobalMem > gpu_mem) {
    valid_devices.push_back(dev);
        }
      }
    } 
  }

  // Set the number of GPU workers and tell CUDA about our list of valid devices
  if (valid_devices.size() > 0) {
    numBkgWorkers_gpu = int(valid_devices.size());
    cudaSetValidDevices( &valid_devices[0], int( valid_devices.size() ) );
  }
  else {
    printf("CUDA: No GPU device available. Defaulting to CPU only computation\n");
    return false;   
  }

 
  PoissonCDFApproxMemo poiss_cache; 
  poiss_cache.Allocate (MAX_POISSON_TABLE_COL,MAX_POISSON_TABLE_ROW,POISSON_TABLE_STEP);
  poiss_cache.GenerateValues(); // fill out my table


  for(int i=valid_devices.size()-1 ; i >= 0; i--){
    try{
      //cudaSetDevice(valid_devices[i]);
      cout << "CUDA "<< valid_devices[i] << ": Creating Context and Constant memory on device with id: "<<  valid_devices[i]<< endl;
      InitConstantMemoryOnGpu(valid_devices[i],poiss_cache);
    }
    catch(cudaException &e) {
      cout << "CUDA "<< valid_devices[i] << ": Context could not be created. removing device with id: "<<  valid_devices[i] << " from valid device list" << endl;
      valid_devices.erase (valid_devices.begin()+i);
      numBkgWorkers_gpu -= 1;
      if(numBkgWorkers_gpu == 0) cout << "CUDA: no context could be created, defaulting to CPU only execution" << endl; 
    }

  }

  if(numBkgWorkers_gpu == 0) return false;

  return true;

#else
  
  return false;

#endif

}
开发者ID:GerritvanNiekerk,项目名称:TS,代码行数:96,代码来源:cudaWrapper.cpp

示例7: stripPositionalArgs

/// \brief Strips any positional args and possible argv[0] from a command-line
/// provided by the user to construct a FixedCompilationDatabase.
///
/// FixedCompilationDatabase requires a command line to be in this format as it
/// constructs the command line for each file by appending the name of the file
/// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
/// start of the command line although its value is not important as it's just
/// ignored by the Driver invoked by the ClangTool using the
/// FixedCompilationDatabase.
///
/// FIXME: This functionality should probably be made available by
/// clang::driver::Driver although what the interface should look like is not
/// clear.
///
/// \param[in] Args Args as provided by the user.
/// \return Resulting stripped command line.
///          \li true if successful.
///          \li false if \c Args cannot be used for compilation jobs (e.g.
///          contains an option like -E or -version).
static bool stripPositionalArgs(std::vector<const char *> Args,
                                std::vector<std::string> &Result) {
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  UnusedInputDiagConsumer DiagClient;
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
      &*DiagOpts, &DiagClient, false);

  // The clang executable path isn't required since the jobs the driver builds
  // will not be executed.
  std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
      /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
      Diagnostics));
  NewDriver->setCheckInputsExist(false);

  // This becomes the new argv[0]. The value is actually not important as it
  // isn't used for invoking Tools.
  Args.insert(Args.begin(), "clang-tool");

  // By adding -c, we force the driver to treat compilation as the last phase.
  // It will then issue warnings via Diagnostics about un-used options that
  // would have been used for linking. If the user provided a compiler name as
  // the original argv[0], this will be treated as a linker input thanks to
  // insertng a new argv[0] above. All un-used options get collected by
  // UnusedInputdiagConsumer and get stripped out later.
  Args.push_back("-c");

  // Put a dummy C++ file on to ensure there's at least one compile job for the
  // driver to construct. If the user specified some other argument that
  // prevents compilation, e.g. -E or something like -version, we may still end
  // up with no jobs but then this is the user's fault.
  Args.push_back("placeholder.cpp");

  // Remove -no-integrated-as; it's not used for syntax checking,
  // and it confuses targets which don't support this option.
  Args.erase(std::remove_if(Args.begin(), Args.end(),
                            MatchesAny(std::string("-no-integrated-as"))),
             Args.end());

  const std::unique_ptr<driver::Compilation> Compilation(
      NewDriver->BuildCompilation(Args));

  const driver::JobList &Jobs = Compilation->getJobs();

  CompileJobAnalyzer CompileAnalyzer;

  for (const auto &Job : Jobs) {
    if (Job.getKind() == driver::Job::CommandClass) {
      const driver::Command &Cmd = cast<driver::Command>(Job);
      // Collect only for Assemble jobs. If we do all jobs we get duplicates
      // since Link jobs point to Assemble jobs as inputs.
      if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass)
        CompileAnalyzer.run(&Cmd.getSource());
    }
  }

  if (CompileAnalyzer.Inputs.empty()) {
    // No compile jobs found.
    // FIXME: Emit a warning of some kind?
    return false;
  }

  // Remove all compilation input files from the command line. This is
  // necessary so that getCompileCommands() can construct a command line for
  // each file.
  std::vector<const char *>::iterator End = std::remove_if(
      Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));

  // Remove all inputs deemed unused for compilation.
  End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));

  // Remove the -c add above as well. It will be at the end right now.
  assert(strcmp(*(End - 1), "-c") == 0);
  --End;

  Result = std::vector<std::string>(Args.begin() + 1, End);
  return true;
}
开发者ID:marcodiiga,项目名称:clang,代码行数:97,代码来源:CompilationDatabase.cpp

示例8: find_node

// fills the vector with the k nodes from our buckets that
// are nearest to the given id.
void routing_table::find_node(node_id const& target
	, std::vector<node_entry>& l, bool include_self, int count)
{
	l.clear();
	if (count == 0) count = m_bucket_size;
	l.reserve(count);

	int bucket_index = distance_exp(m_id, target);
	bucket_t& b = m_buckets[bucket_index].first;

	// copy all nodes that hasn't failed into the target
	// vector.
	std::remove_copy_if(b.begin(), b.end(), std::back_inserter(l)
		, bind(&node_entry::fail_count, _1));
	TORRENT_ASSERT((int)l.size() <= count);

	if ((int)l.size() == count)
	{
		TORRENT_ASSERT(std::count_if(l.begin(), l.end()
			, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
		return;
	}

	// if we didn't have enough nodes in that bucket
	// we have to reply with nodes from buckets closer
	// to us. i.e. all the buckets in the range
	// [0, bucket_index) if we are to include ourself
	// or [1, bucket_index) if not.
	bucket_t tmpb;
	for (int i = include_self?0:1; i < bucket_index; ++i)
	{
		bucket_t& b = m_buckets[i].first;
		std::remove_copy_if(b.begin(), b.end(), std::back_inserter(tmpb)
			, bind(&node_entry::fail_count, _1));
	}

	std::random_shuffle(tmpb.begin(), tmpb.end());
	size_t to_copy = (std::min)(m_bucket_size - l.size()
		, tmpb.size());
	std::copy(tmpb.begin(), tmpb.begin() + to_copy
		, std::back_inserter(l));
		
	TORRENT_ASSERT((int)l.size() <= m_bucket_size);

	// return if we have enough nodes or if the bucket index
	// is the biggest index available (there are no more buckets)
	// to look in.
	if ((int)l.size() == count
		|| bucket_index == (int)m_buckets.size() - 1)
	{
		TORRENT_ASSERT(std::count_if(l.begin(), l.end()
			, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
		return;
	}

	for (size_t i = bucket_index + 1; i < m_buckets.size(); ++i)
	{
		bucket_t& b = m_buckets[i].first;
	
		std::remove_copy_if(b.begin(), b.end(), std::back_inserter(l)
			, bind(&node_entry::fail_count, _1));
		if ((int)l.size() >= count)
		{
			l.erase(l.begin() + count, l.end());
			TORRENT_ASSERT(std::count_if(l.begin(), l.end()
				, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
			return;
		}
	}
	TORRENT_ASSERT((int)l.size() == count
		|| std::distance(l.begin(), l.end()) < m_bucket_size);
	TORRENT_ASSERT((int)l.size() <= count);

	TORRENT_ASSERT(std::count_if(l.begin(), l.end()
		, boost::bind(&node_entry::fail_count, _1) != 0) == 0);
}
开发者ID:naroya,项目名称:fdm,代码行数:78,代码来源:routing_table.cpp

示例9: display

void display() {
	doIntelWarning(); // warn for possible problems with pciking on Intel graphics chipsets

	double currentTime = u_timeGet();

	// check if we should get new random dest
	if (currentTime - g_startTime > interpolationTime) {
		g_startTime = g_startTime + interpolationTime;

		// when the process has been 'asleep' for a long time, simply skip:
		if (currentTime - g_startTime > interpolationTime)
			g_startTime = currentTime;

		// start new interpolation
		copyDestToSource();
		initRandomDest();
	}

	// interpolate:
	mv::Float alpha = (mv::Float)(currentTime - g_startTime) / (mv::Float)interpolationTime;
	TRversor V = interpolateTRversor(g_sourceVersor, g_destVersor, alpha);

	// setup projection & transform for the vectors:
	glViewport(0, 0, g_viewportWidth, g_viewportHeight);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	const float screenWidth = 1600.0f;
	glLoadIdentity();
	GLpick::g_frustumWidth = 2.0 *  (double)g_viewportWidth / screenWidth;
	GLpick::g_frustumHeight = 2.0 *  (double)g_viewportHeight / screenWidth;
	glFrustum(
		-GLpick::g_frustumWidth / 2.0, GLpick::g_frustumWidth / 2.0,
		-GLpick::g_frustumHeight / 2.0, GLpick::g_frustumHeight / 2.0,
		GLpick::g_frustumNear, GLpick::g_frustumFar);
	glMatrixMode(GL_MODELVIEW);
	glTranslatef(0.0f, 0.0f, -12.0f);


	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glEnable(GL_DEPTH_TEST);
	glPolygonMode(GL_FRONT, GL_FILL);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glLineWidth(2.0f);


	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();

	rotorGLMult(g_modelRotor);

	circle C = _circle((e1^e2^no) + (e1^e2^ni));
	circle imageOfC = _circle(V * C * inverse(V));

	// draw the circle
	glColor3fm(0.0f, 0.0f, 0.0f);
	draw(imageOfC);

	// draw trail:
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	for (unsigned int i = 0; i < g_circleTrail.size(); i++) {
		float a = 0.7f * (float)i / (float)(g_circleTrail.size());

		// draw the frame
		glColor4fm(1.0f - a, 1.0f - a, 1.0f - a, a);
		draw(g_circleTrail[i]);
	}

	glDisable(GL_BLEND);

	// update the trail:
	if (((currentTime - g_prevTrailTime) / interpolationTime) > 0.15) {
		g_prevTrailTime = currentTime;
		g_circleTrail.push_back(imageOfC);

		// trim trail to length 20:
		if (g_circleTrail.size() > 20) {
			g_circleTrail.erase(g_circleTrail.begin());
		}
	}



	glPopMatrix();

/*
	glViewport(0, 0, g_viewportWidth, g_viewportHeight);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, g_viewportWidth, 0, g_viewportHeight, -100.0, 100.0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

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

示例10: renderBoard

void MainWindow::renderBoard(std::vector<MoveHistoryEntry> history, QString outFile, int removeLast, bool renderOpenTiles, bool renderFrames, bool renderPlayers, bool renderNextTile)
{
	//TODO correct backgrounds

	jcz::TileFactory tileFactory(false);
	TileImageFactory imgFactory(&tileFactory);

	QImage image;
	QPainter * painter = 0;

	RandomNextTileProvider rntp;
	HistoryProvider hp(&rntp, history, history.size() - removeLast);
	Game g(&hp, false);
	g.addPlayer(&RandomPlayer::instance);
	g.addPlayer(&RandomPlayer::instance);

	BoardGraphicsScene bgs(&tileFactory, &imgFactory);
	bgs.setRenderOpenTiles(renderOpenTiles);
	bgs.setRenderFrames(renderFrames);
	bgs.setGame(&g);
	g.addWatchingPlayer(&bgs);

	history.erase(history.end() - removeLast, history.end());
	g.newGame(Tile::BaseGame, &tileFactory, history, true);

	bgs.clearSelection();
	bgs.setSceneRect(bgs.itemsBoundingRect());

	int const spacing = 50;
	int constexpr pivScale = 4;
	QSize sceneSize = bgs.sceneRect().size().toSize();
	QSize size = sceneSize;
	QPoint offset(0, 0);
	if (renderPlayers)
	{
		QLabel remainingLabel(QString("%1 tiles left").arg(g.getTileCount() - 1));
		remainingLabel.updateGeometry();
		int nextTileType = g.getTile(hp.nextTile(&g))->tileType;

		QSize pivSize;
		for (uint p = 0; p < g.getPlayerCount(); ++p)
		{
			PlayerInfoView piv(p, &g, &imgFactory);
			piv.updateView();
			if (renderNextTile)
				piv.displayTile(g.getNextPlayer(), nextTileType);
			piv.updateGeometry();

			if (p == 0)
			{
				pivSize = piv.size() * pivScale;
				pivSize.rheight() *= g.getPlayerCount();

				QSize remSize = remainingLabel.sizeHint() * pivScale;

				size.rwidth() += pivSize.width() + spacing;
				size.rheight() = qMax(size.height(), pivSize.height() + spacing + remSize.height());

				image = QImage(size, QImage::Format_ARGB32);
				image.fill(Qt::transparent);
				painter = new QPainter(&image);
				painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);

				painter->scale(pivScale, pivScale);
			}

			piv.render(painter, offset);

			offset.ry() += piv.size().height();
		}
		offset.setX(0);
		offset.setY((pivSize.height() + spacing) / pivScale);

		remainingLabel.render(painter, offset);

		offset.setX(pivSize.width() + spacing);
		offset.setY(0);
		painter->resetTransform();
	}
	else
	{
		image = QImage(size, QImage::Format_ARGB32);
		image.fill(Qt::transparent);
		painter = new QPainter(&image);
		painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);
	}

	bgs.render(painter, QRectF(offset, size));

	image.save(outFile);

	delete painter;
}
开发者ID:TripleWhy,项目名称:Carcasum,代码行数:93,代码来源:mainwindow.cpp

示例11: UpdateStructure

int UpdateStructure(std::vector<int>& structure, int StructuringRule, double *U, int d, int d1, unsigned int n)
{
    int i,j;
    
    std::vector<double> tau(d1*d1);
    SD_Kendall_Tau_Matrix(&tau[0],U,d1,n);
    
    std::vector<double> tau1(d1);
    double Tau1;
    
    for (i=0;i<d1;i++)
    {
        for (j=0;j<d1;j++)
        {
            Tau1 = std::abs(tau[i*d1+j]);
            tau1[i] += Tau1;
        }
    }
    
    std::vector<double>::iterator Maximum;
    
    Maximum = std::max_element(tau1.begin(), tau1.end());
    int I = std::distance(tau1.begin(), Maximum);
    
    int idxI = structure[I+d-d1];
    
    structure.erase (structure.begin()+I+d-d1);
    
    structure.insert (structure.begin()+d-d1,idxI);
    switch (StructuringRule)
    {
        case 1:
        {
            tau1.resize(d1-1);
            for (j=0;j<I;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j] = Tau1;
            }
            for (j=I+1;j<d1;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j-1] = Tau1;
            }
            
            for (j=0;j<d1-2;j++)
            {
                Maximum = std::max_element(tau1.begin(), tau1.end());
                int I = std::distance(tau1.begin(), Maximum);
                
                tau1.erase(tau1.begin()+I);
                
                int idxI = structure[I+1+j];
                
                structure.erase (structure.begin()+I+1+j);
                
                structure.insert (structure.begin()+1+j,idxI);
            }
            break;
        }
        case 2:
        {
            tau1.resize(d1-1);
            for (j=0;j<I;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j] = Tau1;
            }
            for (j=I+1;j<d1;j++)
            {
                Tau1 = std::abs(tau[I*d1+j]);
                tau1[j-1] = Tau1;
            }
            
            for (j=0;j<d1-2;j++)
            {
                Maximum = std::min_element(tau1.begin(), tau1.end()); // Note that Maximum is the minimum in this case!
                int I = std::distance(tau1.begin(), Maximum);
                
                tau1.erase(tau1.begin()+I);
                
                int idxI = structure[I+1+j];
                
                structure.erase (structure.begin()+I+1+j);
                
                structure.insert (structure.begin()+1+j,idxI);
            }
            break;
        }
        case 3:
        {
            for (j=0;j<d1-2;j++)
            {
                tau1.resize(d1-1-j);
                for (i=0;i<d1-1-j;i++)
                {
                    Tau1 = std::abs(tau[(I+j)*d1+structure[i+1+j]]);
                    tau1[i] = Tau1;
                }
                Maximum = std::min_element(tau1.begin(), tau1.end()); // Note that Maximum is the minimum in this case!
//.........这里部分代码省略.........
开发者ID:freephys,项目名称:VineCopulaCPP,代码行数:101,代码来源:VineCopulaStructureSelect.cpp

示例12: trimSnapshots

static void trimSnapshots(std::vector<T> &snapshots) {
	if (snapshots.size() > MIN_SNAPSHOT_HISTORY)
		snapshots.erase(snapshots.begin(), snapshots.begin() + snapshots.size() - MIN_SNAPSHOT_HISTORY);
}
开发者ID:lostlevels,项目名称:wild-dust,代码行数:4,代码来源:Entity.cpp

示例13: eliminateMultipleNumbers

bool CEvaluationNodeNormalizer::eliminateMultipleNumbers(CEvaluationNodeOperator::SubType subType, std::vector<CEvaluationNode*>& chainNodes)
{
  // check if there are several numerical values in the operator chain and
  // evaluate those operations
  bool changed = false;

  if (chainNodes.size() > 1)
    {
      std::vector<CEvaluationNode*>::iterator it = chainNodes.begin(), endit = chainNodes.end();

      if (subType == CEvaluationNodeOperator::MULTIPLY || subType == CEvaluationNodeOperator::PLUS)
        {

          double value = (subType == CEvaluationNodeOperator::MULTIPLY) ? 1.0 : 0.0;
          CEvaluationNodeNumber* pNumberNode = NULL;
          std::vector<CEvaluationNode*> numbers;

          while (it != endit)
            {
              pNumberNode = dynamic_cast<CEvaluationNodeNumber*>(*it);

              if (pNumberNode != NULL)
                {
                  numbers.push_back(pNumberNode);

                  if (subType == CEvaluationNodeOperator::MULTIPLY)
                    {
                      value *= pNumberNode->value();
                    }
                  else
                    {
                      value += pNumberNode->value();
                    }
                }

              ++it;
            }

          if (numbers.size() > 1)
            {
              changed = true;
              it = numbers.begin(), endit = numbers.end();
              // don't delete the last one since we reset it's value
              --endit;

              while (it != endit)
                {
                  chainNodes.erase(std::find(chainNodes.begin(), chainNodes.end(), *it));
                  delete *it;
                  ++it;
                }

              std::ostringstream os;
              os << value;
              (*it)->setData(os.str());
            }
        }
    }

  return changed;
}
开发者ID:mgaldzic,项目名称:copasi_api,代码行数:61,代码来源:CEvaluationNodeNormalizer.cpp

示例14:

bool
sp_item_list_to_curves(const std::vector<SPItem*> &items, std::vector<SPItem*>& selected, std::vector<Inkscape::XML::Node*> &to_select, bool skip_all_lpeitems)
{
    bool did = false;
    for (std::vector<SPItem*>::const_iterator i = items.begin(); i != items.end(); ++i){
        SPItem *item = *i;
        g_assert(item != NULL);
        SPDocument *document = item->document;

        SPGroup *group = dynamic_cast<SPGroup *>(item);
        if ( skip_all_lpeitems &&
             dynamic_cast<SPLPEItem *>(item) && 
             !group ) // also convert objects in an SPGroup when skip_all_lpeitems is set.
        { 
            continue;
        }

        SPPath *path = dynamic_cast<SPPath *>(item);
        if (path && !path->_curve_before_lpe) {
            // remove connector attributes
            if (item->getAttribute("inkscape:connector-type") != NULL) {
                item->removeAttribute("inkscape:connection-start");
                item->removeAttribute("inkscape:connection-end");
                item->removeAttribute("inkscape:connector-type");
                item->removeAttribute("inkscape:connector-curvature");
                did = true;
            }
            continue; // already a path, and no path effect
        }

        SPBox3D *box = dynamic_cast<SPBox3D *>(item);
        if (box) {
            // convert 3D box to ordinary group of paths; replace the old element in 'selected' with the new group
            Inkscape::XML::Node *repr = box3d_convert_to_group(box)->getRepr();
            
            if (repr) {
                to_select.insert(to_select.begin(),repr);
                did = true;
                selected.erase(remove(selected.begin(), selected.end(), item), selected.end());
            }

            continue;
        }
        
        if (group) {
            group->removeAllPathEffects(true);
            std::vector<SPItem*> item_list = sp_item_group_item_list(group);
            
            std::vector<Inkscape::XML::Node*> item_to_select;
            std::vector<SPItem*> item_selected;
            
            if (sp_item_list_to_curves(item_list, item_selected, item_to_select))
                did = true;


            continue;
        }

        Inkscape::XML::Node *repr = sp_selected_item_to_curved_repr(item, 0);
        if (!repr)
            continue;

        did = true;
        selected.erase(remove(selected.begin(), selected.end(), item), selected.end());

        // remember the position of the item
        gint pos = item->getRepr()->position();
        // remember parent
        Inkscape::XML::Node *parent = item->getRepr()->parent();
        // remember id
        char const *id = item->getRepr()->attribute("id");
        // remember title
        gchar *title = item->title();
        // remember description
        gchar *desc = item->desc();
        // remember highlight color
        guint32 highlight_color = 0;
        if (item->isHighlightSet())
            highlight_color = item->highlight_color();

        // It's going to resurrect, so we delete without notifying listeners.
        item->deleteObject(false);

        // restore id
        repr->setAttribute("id", id);
        // add the new repr to the parent
        parent->appendChild(repr);
        SPObject* newObj = document->getObjectByRepr(repr);
        if (title && newObj) {
            newObj->setTitle(title);
            g_free(title);
        }
        if (desc && newObj) {
            newObj->setDesc(desc);
            g_free(desc);
        }
        if (highlight_color && newObj) {
                SP_ITEM(newObj)->setHighlightColor( highlight_color );
        }

//.........这里部分代码省略.........
开发者ID:AakashDabas,项目名称:inkscape,代码行数:101,代码来源:path-chemistry.cpp

示例15: nextToken

void nextToken()
{
  tokens.erase(tokens.begin());
}
开发者ID:skinnylover,项目名称:NTemplate,代码行数:4,代码来源:parser.cpp


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