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


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

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


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

示例1: getDistancesFrom

int Network::getDistancesFrom(Node* start,
		              std::map<Node*, int>& distances,
			      std::map<Node*, int>& weights,
			      std::set<Node*>& leaf_nodes,
			      int max_depth) const {
  
  //make sure the output is intialized
  distances.clear();
  weights.clear();
  leaf_nodes.clear();
  //This is a queue to keep track of the nodes doing a breadth first search
  queue<Node*> to_visit;
  distances[start] = 0;
  weights[start] = 1;
  int max_dist = 0,
      distance = 0,
      neighbor_max_dist = 0,
      weight = 1;
  to_visit.push(start);
  Node* tmp_node = 0;
  //Only go a certain depth:
  bool is_max_depth = (max_depth != -1);
  map<Node*, int>::iterator dit;
  
  while( to_visit.size() > 0 ) {
    tmp_node = to_visit.front();
    int tmp_node_distance = distances[tmp_node];
    distance = tmp_node_distance + 1;
    weight = weights[tmp_node];
    //Just stop if the distance is more than we should go
    if( is_max_depth && (distance > max_depth) ) { break; }
    neighbor_max_dist = 0;
    NeighborIterator neighit(tmp_node, _node_to_edges.find(tmp_node)->second );
    while( neighit.moveNext() ) {
      Node* n = neighit.current();
      dit = distances.find( n );
      if( dit == distances.end() ) {
	//We have not yet visited this node
	pair< map<Node*, int>::iterator, bool> result;
        result = distances.insert( pair<Node*, int>(n, distance) );
        //Update dit:
        dit = result.first;
	weights.insert( pair<Node*, int>(n, weight) );
	to_visit.push( n );
	//update the maximum
	max_dist = (max_dist < distance ) ? distance : max_dist;
      }
      else if( dit->second == distance ) {
        //There is more than one way to reach this node:
	weights[n] += weight;
      }
      //We know dit:
      if( neighbor_max_dist < dit->second ) {
        neighbor_max_dist = dit->second;
      }
    }
    /**
     * We check all the nodes at distance d before d+1 (breadth first)
     * so, once a distance is assigned it is never decreased
     * Hence, we know now the distance of all tmp_node neighbors.
     * If they are all less than or equal to distance from tmp_node,
     * then tmp_node must be a leaf node
     */
    if( neighbor_max_dist <= tmp_node_distance ) {
      leaf_nodes.insert(tmp_node);
    }
    //Remove the first element in the list
    to_visit.pop();
  }
  return max_dist; 
}
开发者ID:hseom,项目名称:netmodeler,代码行数:71,代码来源:network.cpp

示例2: add

 long add(shared_ptr<CoolProp::AbstractState> AS){
     ASlibrary.insert(std::pair<std::size_t, shared_ptr<CoolProp::AbstractState> >(this->next_handle,  AS));
     this->next_handle++;
     return next_handle-1;
 }
开发者ID:spada9,项目名称:CoolProp,代码行数:5,代码来源:CoolPropLib.cpp

示例3: getName

std::string H5Dataset::dump(std::map<haddr_t, std::string> & alreadyVisited, const unsigned int indentLevel) const
{
    std::ostringstream os;
    haddr_t addr = this->getAddr();
    std::map<haddr_t, std::string>::iterator it = alreadyVisited.find(addr);
    if (it != alreadyVisited.end())
    {
        os << H5Object::getIndentString(indentLevel) << "DATASET \"" << getName() << "\" {" << std::endl
           << H5Object::getIndentString(indentLevel + 1) << "HARDLINK \"" << it->second << "\"" << std::endl
           << H5Object::getIndentString(indentLevel) << "}" << std::endl;

        return os.str();
    }
    else
    {
        alreadyVisited.insert(std::pair<haddr_t, std::string>(addr, getCompletePath()));
    }

    const H5Type & type = const_cast<H5Dataset *>(this)->getDataType();
    const H5Dataspace & space = const_cast<H5Dataset *>(this)->getSpace();
    const H5AttributesList & attrs = const_cast<H5Dataset *>(this)->getAttributes();
    const H5Dataset::H5Layout & layout = const_cast<H5Dataset *>(this)->getLayout();

    H5Data * data = 0;

    try
    {
        data = &const_cast<H5Dataset *>(this)->getData();
    }
    catch (const H5Exception & /*e*/)
    {

    }

    os << H5Object::getIndentString(indentLevel) << "DATASET \"" << getName() << "\" {" << std::endl
       << type.dump(alreadyVisited, indentLevel + 1)
       << space.dump(alreadyVisited, indentLevel + 1)
       << layout.dump(alreadyVisited, indentLevel + 1);

    if (data)
    {
        os << data->dump(alreadyVisited, indentLevel + 1);
    }
    else
    {
        os << H5Object::getIndentString(indentLevel + 1) << _("Error in retrieving data.") << std::endl;
    }

    os << attrs.dump(alreadyVisited, indentLevel + 1)
       << H5Object::getIndentString(indentLevel) << "}" << std::endl;

    delete &type;
    delete &space;
    if (data)
    {
        delete data;
    }
    delete &attrs;
    delete &layout;

    return os.str();
}
开发者ID:ASP1234,项目名称:Scilabv5.5.2,代码行数:62,代码来源:H5Dataset.cpp

示例4: InitFilenameFilterList

void InitFilenameFilterList()
{
	if (gFilenameFiltersInited)
		return;

	gFilenameFiltersInited = true;

	gFilenameFilters.insert(std::pair<int, std::string>(0, "Base"));
	gFilenameFilters.insert(std::pair<int, std::string>(1, "Brick"));
	gFilenameFilters.insert(std::pair<int, std::string>(2, "Brush"));
	gFilenameFilters.insert(std::pair<int, std::string>(3, "Cobblestone"));
	gFilenameFilters.insert(std::pair<int, std::string>(4, "Cracked"));
	gFilenameFilters.insert(std::pair<int, std::string>(5, "Creep"));
	gFilenameFilters.insert(std::pair<int, std::string>(6, "Crop"));
	gFilenameFilters.insert(std::pair<int, std::string>(7, "Dirt"));
	gFilenameFilters.insert(std::pair<int, std::string>(8, "Fern"));
	gFilenameFilters.insert(std::pair<int, std::string>(9, "Flower"));
	gFilenameFilters.insert(std::pair<int, std::string>(10, "Footprints"));
	gFilenameFilters.insert(std::pair<int, std::string>(11, "Grass"));
	gFilenameFilters.insert(std::pair<int, std::string>(12, "Ice"));
	gFilenameFilters.insert(std::pair<int, std::string>(13, "Leaf"));
	gFilenameFilters.insert(std::pair<int, std::string>(14, "Mud"));
	gFilenameFilters.insert(std::pair<int, std::string>(15, "Moss"));
	gFilenameFilters.insert(std::pair<int, std::string>(16, "Road"));
	gFilenameFilters.insert(std::pair<int, std::string>(17, "Rock"));
	gFilenameFilters.insert(std::pair<int, std::string>(18, "Root"));
	gFilenameFilters.insert(std::pair<int, std::string>(19, "Rubble"));
	gFilenameFilters.insert(std::pair<int, std::string>(20, "Sand"));
	gFilenameFilters.insert(std::pair<int, std::string>(21, "Shore"));
	gFilenameFilters.insert(std::pair<int, std::string>(22, "Straw"));
	gFilenameFilters.insert(std::pair<int, std::string>(23, "Weed"));
}
开发者ID:Ikesters,项目名称:noggit,代码行数:32,代码来源:UITexturingGUI.cpp

示例5: solve


//.........这里部分代码省略.........
    
    for (size_t iter=0; iter< _maxIter; iter++){
	max_diff = 0;
      
// 	for(size_t row = 0 ; row < _nrows ; row++){
// 	  
//     // 	if ((! _nzd_indicator[row]) || (_trn_indicator[row]))
// 	    if (! _nzd_indicator[row])
// 		continue;
// 	    
// 	    for(size_t jj=0; jj < _Wnorm[row].size(); jj++){
// 		unsigned int col = _Wnorm[row][jj].j;
// 		double val = _Wnorm[row][jj].v;
// 		
//     // 	    if ((! _nzd_indicator[col]) || (_trn_indicator[col]))
// 		if (! _nzd_indicator[col])
// 		    continue;
// 		
// 		for(int cc=0; cc<_nClass; cc++){
// 		    (_result[row][cc]) += (val * _prev_result[col][cc]);
// 		}
// 	    }
// 	}
	
	size_t start_row=0;
	std::vector< boost::thread* > threads;
	size_t chunksz = _nrows/ncores;
	if (_nrows> (ncores*chunksz))
	    ncores++;
	for(size_t ichunk=0; ichunk < ncores; ichunk++){
	    size_t end_row = start_row + chunksz;
	    if (end_row >=_nrows)
		end_row = _nrows;
	    
	    threads.push_back(new boost::thread(&WeightMatrix_iter::solve_partial, this, start_row, end_row));
	    
	    start_row = end_row;
	}
	
// 	printf("Sync all threads \n");
	for (size_t ti=0; ti<threads.size(); ti++) 
	  (threads[ti])->join();
// 	printf("all threads done\n");
	
// 	double debug_diff=0;
// 	for(size_t row = 0 ; row < _nrows ; row++){
// 	    for(int cc=0; cc<_nClass; cc++){
// 		debug_diff += fabs(_result[row][cc] - _result_parallel[row][cc]);
// 	    }
// 	}
// 	if (debug_diff>0)
// 	    printf("Difference between serial and parallel = %f\n",debug_diff);
	
	
	
	
	
	for(size_t row = 0 ; row < _nrows ; row++){
// 	    normalize_row(_result[row]);
	    normalize_row(_result_parallel[row]);
	}
	
	
	for(size_t row = 0 ; row < _nrows ; row++){
	    if (_trn_indicator[row]){
	      continue;
	    }
	    
	    double diff=0;
	    for(int cc=0; cc<_nClass; cc++){
		diff = fabs(_prev_result[row][cc] - _result_parallel[row][cc]);
		max_diff = (max_diff>diff) ? max_diff: diff;
		
		_prev_result[row][cc] = _result_parallel[row][cc];
	    }
	}
	
	reassign_label();
	if (!(iter%10))
	  printf("max diff %.5f\n",max_diff);    
	if (max_diff<EPS)
	  break;
	
    }
    printf("max diff %.5f\n",max_diff);    
    
    for(size_t row = 0 ; row < _nrows ; row++){
	  
	if ((! _nzd_indicator[row]) || (_trn_indicator[row]))
	  continue;
	
	  
	
	if (!(vector_sum(_result_parallel[row])>0))
	    _result_parallel[row].assign(_nClass, (double)(1.0/_nClass));

	ret_result.insert(std::make_pair(row, _result_parallel[row]));
    }
    
}
开发者ID:paragt,项目名称:ActiveSpBdryLearn,代码行数:101,代码来源:weightmatrix_iter.cpp

示例6: frameDoneCallback

void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {
    completedFrames++;

    if (printFrameNumber) {
        std::chrono::time_point<std::chrono::high_resolution_clock> currentTime(std::chrono::high_resolution_clock::now());
        std::chrono::duration<double> elapsedSeconds = currentTime - lastFpsReportTime;
        if (elapsedSeconds.count() > 10) {
            hasMeaningfulFps = true;
            fps = (completedFrames - lastFpsReportFrame) / elapsedSeconds.count();
            lastFpsReportTime = currentTime;
            lastFpsReportFrame = completedFrames;
        }
    }

    if (f) {
        reorderMap.insert(std::make_pair(n, f));
        while (reorderMap.count(outputFrames)) {
            const VSFrameRef *frame = reorderMap[outputFrames];
            reorderMap.erase(outputFrames);
            if (!outputError) {
                if (y4m) {
                    if (fwrite("FRAME\n", 1, 6, outFile) != 6) {
                        if (errorMessage.empty())
                            errorMessage = "Error: fwrite() call failed when writing header, errno: " + std::to_string(errno);
                        totalFrames = requestedFrames;
                        outputError = true;
                    }
                }

                if (!outputError) {
                    const VSFormat *fi = vsapi->getFrameFormat(frame);
                    for (int p = 0; p < fi->numPlanes; p++) {
                        int stride = vsapi->getStride(frame, p);
                        const uint8_t *readPtr = vsapi->getReadPtr(frame, p);
                        int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;
                        int height = vsapi->getFrameHeight(frame, p);
                        for (int y = 0; y < height; y++) {
                            if (fwrite(readPtr, 1, rowSize, outFile) != (size_t)rowSize) {
                                if (errorMessage.empty())
                                    errorMessage = "Error: fwrite() call failed when writing frame: " + std::to_string(outputFrames) + ", plane: " + std::to_string(p) +
                                        ", line: " + std::to_string(y) + ", errno: " + std::to_string(errno);
                                totalFrames = requestedFrames;
                                outputError = true;
                                p = 100; // break out of the outer loop
                                break;
                            }
                            readPtr += stride;
                        }
                    }
                }
            }
            vsapi->freeFrame(frame);
            outputFrames++;
        }
    } else {
        outputError = true;
        totalFrames = requestedFrames;
        if (errorMessage.empty()) {
            if (errorMsg)
                errorMessage = "Error: Failed to retrieve frame " + std::to_string(n) + " with error: " + errorMsg;
            else
                errorMessage = "Error: Failed to retrieve frame " + std::to_string(n);
        }
    }

    if (requestedFrames < totalFrames) {
        vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);
        requestedFrames++;
    }

    if (printFrameNumber && !outputError) {
        if (hasMeaningfulFps)
            fprintf(stderr, "Frame: %d/%d (%.2f fps)\r", completedFrames, totalFrames, fps);
        else
            fprintf(stderr, "Frame: %d/%d\r", completedFrames, totalFrames);
    }

    if (totalFrames == completedFrames) {
        std::lock_guard<std::mutex> lock(mutex);
        condition.notify_one();
    }
}
开发者ID:adworacz,项目名称:vapoursynth,代码行数:82,代码来源:vspipe.cpp

示例7: UpdateAI


//.........这里部分代码省略.........
                        if (Creature* pGuardian = DoSummon(NPC_ICECROWN, Pos[RAND(2, 5, 8, 11)]))
                            pGuardian->SetFloatValue(UNIT_FIELD_COMBATREACH, 2);
                        ++nGuardiansOfIcecrownCount;
                        uiGuardiansOfIcecrownTimer = 5000;
                    }
                    else uiGuardiansOfIcecrownTimer -= diff;
                }

                if (me->HasUnitState(UNIT_STAT_CASTING))
                    return;

                if (uint32 eventId = events.GetEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_BOLT:
                            DoCastVictim(RAID_MODE(SPELL_FROST_BOLT, H_SPELL_FROST_BOLT));
                            events.RepeatEvent(urand(5000, 10000));
                            break;
                        case EVENT_NOVA:
                            DoCastAOE(RAID_MODE(SPELL_FROST_BOLT_AOE, H_SPELL_FROST_BOLT_AOE));
                            events.RepeatEvent(urand(15000, 30000));
                            break;
                        case EVENT_CHAIN:
                        {
                            uint32 count = urand(1, 3);
                            for (uint8 i = 1; i <= count; i++)
                            {
                                Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true);
                                if (target && !target->isCharmed() && (chained.find(target->GetGUID()) == chained.end()))
                                {
                                    DoCast(target, SPELL_CHAINS_OF_KELTHUZAD);
                                    float scale = target->GetFloatValue(OBJECT_FIELD_SCALE_X);
                                    chained.insert(std::make_pair(target->GetGUID(), scale));
                                    target->SetFloatValue(OBJECT_FIELD_SCALE_X, scale * 2);
                                    events.ScheduleEvent(EVENT_CHAINED_SPELL, 2000); //core has 2000ms to set unit flag charm
                                }
                            }
                            if (!chained.empty())
                                DoScriptText(RAND(SAY_CHAIN_1, SAY_CHAIN_2), me);
                            events.RepeatEvent(urand(100000, 180000));
                            break;
                        }
                        case EVENT_CHAINED_SPELL:
                        {
                            std::map<uint64, float>::iterator itr;
                            for (itr = chained.begin(); itr != chained.end();)
                            {
                                if (Unit* player = Unit::GetPlayer(*me, (*itr).first))
                                {
                                    if (!player->isCharmed())
                                    {
                                        player->SetFloatValue(OBJECT_FIELD_SCALE_X, (*itr).second);
                                        std::map<uint64, float>::iterator next = itr;
                                        ++next;
                                        chained.erase(itr);
                                        itr = next;
                                        continue;
                                    }

                                    if (Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, NotCharmedTargetSelector()))
                                    {
                                        switch (player->getClass())
                                        {
                                            case CLASS_DRUID:
                                                if (urand(0, 1))
开发者ID:,项目名称:,代码行数:67,代码来源:

示例8: setPluginJavaData

void PluginUtils::setPluginJavaData(PluginProtocol* pKeyObj, PluginJavaData* pData)
{
    erasePluginJavaData(pKeyObj);
    s_PluginObjMap.insert(std::pair<PluginProtocol*, PluginJavaData*>(pKeyObj, pData));
}
开发者ID:524777134,项目名称:cocos2d-x,代码行数:5,代码来源:PluginUtils.cpp

示例9: TypesEqual

// TypesEqual - Two types are considered structurally equal if they have the
// same "shape": Every level and element of the types have identical primitive
// ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
// be pointer equals to be equivalent though.  This uses an optimistic algorithm
// that assumes that two graphs are the same until proven otherwise.
//
static bool TypesEqual(const Type *Ty, const Type *Ty2,
                       std::map<const Type *, const Type *> &EqTypes) {
  if (Ty == Ty2) return true;
  if (Ty->getTypeID() != Ty2->getTypeID()) return false;
  if (Ty->isOpaqueTy())
    return false;  // Two unequal opaque types are never equal

  std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
  if (It != EqTypes.end())
    return It->second == Ty2;    // Looping back on a type, check for equality

  // Otherwise, add the mapping to the table to make sure we don't get
  // recursion on the types...
  EqTypes.insert(It, std::make_pair(Ty, Ty2));

  // Two really annoying special cases that breaks an otherwise nice simple
  // algorithm is the fact that arraytypes have sizes that differentiates types,
  // and that function types can be varargs or not.  Consider this now.
  //
  if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
    const IntegerType *ITy2 = cast<IntegerType>(Ty2);
    return ITy->getBitWidth() == ITy2->getBitWidth();
  }
  
  if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
    const PointerType *PTy2 = cast<PointerType>(Ty2);
    return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
           TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
  }
  
  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
    const StructType *STy2 = cast<StructType>(Ty2);
    if (STy->getNumElements() != STy2->getNumElements()) return false;
    if (STy->isPacked() != STy2->isPacked()) return false;
    for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
      if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
        return false;
    return true;
  }
  
  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
    const ArrayType *ATy2 = cast<ArrayType>(Ty2);
    return ATy->getNumElements() == ATy2->getNumElements() &&
           TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
  }
  
  if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
    const VectorType *PTy2 = cast<VectorType>(Ty2);
    return PTy->getNumElements() == PTy2->getNumElements() &&
           TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
  }
  
  if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
    const FunctionType *FTy2 = cast<FunctionType>(Ty2);
    if (FTy->isVarArg() != FTy2->isVarArg() ||
        FTy->getNumParams() != FTy2->getNumParams() ||
        !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
      return false;
    for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
      if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
        return false;
    }
    return true;
  }
  
  llvm_unreachable("Unknown derived type!");
  return false;
}
开发者ID:5432935,项目名称:crossbridge,代码行数:74,代码来源:Type.cpp

示例10: FsExecuteFile

/**
* Invoked from Total Commander's command line - or by pressing enter.
*/ 
int __stdcall FsExecuteFile(HWND MainWin, bchar * fullRemoteName, bchar * verb)
{
	gMainWin = MainWin;
	WLock wlock;
	if (!verb || !*verb)
		return FS_EXEC_ERROR;

	// disable automatic reloads
	lastServer = 0;

	bstring cmd = verb;
	bstring fullRemotePath;
	if (fullRemoteName && *fullRemoteName) fullRemotePath = fullRemoteName + 1;

	// set the global mode!? -- ignore, since SFTP does not support it.
	if (cmd.length() > 5 && cmd.substr(0, 4) == TEXT("MODE")) {
		if (cmd[5] == 'A')
			transferAscii = true;
		else {
			modeExtensions.clear();
			transferAscii = false;
			if (cmd[5] == 'X') {
				size_t start = (size_t)-1;
				for (size_t i = 6; i < cmd.size(); ++i)
				{
					if (cmd[i] == '.') start = i;
					else if (cmd[i] <= 32) {
						size_t len = i - start;
						bstring x = cmd.substr(start, len);
						modeExtensions.insert(std::make_pair(x, x));
						start = (size_t)-1;
					}
				}
				if (start != (size_t)-1) {
					bstring x = cmd.substr(start);
					modeExtensions.insert(std::make_pair(x, x));
				}
			}
		}
		return FS_EXEC_OK;
	}

	bstring remotePath;
	if (cmd == TEXT("open")) {
		size_t slash = fullRemotePath.find_first_of('\\');
		if (slash != (size_t)-1)
			return FS_EXEC_YOURSELF;

		// it's a server name
		if (fullRemotePath != EDIT_CONNECTIONS) {
			// get or create the server
			Server * server = Server::findServer(remotePath, fullRemotePath.c_str());
			if (!server)
				return FS_EXEC_ERROR;

			if (!server->connect()) {
				Server::removeServer(server->getName().c_str());
				return FS_EXEC_ERROR;
			}
							
			// simply get the home folder and append. Otherwise the progress bar hides
			// connect and get the home folder
			bstring response;
			if (!server->getHomeDir(response))
				return FS_EXEC_ERROR;

			// return the full remote path and force reload of dir
			fullRemoteName[0] = '/';
			bstrcpy(fullRemoteName + 1, server->getName().c_str());
			bstrcat(fullRemoteName, response.c_str());
			toDos(fullRemoteName);

			return FS_EXEC_SYMLINK;
		}

		// It's edit connections. Create a temp server - maybe we keep it.
		Server server(TEXT("~"));

		// popup config dialog
		config_tag const * const cfg = server.doConfig();
		if (!cfg) {
			fullRemoteName[1] = 0;
			return FS_EXEC_SYMLINK;
		}

		Sftp4tc const * const session = &cfg->sftp4tc;

		// is there a session?
		bstring sessionName;
#ifdef UNICODE
		BCONVERT(wchar_t, 256, sessionName, session->selectedSession)
#else
		sessionName = session->selectedSession;
#endif
		bchar buf[16];
		if (sessionName.length() == 0) {
			// no create a name from host
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:sftp4tc-svn,代码行数:101,代码来源:fsplugin.cpp

示例11: GetDelimiter

char_t Tokenizer::GetDelimiter(TokenRange range) const {
  // Symbols are sorted by their precedence, in decreasing order. While the most
  // common delimiters are underscore, space and dot, we give comma the priority
  // to handle the case where words are separated by ", ". Besides, we'll be
  // trimming whitespace later on.
  static const string_t kDelimiterTable = L",_ .-+;&|~";

  // Trim whitespace so that it doesn't interfere with our frequency analysis.
  // This proves useful for handling some edge cases, and it doesn't seem to
  // have any side effects.
  if (!TrimWhitespace(filename_, range))
    return L' ';

  static std::map<char_t, size_t> frequency;

  if (frequency.empty()) {
    // Initialize frequency map
    for (const auto& character : kDelimiterTable) {
      frequency.insert(std::make_pair(character, 0));
    }
  } else {
    // Reset frequency map
    for (auto& pair : frequency) {
      pair.second = 0;
    }
  }

  // Count all possible delimiters
  for (size_t i = range.offset; i < range.offset + range.size; i++) {
    const char_t character = filename_.at(i);
    if (IsAlphanumericChar(character))
      continue;
    if (frequency.find(character) == frequency.end())
      continue;
    frequency.at(character) += 1;
  }

  char_t delimiter = L'\0';

  for (const auto& pair : frequency) {
    if (pair.second == 0)
      continue;

    // Initialize delimiter at first iteration
    if (delimiter == L'\0') {
      delimiter = pair.first;
      continue;
    }

    int character_distance =
        static_cast<int>(kDelimiterTable.find(pair.first)) -
        static_cast<int>(kDelimiterTable.find(delimiter));
    // If the distance is negative, then the new delimiter has higher priority
    if (character_distance < 0) {
      delimiter = pair.first;
      continue;
    }

    // Even if the new delimiter has lower priority, it may be much more common
    float frequency_ratio = static_cast<float>(pair.second) /
                            static_cast<float>(frequency[delimiter]);
    // The constant value was chosen by trial and error. There should be room
    // for improvement.
    if (frequency_ratio / abs(character_distance) > 0.8f)
      delimiter = pair.first;
  }

  return delimiter;
}
开发者ID:vevix,项目名称:anitomy,代码行数:69,代码来源:tokenizer.cpp

示例12: LoadMtl

std::string LoadMtl (
  std::map<std::string, material_t>& material_map,
  const char* filename,
  const char* mtl_basepath)
{
  material_map.clear();
  std::stringstream err;

  std::string filepath;

  if (mtl_basepath) {
    filepath = std::string(mtl_basepath) + std::string(filename);
  } else {
    filepath = std::string(filename);
  }

  std::ifstream ifs(filepath.c_str());
  if (!ifs) {
    err << "Cannot open file [" << filepath << "]" << std::endl;
    return err.str();
  }

  material_t material;
  
  int maxchars = 8192;  // Alloc enough size.
  std::vector<char> buf(maxchars);  // Alloc enough size.
  while (ifs.peek() != -1) {
    ifs.getline(&buf[0], maxchars);

    std::string linebuf(&buf[0]);

    // Trim newline '\r\n' or '\r'
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1);
    }
    if (linebuf.size() > 0) {
      if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1);
    }

    // Skip if empty line.
    if (linebuf.empty()) {
      continue;
    }

    // Skip leading space.
    const char* token = linebuf.c_str();
    token += strspn(token, " \t");

    assert(token);
    if (token[0] == '\0') continue; // empty line
    
    if (token[0] == '#') continue;  // comment line
    
    // new mtl
    if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) {
      // flush previous material.
      material_map.insert(std::pair<std::string, material_t>(material.name, material));

      // initial temporary material
      InitMaterial(material);

      // set new mtl name
      char namebuf[4096];
      token += 7;
      sscanf(token, "%s", namebuf);
      material.name = namebuf;
      continue;
    }
    
    // ambient
    if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.ambient[0] = r;
      material.ambient[1] = g;
      material.ambient[2] = b;
      continue;
    }
    
    // diffuse
    if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.diffuse[0] = r;
      material.diffuse[1] = g;
      material.diffuse[2] = b;
      continue;
    }
    
    // specular
    if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) {
      token += 2;
      float r, g, b;
      parseFloat3(r, g, b, token);
      material.specular[0] = r;
      material.specular[1] = g;
      material.specular[2] = b;
      continue;
//.........这里部分代码省略.........
开发者ID:cassab,项目名称:Decorato_Sketching,代码行数:101,代码来源:objloader.cpp

示例13: ColorFindNearest

    EDA_COLOR_T COLOR4D::GetNearestLegacyColor( const COLOR4D &aColor )
    {
        // Cache layer implemented here, because all callers are using wxColour
        static std::map< unsigned int, unsigned int > nearestCache;
        static double hues[NBCOLORS];
        static double values[NBCOLORS];

        unsigned int colorInt = aColor.ToU32();

        auto search = nearestCache.find( colorInt );

        if( search != nearestCache.end() )
            return static_cast<EDA_COLOR_T>( search->second );

        // First use ColorFindNearest to check for exact matches
        EDA_COLOR_T nearest = ColorFindNearest( aColor.r * 255.0, aColor.g * 255.0, aColor.b * 255.0 );

        if( COLOR4D( nearest ) == aColor )
        {
            nearestCache.insert( std::pair< unsigned int, unsigned int >(
                                 colorInt, static_cast<unsigned int>( nearest ) ) );
            return nearest;
        }

        // If not, use hue and value to match.
        // Hue will be NAN for grayscale colors.
        // The legacy color palette is a grid across hue and value.
        // We can exploit that to find a good match -- hue is most apparent to the user.
        // So, first we determine the closest hue match, and then the closest value from that
        // "grid row" in the legacy palette.

        double h, s, v;
        aColor.ToHSV( h, s, v );

        double minDist = 360.0;
        double legacyHue = 0.0;

        if( std::isnan( h ) )
        {
            legacyHue = NAN;
        }
        else
        {
            for( EDA_COLOR_T candidate = ::BLACK;
                    candidate < NBCOLORS; candidate = NextColor( candidate ) )
            {
                double ch;

                if( hues[candidate] == 0.0 && values[candidate] == 0.0 )
                {
                    COLOR4D candidate4d( candidate );
                    double cs, cv;

                    candidate4d.ToHSV( ch, cs, cv );

                    values[candidate] = cv;
                    // Set the hue to non-zero for black so that we won't do this more than once
                    hues[candidate] = ( cv == 0.0 ) ? 1.0 : ch;
                }
                else
                {
                    ch = hues[candidate];
                }

                if( fabs( ch - h ) < minDist )
                {
                    minDist = fabs( ch - h );
                    legacyHue = ch;
                }
            }
        }

        // Now we have the desired hue; let's find the nearest value
        minDist = 1.0;
        for( EDA_COLOR_T candidate = ::BLACK;
                candidate < NBCOLORS; candidate = NextColor( candidate ) )
        {
            // If the target hue is NAN, we didn't extract the value for any colors above
            if( std::isnan( legacyHue ) )
            {
                double ch, cs, cv;
                COLOR4D candidate4d( candidate );
                candidate4d.ToHSV( ch, cs, cv );
                values[candidate] = cv;
                hues[candidate] = ( cv == 0.0 ) ? 1.0 : ch;
            }

            if( ( std::isnan( legacyHue ) != std::isnan( hues[candidate] ) ) || hues[candidate] != legacyHue )
                continue;

            if( fabs( values[candidate] - v ) < minDist )
            {
                minDist = fabs( values[candidate] - v );
                nearest = candidate;
            }
        }

        nearestCache.insert( std::pair< unsigned int, unsigned int >(
                             colorInt, static_cast<unsigned int>( nearest ) ) );

//.........这里部分代码省略.........
开发者ID:KiCad,项目名称:kicad-source-mirror,代码行数:101,代码来源:color4d.cpp

示例14: main

int main(int argc,char** argv)
{
    
    char *channelProcessControl = NULL;
    char *configurationFile = NULL;

    if (argc!=5) {
        usage();
        exit(0);
    }
    
    channelProcessControl = argv[1];
    channelStereoControl = argv[2];
    channelProcessReport = argv[3];
    configurationFile = argv[4];


    // read the configuration file to get the processes we'll need
    GKeyFile *keyfile;
    GKeyFileFlags flags = G_KEY_FILE_NONE;
    GError *error = NULL;
    gsize length, length2;

    /* Create a new GKeyFile object and a bitwise list of flags. */
    keyfile = g_key_file_new ();

    /* Load the GKeyFile from keyfile.conf or return. */
    if (!g_key_file_load_from_file (keyfile, configurationFile, flags, &error))
    {
        fprintf(stderr, "Configuration file \"%s\" not found.\n", configurationFile);
        return -1;
    }
    
    // build the process table based on the configuration file
    
    // first get the names of all of the processes
    char **processGroups = g_key_file_get_groups(keyfile, &length);
    
    for (int i=0; i<(int)length; i++)
    {
        // for each process...
        
        // get the arguments
        char **thisArgs = g_key_file_get_string_list(keyfile, processGroups[i], "arguments", &length2, &error);
        
        if (thisArgs == NULL)
        {
            cout << "Error: no arguments list for process " << processGroups[i] << endl;
        } else {
            processMap.insert(std::pair<string, ProcessControlProc>(processGroups[i], ProcessControlProc(thisArgs, (int)length)));
        }
    }
    
    // now throw an error if the configuration file doesn't have all the right parts
    CheckForProc("paramServer");
    CheckForProc("mavlinkLcmBridge");
    CheckForProc("mavlinkSerial");
    CheckForProc("stateEstimator");
    CheckForProc("windEstimator");
    CheckForProc("controller");
    CheckForProc("logger");
    CheckForProc("stereo");
    

    lcm = lcm_create ("udpm://239.255.76.67:7667?ttl=1");
    if (!lcm)
    {
        fprintf(stderr, "lcm_create for recieve failed.  Quitting.\n");
        return 1;
    }

    process_control_sub = lcmt_process_control_subscribe(lcm, channelProcessControl, &procces_control_handler, NULL);

    signal(SIGINT,sighandler);
    
    pthread_t processStatusThread;
    
    pthread_create( &processStatusThread, NULL, ProcessStatusThreadFunc, NULL);
    
    printf("Receiving:\n\tProcess Control LCM: %s\nPublishing LCM:\n\tStereo: %s\n\tStatus: %s\n", channelProcessControl, channelStereoControl, channelProcessReport);

    while (true)
    {
        // read the LCM channel
        lcm_handle (lcm);
    }

    return 0;
}
开发者ID:fengmushu,项目名称:flight,代码行数:89,代码来源:process-control.cpp

示例15: main

int main (int argc, char ** argv)
{
	std::string filename;
	std::ifstream trace_file;

	uint64_t memory_size = 8*1024*1024; // default is 8GB
	// Check if all arguments are given in command line
	if (argc != 3)
	{
		std::cout << "Please supply two arguements: <trace file> <physical memory size (B)>." << std::endl;
		return -1;
	}

	// Get the filename
	filename.assign(argv[1]);
	// Assign the memory size
	memory_size = std::stol(argv[2], nullptr, 10);

	// allocate array
	uint64_t array_size = memory_size / page_size;
	array_size--; // assume 1st level page table ALWAYS in memory
	MEME * in_memory = new MEME[array_size];
//	in_memory [array_size];
	uint64_t array_index = 0;

	//std::cout << argv[2] << " " << memory_size << " " << array_size << std::endl;


	// Open the file
	trace_file.open(filename);
	char operation;
	std::string virtual_address;
	std::string this_key;
	int byte_size;
	std::string file_line;
	std::vector<std::string> line_input;
	std::string token;

	while (std::getline(trace_file, file_line))
	{
		// tokenize string
		std::istringstream ss(file_line);
		while(std::getline(ss, token, ' '))
		{
			line_input.push_back(token);
			//std::cout << token << std::endl;
		}

		if (line_input.size() != 3)
		{
			line_input.clear();
			continue;
		}
		
		operation = line_input[0].at(0);
		if (operation != 'R' && operation != 'W')
		{
			line_input.clear();
			continue;
		}

		line_input[1] = line_input[1].substr(0, line_input[1].size() - 3);
		if (!valid_address(line_input[1]))
		{
			line_input.clear();
			continue;
		}
		virtual_address = line_input[1];
		this_key = line_input[1];//virtual_address;//get_VPN(virtual_address);

		if (!valid_size(line_input[2]))
		{
			line_input.clear();
			continue;
		}
		byte_size = std::stoi(line_input[2]);

		if (operation == 'R')
			total_bytes_read += byte_size;
		else
			total_bytes_write += byte_size;

		auto search = vpn_tracker.find(this_key);
		if (search != vpn_tracker.end())
		{
			// check if 2nd level not in memory
			if (!vpn_tracker[this_key].lvl_2_mem)
			{
				// find page to eject
				array_index = get_next_index(in_memory, array_size, array_index);
				eject_from_memory (in_memory[array_index].vpn, in_memory[array_index].level);

				// insert new page
				insert_into_memory (in_memory, array_index, this_key, 2);
			}
			else if (vpn_tracker[this_key].lvl_2_mem)
			{
				total_accessed++;
				vpn_tracker[this_key].lvl_2_clock = 1;
			}
//.........这里部分代码省略.........
开发者ID:rfolk,项目名称:Memory-Analyzer,代码行数:101,代码来源:main.cpp


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