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


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

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


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

示例1: main

int main(int argc, char* argv[]) 
{
	srand(time(NULL));
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		printf("%s\n", strerror(errno));
	}

	struct sockaddr_in servaddr;
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(11000);
	inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);

	int ret = connect(fd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr));

	if (ret == -1) {
		printf("%s", strerror(errno));
		return 0;
	}

	int epfd = epoll_create(1024);
	if (epfd == -1) {
		printf("create failed");
		return 0;
	}

	set_io_nonblock(fd, 1);

	struct epoll_event event;
	event.data.fd = fd;
	event.events = EPOLLIN | EPOLLET;
	ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
	struct epoll_event *evs = (struct epoll_event *)malloc(sizeof(struct epoll_event) * 200);	
	int done = 0;

	
	while (!done) {
		int i;
recv_again:
		int n = epoll_wait(epfd, evs, 1024, 100);
		if (n == -1 && errno != EINTR) {
			printf("%s", strerror(errno));
			return 0;
		}


		for (i = 0; i < n; ++i) {
			int fd = evs[i].data.fd;
			printf("fd=%u type=%u\n", fd, evs[i].events);
			if (evs[i].events && EPOLLIN) {
				char recvbuf[102400];
				int ret = safe_tcp_recv_n(fd, recvbuf, 102400);
				if (ret == 0) {
					printf("fd closed");
					return 0;
				} else if (ret > 0) {
					printf("recvbuf len=%d\n", ret);
					int len = ret;
					int readlen = 0;
					struct timeval end;
					struct timeval start; 
					while (readlen < len) {
						gettimeofday(&end, NULL);
						char*  ptr = recvbuf;
						proto_pkg_t *msg = (proto_pkg_t *)(ptr + readlen);
						start = seq_time_map[msg->seq];
						printf("recv: %d,%d,%d,%d,%d,%s:%lu,%lu\n", 
								msg->id, 
								msg->cmd, 
								msg->seq,
								msg->ret, 
								msg->len,
								msg->data,
								msg->len - sizeof(proto_pkg_t), 
								(end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec)
							  );
						readlen += msg->len;
						seq_time_map.erase(msg->seq);
					}
				} else {
					printf("recv error");
					return 0;
				}
			} else if (evs[i].events && EPOLLOUT) {

			}
		}
		if (seq_time_map.size()) {
			goto recv_again;
		}

		sleep(1);
		//getchar();
		char input[200] = {'\0'};
		int num = rand() % 200+ 1;
		//int num = 30;
		gen_str(input, num);
		//		scanf("%s", input);
		char buf[1024];
		for (i = 0; i < 200; ++i) {
//.........这里部分代码省略.........
开发者ID:assslove,项目名称:SimpleServer,代码行数:101,代码来源:epoll_cli.cpp

示例2: getNullValue

Value *ForExprAST::Codegen() {
  // Output this as:
  //   var = alloca double
  //   ...
  //   start = startexpr
  //   store start -> var
  //   goto loop
  // loop:
  //   ...
  //   bodyexpr
  //   ...
  // loopend:
  //   step = stepexpr
  //   endcond = endexpr
  //
  //   curvar = load var
  //   nextvar = curvar + step
  //   store nextvar -> var
  //   br endcond, loop, endloop
  // outloop:

  Function *TheFunction = Builder.GetInsertBlock()->getParent();

  // Create an alloca for the variable in the entry block.
  AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);

  // Emit the start code first, without 'variable' in scope.
  Value *StartVal = Start->Codegen();
  if (StartVal == 0) return 0;

  // Store the value into the alloca.
  Builder.CreateStore(StartVal, Alloca);

  // Make the new basic block for the loop header, inserting after current
  // block.
  BasicBlock *LoopBB = BasicBlock::Create(TheContext, "loop", TheFunction);

  // Insert an explicit fall through from the current block to the LoopBB.
  Builder.CreateBr(LoopBB);

  // Start insertion in LoopBB.
  Builder.SetInsertPoint(LoopBB);

  // Within the loop, the variable is defined equal to the PHI node.  If it
  // shadows an existing variable, we have to restore it, so save it now.
  AllocaInst *OldVal = NamedValues[VarName];
  NamedValues[VarName] = Alloca;

  // Emit the body of the loop.  This, like any other expr, can change the
  // current BB.  Note that we ignore the value computed by the body, but don't
  // allow an error.
  if (Body->Codegen() == 0)
    return 0;

  // Emit the step value.
  Value *StepVal;
  if (Step) {
    StepVal = Step->Codegen();
    if (StepVal == 0) return 0;
  } else {
    // If not specified, use 1.0.
    StepVal = ConstantFP::get(TheContext, APFloat(1.0));
  }

  // Compute the end condition.
  Value *EndCond = End->Codegen();
  if (EndCond == 0) return EndCond;

  // Reload, increment, and restore the alloca.  This handles the case where
  // the body of the loop mutates the variable.
  Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
  Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
  Builder.CreateStore(NextVar, Alloca);

  // Convert condition to a bool by comparing equal to 0.0.
  EndCond = Builder.CreateFCmpONE(
      EndCond, ConstantFP::get(TheContext, APFloat(0.0)), "loopcond");

  // Create the "after loop" block and insert it.
  BasicBlock *AfterBB =
      BasicBlock::Create(TheContext, "afterloop", TheFunction);

  // Insert the conditional branch into the end of LoopEndBB.
  Builder.CreateCondBr(EndCond, LoopBB, AfterBB);

  // Any new code will be inserted in AfterBB.
  Builder.SetInsertPoint(AfterBB);

  // Restore the unshadowed variable.
  if (OldVal)
    NamedValues[VarName] = OldVal;
  else
    NamedValues.erase(VarName);


  // for expr always returns 0.0.
  return Constant::getNullValue(Type::getDoubleTy(TheContext));
}
开发者ID:1995hnagamin,项目名称:llvm,代码行数:98,代码来源:toy.cpp

示例3: CacheBannerInternal

void BannerCache::CacheBannerInternal( std::string sBannerPath )
{
	using std::min;
	using std::max;
	std::string sError;
	RageSurface *pImage = RageSurfaceUtils::LoadFile( sBannerPath, sError );
	if( pImage == nullptr )
	{
		LOG->UserLog( "Cache file", sBannerPath, "couldn't be loaded: %s", sError.c_str() );
		return;
	}

	const int iSourceWidth = pImage->w, iSourceHeight = pImage->h;

	int iWidth = pImage->w / 2, iHeight = pImage->h / 2;
//	int iWidth = pImage->w, iHeight = pImage->h;

	/* Round to the nearest power of two.  This simplifies the actual texture load. */
	iWidth = closest( iWidth, power_of_two(iWidth), power_of_two(iWidth) / 2 );
	iHeight = closest( iHeight, power_of_two(iHeight), power_of_two(iHeight) / 2 );

	/* Don't resize the image to less than 32 pixels in either dimension or the next
	 * power of two of the source (whichever is smaller); it's already very low res. */
	iWidth = max( iWidth, min(32, power_of_two(iSourceWidth)) );
	iHeight = max( iHeight, min(32, power_of_two(iSourceHeight)) );

	//RageSurfaceUtils::ApplyHotPinkColorKey( pImage );

	RageSurfaceUtils::Zoom( pImage, iWidth, iHeight );

	/*
	 * When paletted banner cache is enabled, cached banners are paletted.  Cached
	 * 32-bit banners take 1/16 as much memory, 16-bit banners take 1/8, and paletted
	 * banners take 1/4.
	 *
	 * When paletted banner cache is disabled, cached banners are stored in 16-bit
	 * RGBA.  Cached 32-bit banners take 1/8 as much memory, cached 16-bit banners
	 * take 1/4, and cached paletted banners take 1/2.
	 *
	 * Paletted cache is disabled by default because palettization takes time, causing
	 * the initial cache run to take longer.  Also, newer ATI hardware doesn't supported
	 * paletted textures, which would slow down runtime, because we have to depalettize
	 * on use.  They'd still have the same memory benefits, though, since we only load
	 * one cached banner into a texture at once, and the speed hit may not matter on
	 * newer ATI cards.  RGBA is safer, though.
	 */
	if( g_bPalettedBannerCache )
	{
		if( pImage->fmt.BytesPerPixel != 1 )
			RageSurfaceUtils::Palettize( pImage );
	}
	else
	{
		/* Dither to the final format.  We use A1RGB5, since that's usually supported
		 * natively by both OpenGL and D3D. */
		RageSurface *dst = CreateSurface( pImage->w, pImage->h, 16,
			0x7C00, 0x03E0, 0x001F, 0x8000 );

		/* OrderedDither is still faster than ErrorDiffusionDither, and
		 * these images are very small and only displayed briefly. */
		RageSurfaceUtils::OrderedDither( pImage, dst );
		delete pImage;
		pImage = dst;
	}

	const std::string sCachePath = GetBannerCachePath(sBannerPath);
	RageSurfaceUtils::SaveSurface( pImage, sCachePath );

	/* If an old image is loaded, free it. */
	if( g_BannerPathToImage.find(sBannerPath) != g_BannerPathToImage.end() )
	{
		RageSurface *oldimg = g_BannerPathToImage[sBannerPath];
		delete oldimg;
		g_BannerPathToImage.erase(sBannerPath);
	}

	if( PREFSMAN->m_BannerCache == BNCACHE_LOW_RES_PRELOAD )
	{
		/* Keep it; we're just going to load it anyway. */
		g_BannerPathToImage[sBannerPath] = pImage;
	}
	else
		delete pImage;

	/* Remember the original size. */
	BannerData.SetValue( sBannerPath, "Path", sCachePath );
	BannerData.SetValue( sBannerPath, "Width", iSourceWidth );
	BannerData.SetValue( sBannerPath, "Height", iSourceHeight );
	BannerData.SetValue( sBannerPath, "FullHash", GetHashForFile( sBannerPath ) );
	BannerData.WriteFile( BANNER_CACHE_INDEX );
}
开发者ID:dguzek,项目名称:stepmania,代码行数:91,代码来源:BannerCache.cpp

示例4: if


//.........这里部分代码省略.........
					closeConnection(frame->header.streamIdentifier, handler);
					return true;
				}
			} else {
				headerBlockFragment += contf->headerBlockFragment;
			}
		} else {
			closeConnection(frame->header.streamIdentifier, handler);
			return true;
		}
	} else if(frame->header.type==5) {
		closeConnection(frame->header.streamIdentifier, handler);
		return true;
	} else if(frame->header.type==4) {
		Http2SettingsFrame* settingsf  = static_cast<Http2SettingsFrame*>(frame);
		//Settings Frame
		if(streamIdentifier==0) {
			settings.insert(settingsf->settings.begin(), settingsf->settings.end());
			if(!settingsf->header.flags.test(0))
			{
				Http2SettingsFrame sframe;
				sframe.header.flags.set(0);
				handler->writeData(&sframe);
				std::map<uint16_t, uint32_t>::iterator itt;
				for(itt=settings.begin();itt!=settings.end();++itt) {
					std::cout << "client_settings[" << itt->first << "] = " << itt->second << std::endl;
				}
				if(settings.find(Http2SettingsFrame::SETTINGS_MAX_FRAME_SIZE)!=settings.end()) {
					handler->updateMaxFrameSize(settings[Http2SettingsFrame::SETTINGS_MAX_FRAME_SIZE]);
				}
			}
			else if(frameAcks.find(frame->header.type)!=frameAcks.end() && frameAcks[frame->header.type])
			{
				frameAcks.erase(frame->header.type);
			}
			else
			{
				//Invalid Ack received
				closeConnection(frame->header.streamIdentifier, handler);
				return true;
			}
		} else {
			closeConnection(frame->header.streamIdentifier, handler);
			return true;
		}
	} else if(frame->header.type==6) {
		Http2PingFrame* pingf  = static_cast<Http2PingFrame*>(frame);
		//Settings Frame
		if(streamIdentifier==0) {
			if(!pingf->header.flags.test(0))
			{
				Http2PingFrame pframe;
				pframe.opaqueData = pingf->opaqueData;
				pframe.header.flags.set(0);
				handler->writeData(&pframe);
			}
			else if(frameAcks.find(frame->header.type)!=frameAcks.end() && frameAcks[frame->header.type])
			{
				frameAcks.erase(frame->header.type);
			}
			else
			{
				//Invalid Ack received
				closeConnection(frame->header.streamIdentifier, handler);
				return true;
			}
开发者ID:sumeetchhetri,项目名称:ffead-cpp,代码行数:67,代码来源:Http2StreamHandler.cpp

示例5: Update


//.........这里部分代码省略.........
			if (CDatabaseFactory::m_enumDatabaseType==OracleType)
				strColumns += (*itr1).first;
			else
				strColumns +="[" +(*itr1).first + "]";
			//值
			var.bstrVal = (*itr1).first;
			adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType();
			if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp)
			{
				switch(CDatabaseFactory::m_enumDatabaseType)
				{
				case AccessType:
					strValues += "#" + (*itr1).second + "#";
					break;
				case SqlServerType:
					strValues += "'" + (*itr1).second + "'";
					break;
				case OracleType:
					strValues += "to_date('" + (*itr1).second + "','yyyy-mm-dd')";
					break;
				}
			}
			else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) )
				strValues+=(*itr1).second;
			else
				strValues+="'"+(*itr1).second+"'";

			strSql3 = "INSERT INTO " + strTypeName + " ( " +  strColumns + " ) VALUES (" + strValues + ")";
		}
		else
		{//具体类别表存在记录
			map<_bstr_t,_bstr_t>::iterator itr1, itr2;
			_bstr_t strUpdateFormat="";
			mapFlds.erase("GUID");
			itr1 = mapFlds.begin();
			itr2 = --mapFlds.end();
			while(itr1 != itr2)
			{
				strTemp=(char *)(*itr1).first;
				if (strTemp=="ID")
				{
					itr1++;
					continue;
				}
				var.bstrVal = (*itr1).first;
				adoFldType = pRecordSet->GetFields()->GetItem(var.bstrVal)->GetType();
				if(adoFldType == ADODB::adDate || adoFldType == ADODB::adDBTimeStamp)
				{
					switch(CDatabaseFactory::m_enumDatabaseType)
					{
					case AccessType:
						strUpdateFormat +="["+ (*itr1).first + "]=#" + (*itr1).second + "#,";
						break;
					case SqlServerType:
						strUpdateFormat += "["+(*itr1).first + "]='" + (*itr1).second + "',";
						break;
					case OracleType:
						strUpdateFormat += (*itr1).first +"=to_date('" + (*itr1).second + "','yyyy-mm-dd'),";
						break;
					}
				}
				else if( (adoFldType == ADODB::adInteger ) || (adoFldType == ADODB::adNumeric) || (adoFldType == ADODB::adDouble ) )
				{
					switch(CDatabaseFactory::m_enumDatabaseType)
					{
					case AccessType:
开发者ID:siredblood,项目名称:tree-bumpkin-project,代码行数:67,代码来源:Concretion.cpp

示例6:

AlembicObjectEmitterNode::~AlembicObjectEmitterNode()
{
  gEmitterNodes.erase(gEmitterNodes.find(mRefId));
}
开发者ID:BlackGinger,项目名称:ExocortexCrate,代码行数:4,代码来源:AlembicObject.cpp

示例7: Event

void PlayHistoryTracker::Event(bz_EventData *eventData)
{
    switch (eventData->eventType)
    {
    default:
        break;

    case bz_ePlayerDieEvent:
    {
        bz_PlayerDieEventData_V1 *deathRecord = (bz_PlayerDieEventData_V1*)eventData;

        // Create variables to store the callsigns
        std::string victimCallsign = "UNKNOWN";
        std::string killerCallsign = "UNKNOWN";

        // Get player records for victim and killer
        bz_BasePlayerRecord *victimData = bz_getPlayerByIndex(deathRecord->playerID);
        bz_BasePlayerRecord *killerData = bz_getPlayerByIndex(deathRecord->killerID);

        // If we have valid data, update the callsigns
        if (victimData)
            victimCallsign = victimData->callsign.c_str();
        if (killerData)
            killerCallsign = killerData->callsign.c_str();

        // Free the player records
        bz_freePlayerRecord(victimData);
        bz_freePlayerRecord(killerData);

        // Handle the victim
        if (spreeCount.find(deathRecord->playerID) != spreeCount.end())
        {
            // Store a quick reference to their former spree count
            int spreeTotal = spreeCount[deathRecord->playerID];

            std::string message;

            // Generate an appropriate message, if any
            if (spreeTotal >= 5 && spreeTotal < 10)
                message = victimCallsign + std::string("'s rampage was stopped by ") + killerCallsign;
            else if (spreeTotal >= 10 && spreeTotal < 20)
                message = victimCallsign + std::string("'s killing spree was halted by ") + killerCallsign;
            else if (spreeTotal >= 20)
                message = std::string("The unstoppable reign of ") + victimCallsign + std::string(" was ended by ") + killerCallsign;

            // If we have a message to send, then send it
            if (message.size())
                bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());

            // Since they died, release their spree counter
            spreeCount[deathRecord->playerID] = 0;
        }

        // Handle the killer (if it wasn't also the victim)
        if (deathRecord->playerID != deathRecord->killerID && spreeCount.find(deathRecord->killerID) != spreeCount.end())
        {
            // Store a quick reference to their newly incremented spree count
            int spreeTotal = ++spreeCount[deathRecord->playerID];

            std::string message;

            // Generate an appropriate message, if any
            if (spreeTotal == 5)
                message = victimCallsign + std::string(" is on a Rampage!");
            else if (spreeTotal == 10)
                message = victimCallsign + std::string(" is on a Killing Spree!");
            else if (spreeTotal == 20)
                message = victimCallsign + std::string(" is Unstoppable!!");
            else if (spreeTotal > 20 && spreeTotal%5 == 0)
                message = victimCallsign + std::string(" continues to rage on");

            // If we have a message to send, then send it
            if (message.size())
                bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, message.c_str());
        }
    }
    break;

    case  bz_ePlayerJoinEvent:
    {
        // Initialize the spree counter for the player that just joined
        spreeCount[((bz_PlayerJoinPartEventData_V1*)eventData)->playerID] = 0;
    }
    break;

    case  bz_ePlayerPartEvent:
    {
        // Erase the spree counter for the player that just left
        std::map<int, int >::iterator itr = spreeCount.find(((bz_PlayerJoinPartEventData_V1*)eventData)->playerID);
        if (itr != spreeCount.end())
            spreeCount.erase(itr);
    }
    break;
    }
}
开发者ID:allejo,项目名称:bzflag,代码行数:95,代码来源:playHistoryTracker.cpp

示例8: update

void ChargesApp::update()
{
	mFps = getAverageFps();

	// Update device
	if ( mLeap && mLeap->isConnected() )
	{
		mLeap->update();
	}

	vector< int32_t > currentFingersIds;

	for ( const std::pair< int32_t, LeapSdk::Hand > hand : mHands )
	{
		const LeapSdk::FingerMap &fingers = hand.second.getFingers();
		for ( const auto &fkv : fingers )
		{
			int32_t id = fkv.first;
			const LeapSdk::Finger &finger = fkv.second;

			currentFingersIds.push_back( id );

			// new finger?
			if ( mActiveFingers.find( id ) == mActiveFingers.end() )
			{
				mActiveFingers[ id ] = mTimestamp;
				mEffectCharge.addCursor( id, 0.f, 0.f, 1.f ); // init with (0, 0), will be updated below
			}

			// update finger
			const LeapSdk::ScreenMap &screens = mLeap->getScreens();
			if ( screens.begin() != screens.end() )
			{
				mActiveFingers[ id ] = mTimestamp;

				const LeapSdk::Screen &screen = screens.begin()->second;
				Vec3f normPos;
				screen.intersects( finger, normPos, true, 1.5f ); // normalized screen coordinates with 1.5 clamp ratio
				Vec2f fingertip = normPos.xy() * Vec2f( mFbo.getSize() );

				Vec3f screenPos;
				screen.intersects( finger, screenPos, false, 1.5f ); // screen coordinates with 1.5 clamp ratio
				float d = screenPos.distance( finger.getPosition() );
				const float dMin = 50.f;
				const float dMax = 500.f;
				const float sMin = 1.f;
				const float sMax = 100.f;
				d = math< float >::clamp( d, dMin, dMax );
				float strength = lmap( d, dMin, dMax, sMax, sMin );

				mEffectCharge.updateCursor( id, fingertip.x, fingertip.y, strength );
			}
		}
	}

	// erase disappeared fingers
	int64_t disappearThr = mFingerDisapperanceThreshold * 1000000;
	for ( auto it = mActiveFingers.begin(); it != mActiveFingers.end(); )
	{
		int32_t id = it->first;
		if ( find( currentFingersIds.begin(), currentFingersIds.end(), id ) == currentFingersIds.end() )
		{
			// seen earlier than the threshold?
			if ( mTimestamp - it->second > disappearThr )
			{
				mEffectCharge.removeCursor( id );
				it = mActiveFingers.erase( it );
			}
			else
			{
				it++;
			}
		}
		else
		{
			it++;
		}
	}
}
开发者ID:gaborpapp,项目名称:apps,代码行数:79,代码来源:ChargesApp.cpp

示例9: getNullValue

// Output for-loop as:
//   ...
//   start = startexpr
//   goto loop
// loop:
//   variable = phi [start, loopheader], [nextvariable, loopend]
//   ...
//   bodyexpr
//   ...
// loopend:
//   step = stepexpr
//   nextvariable = variable + step
//   endcond = endexpr
//   br endcond, loop, endloop
// outloop:
Value *ForExprAST::codegen() {
  // Emit the start code first, without 'variable' in scope.
  Value *StartVal = Start->codegen();
  if (!StartVal)
    return nullptr;

  // Make the new basic block for the loop header, inserting after current
  // block.
  Function *TheFunction = Builder.GetInsertBlock()->getParent();
  BasicBlock *PreheaderBB = Builder.GetInsertBlock();
  BasicBlock *LoopBB =
      BasicBlock::Create(getGlobalContext(), "loop", TheFunction);

  // Insert an explicit fall through from the current block to the LoopBB.
  Builder.CreateBr(LoopBB);

  // Start insertion in LoopBB.
  Builder.SetInsertPoint(LoopBB);

  // Start the PHI node with an entry for Start.
  PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
                                        2, VarName.c_str());
  Variable->addIncoming(StartVal, PreheaderBB);

  // Within the loop, the variable is defined equal to the PHI node.  If it
  // shadows an existing variable, we have to restore it, so save it now.
  Value *OldVal = NamedValues[VarName];
  NamedValues[VarName] = Variable;

  // Emit the body of the loop.  This, like any other expr, can change the
  // current BB.  Note that we ignore the value computed by the body, but don't
  // allow an error.
  if (!Body->codegen())
    return nullptr;

  // Emit the step value.
  Value *StepVal = nullptr;
  if (Step) {
    StepVal = Step->codegen();
    if (!StepVal)
      return nullptr;
  } else {
    // If not specified, use 1.0.
    StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
  }

  Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");

  // Compute the end condition.
  Value *EndCond = End->codegen();
  if (!EndCond)
    return nullptr;

  // Convert condition to a bool by comparing equal to 0.0.
  EndCond = Builder.CreateFCmpONE(
      EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");

  // Create the "after loop" block and insert it.
  BasicBlock *LoopEndBB = Builder.GetInsertBlock();
  BasicBlock *AfterBB =
      BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);

  // Insert the conditional branch into the end of LoopEndBB.
  Builder.CreateCondBr(EndCond, LoopBB, AfterBB);

  // Any new code will be inserted in AfterBB.
  Builder.SetInsertPoint(AfterBB);

  // Add a new entry to the PHI node for the backedge.
  Variable->addIncoming(NextVar, LoopEndBB);

  // Restore the unshadowed variable.
  if (OldVal)
    NamedValues[VarName] = OldVal;
  else
    NamedValues.erase(VarName);

  // for expr always returns 0.0.
  return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
}
开发者ID:Aspirisha,项目名称:llvm,代码行数:95,代码来源:toy.cpp

示例10: GetPostManageFunction

void GetPostManageFunction()
{
	// GET / POST requests code
	curlHandleCount = 0;
	CURLMcode code = CURLM_CALL_MULTI_PERFORM;
	while (code == CURLM_CALL_MULTI_PERFORM)
	{
		code = curl_multi_perform(curlMulti, &curlHandleCount);
		/////////////////////////DEV ONLY/////////////////////////
		//if (code !=0)
		//{
		//	//requestQueue.front()->Error[1023] = '\0';
		//	printf("Perform: %d %d!!!\n", code, curlHandleCount);
		//	//printf("%s\n", requestQueue.front()->Error);
		//}
		//if (curlHandleCount !=0)
		//{
		//	requestQueue.front()->Error[1023] = '\0';
		//	printf("Perform: %d %d!!!\n", code, curlHandleCount);
		//	printf("%s\n", requestQueue.front()->Error);
		//}
		/////////////////////////DEV ONLY/////////////////////////
	}
	if ( code != CURLM_OK && curlHandleCount != 0) 
	{
		printf("Error: Something happend in perform GET/POST: %d!!!\n", code);
		//// what after error????????
	}

	CURLMsg *msg; // for picking up messages with the transfer status 
	int msgsLeft; // how many messages are left 

	std::list<InfoResultStruct> handlesInfoResult;
	while ( (msg = curl_multi_info_read(curlMulti, &msgsLeft)) ) 
	{
		if (msg->msg == CURLMSG_DONE) 
		{
			std::map<CURL *, CRequest *>::iterator f = requestMap.find(msg->easy_handle);
			f->second->SetStatusWaitingForDone();
			InfoResultStruct d = { msg->easy_handle, msg->data.result };
			handlesInfoResult.push_back(d);
		}
		if (msgsLeft == 0)
			break;
	}

	{
		std::list<InfoResultStruct>::iterator e = handlesInfoResult.end();
		std::list<InfoResultStruct>::iterator i = handlesInfoResult.begin();
		for ( ; i != e; i++ ) 
		{
			CURLcode result = i->result;
			CURL *handle = i->handle;
			std::map<CURL *, CRequest *>::iterator e = requestMap.end();
			std::map<CURL *, CRequest *>::iterator f = requestMap.find(handle);
			if ( f == e ) 
			{
				printf("REQUEST NOT FOUND FOR HANDLE %p\n", handle);
				continue;
			}

			CRequest *foundRequest = f->second;
			curl_multi_remove_handle(curlMulti, handle);
			DecrementRequestCount(foundRequest->GetMethodHttp());

			if (foundRequest->GetIsPostPush())
			{
				foundRequest->SetSuccessError(ErrorConnectionEndedByServer);
				foundRequest->SetStatusDone();
			}
			else
			{
				if ( result != CURLE_OK ) 
				{
					foundRequest->SetError(ErrorUndefineResultDone, result, curl_easy_strerror(result));
					foundRequest->SetStatusDone();
				} 
				else 
				{
					foundRequest->SetSuccess();
					foundRequest->SetStatusDone();
				}
			}
			requestMap.erase(f);
			requestQueue.remove(foundRequest);
            delete foundRequest;
		}
	}


	std::list<CRequest *>::iterator e = requestQueue.end();
	std::list<CRequest *>::iterator i = requestQueue.begin();

		// start requests which are ready GET / POST
	for ( ; i != e; i++ )
	{
			// remove canceled request
		if ( i != e && (*i)->GetRequestStatus() == RSCancel )
		{
			curl_multi_remove_handle(curlMulti, (*i)->GetCurl());
//.........这里部分代码省略.........
开发者ID:JackIrish,项目名称:ios,代码行数:101,代码来源:NetworkInterface.cpp

示例11: log_deregister_thread

void log_deregister_thread()
{
	threadid_t id = get_current_thread_id();
	log_threadnames.erase(id);
}
开发者ID:AMDmi3,项目名称:minetest,代码行数:5,代码来源:log.cpp

示例12: callback_eqemu

int callback_eqemu(libwebsocket_context *context, libwebsocket *wsi, libwebsocket_callback_reasons reason, void *user, void *in, size_t len) {
	per_session_data_eqemu *session = (per_session_data_eqemu*)user;
	switch (reason) {
	case LWS_CALLBACK_ESTABLISHED:
		session->uuid = CreateUUID();
		session->send_queue = new std::list<std::string>();
		sessions[session->uuid] = session;
		break;
	case LWS_CALLBACK_RECEIVE: {

		//recv and parse commands here
		if(len < 1)
			break;
			
		rapidjson::Document document;
		if(document.Parse((const char*)in).HasParseError()) {
			WriteWebCallResponseString(session, document, "Malformed JSON data", true, true);
			break;
		}

		std::string method;
		if(document.HasMember("method") && !document["method"].Empty() &&  document["method"].IsString()) {
			method = document["method"].GetString();
		}

		if(method.length() == 0) {
			//No function called, toss this message
			WriteWebCallResponseString(session, document, "No method specified", true);
			break;
		}
		
		int status = CheckTokenAuthorization(session);
		if (status == 0) {
			//check func call against functions that dont req auth
			if (unauthorized_methods.count(method) == 0) {
				WriteWebCallResponseString(session, document, "No suitable method found: " + method, true);
				break;
			}
			auto call_func = unauthorized_methods[method];
			call_func(session, document, method);
		}
		else if(status > 0) {
			//check func call against functions that req auth
			if (authorized_methods.count(method) == 0) {
				WriteWebCallResponseString(session, document, "No suitable method found: " + method, true);
				break;
			}
		
			//check status level
			auto iter = authorized_methods.find(method);
			if(iter->second.first > status) {
				WriteWebCallResponseString(session, document, "Method " + method + " requires status " + std::to_string((long)iter->second.first), true);
				break;
			}

			auto call_func = iter->second.second;
			call_func(session, document, method);
		}

		break;
	}
	case LWS_CALLBACK_SERVER_WRITEABLE: {
		std::vector<char> out_message;
		for (auto iter = session->send_queue->begin(); iter != session->send_queue->end(); ++iter) {
			out_message.resize((*iter).size() + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING + 1);
			memset(&out_message[0], 0, (*iter).size() + LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING + 1);
			memcpy(&out_message[LWS_SEND_BUFFER_PRE_PADDING], &(*iter)[0], (*iter).size());
			int n = libwebsocket_write(wsi, (unsigned char*)&out_message[LWS_SEND_BUFFER_PRE_PADDING], (*iter).size(), LWS_WRITE_TEXT);
			if(n < (*iter).size()) {
				return -1;
			}
		}
		session->send_queue->clear();
		break;
	}
	case LWS_CALLBACK_PROTOCOL_DESTROY:
		//clean up sessions here
		safe_delete(session->send_queue);
		break;

	case LWS_CALLBACK_CLOSED:
		//Session closed but perhaps not yet destroyed, we still don't want to track it though.
		sessions.erase(session->uuid);
		safe_delete(session->send_queue);
		session->uuid.clear();
		break;
	default:
		break;
	};
	return 0;
}
开发者ID:UnityEQ,项目名称:UnityEQServer,代码行数:91,代码来源:web_interface.cpp

示例13: merge

// delete clusters with no members, merge clusters that are close
bool Segment::merge(std::map<int, std::vector<int> > &clusterMembers, std::vector<int> &indices, int &clusters) {

    if (DEBUG) {
        printf("Merging clusters...\n");
    }

    int origClusters = clusters;

    std::vector<int> mergeTo(indices.size());
    std::vector<int> bestMerge(indices.size());
    std::vector<float> bestScore(indices.size());

    for(unsigned int i=0; i<indices.size(); ++i) {
        mergeTo[i] = i;
        bestMerge[i] = -1;
        bestScore[i] = 1;
    }

    std::map<int, std::vector<int> >::iterator i, j;
    for(i=clusterMembers.begin(); i!=clusterMembers.end(); ++i) {
        if (i->second.size() == 0) {
            continue;
        }

        int curMerge = i->first;
        float minDist = 1;

        for(j=clusterMembers.begin(); j!=clusterMembers.end(); ++j) {
            if (i==j || j->second.size() == 0) {
                continue;
            }

            float curDist = distance(visibilityVectors[indices[i->first]], visibilityVectors[indices[j->first]]);
            if (curDist < minDist) {
                minDist = curDist;
                curMerge = j->first;
                //i->second.insert(i->second.end(), j->second.begin(), j->second.end());
                //j->second.clear();
            }
        }
        bestMerge[i->first] = curMerge;
        bestScore[i->first] = minDist;
    }

    for(unsigned int k=0; k<bestMerge.size(); ++k) {

        // prevents merging into self
        if (mergeTo[bestMerge[k]] == k) {
            continue;
        }

        // 2 clusters that want to merge into each other
        if (bestMerge[k] == bestMerge[bestMerge[k]]) {
            if (k < bestMerge[k]) {
                continue;
            }
            clusterMembers[mergeTo[bestMerge[k]]].insert(clusterMembers[mergeTo[bestMerge[k]]].end(), clusterMembers[k].begin(), clusterMembers[k].end());
            clusterMembers[k].clear();

            mergeTo[k] = mergeTo[bestMerge[k]];
        } else if (bestScore[k] < MERGE_THRESH) {

            clusterMembers[mergeTo[bestMerge[k]]].insert(clusterMembers[mergeTo[bestMerge[k]]].end(), clusterMembers[k].begin(), clusterMembers[k].end());
            clusterMembers[k].clear();

            mergeTo[k] = mergeTo[bestMerge[k]];
        }
    }

    for(unsigned int k=0; k<indices.size(); ++k) {
        if (clusterMembers.count(k) > 0 && clusterMembers[k].size() == 0) {
            clusters -= clusterMembers.erase(k);
            indices[k] = -1;
        }
    }

    return origClusters != clusters;
}
开发者ID:bchoi12,项目名称:computer_vision_sp2016,代码行数:79,代码来源:segment.cpp

示例14: ss_prefix

int
fn_2D_by_2D_args_2D_count(MContext *mc, DNode *form, const char *prefix)
{
    dale::Units *units = (dale::Units*) mc->units;

    Node *n = units->top()->dnc->toNode(form);

    if (!units->top()->ctx->er->assertArgNums("fn-by-args-count", n, 0, -1)) {
        return 0;
    }

    int error_count_begin =
        units->top()->ctx->er->getErrorTypeCount(ErrorType::Error);

    std::vector<Node *> *lst = n->list;

    std::vector<Node *>::iterator iter = lst->begin();

    std::string map_key;
    std::vector<Type *> parameter_types;
    while (iter != lst->end()) {
        Type *parameter_type = FormTypeParse(units, (*iter), false, false);
        if (!parameter_type) {
            units->top()->ctx->er->popErrors(error_count_begin);
            return 0;
        }
        parameter_type->toString(&map_key);
        parameter_types.push_back(parameter_type);
        ++iter;
    }

    std::map<std::string, std::vector<std::string>*>::iterator
        b = fn_by_args.find(map_key),
        e = fn_by_args.end();
    if (b != e) {
        std::vector<std::string>* fn_by_args_list = b->second;
        delete fn_by_args_list;
        fn_by_args.erase(b);
    }

    /* For each function that exists, see if it has an instance
     * for the provided parameter types. */

    std::set<std::string> function_names;
    bool has_prefix = prefix;
    if (!prefix) {
        prefix = "";
    }
    std::string ss_prefix(prefix);
    units->top()->ctx->getFunctionNames(&function_names,
                             (has_prefix ? &ss_prefix : NULL));
    std::vector<std::string> *fn_by_args_list =
        new std::vector<std::string>;

    for (std::set<std::string>::iterator
            b = function_names.begin(),
            e = function_names.end();
            b != e;
            ++b) {
        Function *fn = units->top()->ctx->getFunction(b->c_str(), &parameter_types,
                                           NULL, NULL, 0);
        if (fn && !fn->is_macro) {
            fn_by_args_list->push_back(*b);
        }
    }

    fn_by_args.insert(
        std::pair<std::string, std::vector<std::string>*>(
            map_key,
            fn_by_args_list
        )
    );

    return (int) fn_by_args_list->size();
}
开发者ID:fabgithub,项目名称:dale,代码行数:75,代码来源:Introspection.cpp

示例15: scatter_copyin_data


//.........这里部分代码省略.........
                                BufferAddRef(buf);
                                OFFLOAD_TIMER_STOP(c_offload_target_add_buffer_refs);
                            }
                            add_ref_count(buf, 0 == m_vars[i].flags.sink_addr);
                        }
                        ptr = static_cast<char*>(buf) +
                            m_vars[i].mic_offset + m_vars[i].offset;
                    }
                    *ptr_addr = ptr;
                }
                else if (m_vars[i].flags.sink_addr) {
                    void *buf;
                    m_in.receive_data(&buf, sizeof(buf));
                    ptr = static_cast<char*>(buf) +
                          m_vars[i].mic_offset + m_vars[i].offset;
                    *ptr_addr = ptr;
                }
                break;

            default:
                LIBOFFLOAD_ERROR(c_unknown_var_type, type);
                abort();
        }
        // Release obsolete buffers for stack of persistent objects
        if (type = c_data_ptr &&
            m_vars[i].flags.is_stack_buf &&
            !m_vars[i].direction.bits &&
            m_vars[i].alloc_if &&
            m_vars[i].size != 0) {
                for (int j=0; j < m_vars[i].size; j++) {
                    void *buf;
                    m_in.receive_data(&buf, sizeof(buf));
                    BufferReleaseRef(buf);
                    ref_data.erase(buf);
                }
        }
        // Do copyin
        switch (m_vars[i].type.dst) {
            case c_data_ptr_array:
                break;
            case c_data:
            case c_void_ptr:
            case c_cean_var:
                if (m_vars[i].direction.in &&
                    !m_vars[i].flags.is_static_dstn) {
                    int64_t size;
                    int64_t disp;
                    char* ptr = m_vars[i].into ?
                                 static_cast<char*>(m_vars[i].into) :
                                 static_cast<char*>(m_vars[i].ptr);
                    if (m_vars[i].type.dst == c_cean_var) {
                        m_in.receive_data((&size), sizeof(int64_t));
                        m_in.receive_data((&disp), sizeof(int64_t));
                    }
                    else {
                        size = m_vars[i].size;
                        disp = 0;
                    }
                    m_in.receive_data(ptr + disp, size);
                }
                break;

            case c_dv:
                if (m_vars[i].direction.bits ||
                    m_vars[i].alloc_if ||
                    m_vars[i].free_if) {
开发者ID:AlexMioMio,项目名称:gcc,代码行数:67,代码来源:offload_target.cpp


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