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


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

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


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

示例1: calcSpearman

//**********************************************************************************************************************
int CorrAxesCommand::calcSpearman(map<string, vector<float> >& axes, ofstream& out) {
	try {
		
		//format data
		vector< map<float, int> > tableX; tableX.resize(numaxes);
		map<float, int>::iterator itTable;
		vector< vector<spearmanRank> > scores; scores.resize(numaxes);
		for (map<string, vector<float> >::iterator it = axes.begin(); it != axes.end(); it++) {
			vector<float> temp = it->second;
			for (int i = 0; i < temp.size(); i++) {
				spearmanRank member(it->first, temp[i]);
				scores[i].push_back(member);  
				
				//count number of repeats
				itTable = tableX[i].find(temp[i]);
				if (itTable == tableX[i].end()) { 
					tableX[i][temp[i]] = 1;
				}else {
					tableX[i][temp[i]]++;
				}
			}
		}
		
		//calc LX
		//for each axis
		vector<double> Lx; Lx.resize(numaxes, 0.0);
		for (int i = 0; i < numaxes; i++) {
			for (itTable = tableX[i].begin(); itTable != tableX[i].end(); itTable++) {
				double tx = (double) itTable->second;
				Lx[i] += ((pow(tx, 3.0) - tx) / 12.0);
			}
		}
		
		//sort each axis
		for (int i = 0; i < numaxes; i++) {  sort(scores[i].begin(), scores[i].end(), compareSpearman); }
		
		//find ranks of xi in each axis
		map<string, vector<float> > rankAxes;
		for (int i = 0; i < numaxes; i++) {
			
			vector<spearmanRank> ties;
			int rankTotal = 0;
			for (int j = 0; j < scores[i].size(); j++) {
				rankTotal += (j+1);
				ties.push_back(scores[i][j]);
				
				if (j != (scores[i].size()-1)) { // you are not the last so you can look ahead
					if (scores[i][j].score != scores[i][j+1].score) { // you are done with ties, rank them and continue

						for (int k = 0; k < ties.size(); k++) {
							float thisrank = rankTotal / (float) ties.size();
  							rankAxes[ties[k].name].push_back(thisrank);
						}
						ties.clear();
						rankTotal = 0;
					}
				}else { // you are the last one
					
					for (int k = 0; k < ties.size(); k++) {
						float thisrank = rankTotal / (float) ties.size();
						rankAxes[ties[k].name].push_back(thisrank);
						
					}
				}
			}
		}
		
				
		//for each otu
		for (int i = 0; i < lookupFloat[0]->getNumBins(); i++) {
			
			if (metadatafile == "") {  out << i+1;	}
			else {  out << metadataLabels[i];		}
			
			//find the ranks of this otu - Y
			vector<spearmanRank> otuScores;
			map<float, int> tableY;
			for (int j = 0; j < lookupFloat.size(); j++) {
				spearmanRank member(lookupFloat[j]->getGroup(), lookupFloat[j]->getAbundance(i));
				otuScores.push_back(member);
				
				itTable = tableY.find(member.score);
				if (itTable == tableY.end()) { 
					tableY[member.score] = 1;
				}else {
					tableY[member.score]++;
				}
				
			}
			
			//calc Ly
			double Ly = 0.0;
			for (itTable = tableY.begin(); itTable != tableY.end(); itTable++) {
				double ty = (double) itTable->second;
				Ly += ((pow(ty, 3.0) - ty) / 12.0);
			}
			
			sort(otuScores.begin(), otuScores.end(), compareSpearman);
			
//.........这里部分代码省略.........
开发者ID:azerxu,项目名称:mothur,代码行数:101,代码来源:corraxescommand.cpp

示例2: Exception

std::vector<std::string> ScriptSystem::load() {

    std::vector<std::string> filenames;

    static const string types[] = {
        "config", "global", "extensions",
        "classes", "states", "ui"
    };
    for (unsigned int i = 0; i < sizeof(types) / sizeof(types[0]); i++) {

        std::vector<std::string> gathered = chi::System::gatherFiles(
                                                System::resourceLocation() + "/script/" + types[i],
                                                "(.*\\.js|.*\\.coffee)"
                                            );

        for (unsigned int j = 0; j < gathered.size(); j++) {
            filenames.push_back(gathered[j]);
        }
    }

    sort(filenames.begin(), filenames.end());

    HandleScope scope;

    for (unsigned int i = 0; i < filenames.size(); i++) {

        Script *script = Script::factory->create();
        scripts[filenames[i]] = script->compileFile(filenames[i]);
    }

    std::vector<std::string> loadedFilenames;

    while (scripts.size() > 0) {

        unsigned int size = scripts.size();

        vector<string>::iterator i = filenames.begin();
        while (i != filenames.end()) {

            try {
                scripts[*i]->run();

                loadedFilenames.push_back(*i);

                delete scripts[*i];

                scripts.erase(*i);
                i = filenames.erase(i);
            }
            catch (std::exception &e) {

                ++i;
            }
        }

        if (size == scripts.size()) {

            std::string text;

            map<string, Script *>::iterator i = scripts.begin();
            while (i != scripts.end()) {

                try {
                    (i->second)->run();
                }
                catch (std::exception &e) {
                    text += e.what();
                }

                delete i->second;
                scripts.erase(i++);
            }

            throw chi::Exception(text);
        }
    }

    return loadedFilenames;
}
开发者ID:cha0s,项目名称:Worlds-Beyond,代码行数:79,代码来源:ScriptSystem.cpp

示例3: print

void print(map<int, int> & distances) {
  for (MapIntIterator it = distances.begin(); it != distances.end(); ++it) {
    cout << it -> first << " => " << it -> second << endl;
  }
}
开发者ID:jonas-pettersson,项目名称:cpp,代码行数:5,代码来源:Dijkstra.cpp

示例4: handleRESTQuery

        void handleRESTQuery( string ns , string action , map<string,string> & params , int & responseCode , stringstream & out ) {
            Timer t;

            int skip = _getOption( params["skip"] , 0 );
            int num = _getOption( params["limit"] , _getOption( params["count" ] , 1000 ) ); // count is old, limit is new

            int one = 0;
            if ( params["one"].size() > 0 && tolower( params["one"][0] ) == 't' ) {
                num = 1;
                one = 1;
            }

            BSONObjBuilder queryBuilder;

            for ( map<string,string>::iterator i = params.begin(); i != params.end(); i++ ) {
                if ( ! i->first.find( "filter_" ) == 0 )
                    continue;

                const char * field = i->first.substr( 7 ).c_str();
                const char * val = i->second.c_str();

                char * temp;

                // TODO: this is how i guess if something is a number.  pretty lame right now
                double number = strtod( val , &temp );
                if ( temp != val )
                    queryBuilder.append( field , number );
                else
                    queryBuilder.append( field , val );
            }

            BSONObj query = queryBuilder.obj();

            auto_ptr<DBClientCursor> cursor = db.query( ns.c_str() , query, num , skip );

            if ( one ) {
                if ( cursor->more() ) {
                    BSONObj obj = cursor->next();
                    out << obj.jsonString() << "\n";
                }
                else {
                    responseCode = 404;
                }
                return;
            }

            out << "{\n";
            out << "  \"offset\" : " << skip << ",\n";
            out << "  \"rows\": [\n";

            int howMany = 0;
            while ( cursor->more() ) {
                if ( howMany++ )
                    out << " ,\n";
                BSONObj obj = cursor->next();
                out << "    " << obj.jsonString();

            }
            out << "\n  ],\n\n";

            out << "  \"total_rows\" : " << howMany << " ,\n";
            out << "  \"query\" : " << query.jsonString() << " ,\n";
            out << "  \"millis\" : " << t.millis() << "\n";
            out << "}\n";
        }
开发者ID:blythedunham,项目名称:mongo,代码行数:65,代码来源:dbwebserver.cpp

示例5: GetSettingsFromMappingsFile

void CPeripherals::GetSettingsFromMappingsFile(TiXmlElement *xmlNode, map<CStdString, CSetting *> &m_settings)
{
  TiXmlElement *currentNode = xmlNode->FirstChildElement("setting");
  int iMaxOrder(0);

  while (currentNode)
  {
    CSetting *setting = NULL;
    CStdString strKey(currentNode->Attribute("key"));
    if (strKey.IsEmpty())
      continue;

    CStdString strSettingsType(currentNode->Attribute("type"));
    int iLabelId = currentNode->Attribute("label") ? atoi(currentNode->Attribute("label")) : -1;
    bool bConfigurable = (!currentNode->Attribute("configurable") ||
                          strcmp(currentNode->Attribute("configurable"), "") == 0 ||
                           (strcmp(currentNode->Attribute("configurable"), "no") != 0 &&
                            strcmp(currentNode->Attribute("configurable"), "false") != 0 &&
                            strcmp(currentNode->Attribute("configurable"), "0") != 0));
    if (strSettingsType.Equals("bool"))
    {
      bool bValue = (strcmp(currentNode->Attribute("value"), "no") != 0 &&
                     strcmp(currentNode->Attribute("value"), "false") != 0 &&
                     strcmp(currentNode->Attribute("value"), "0") != 0);
      setting = new CSettingBool(0, strKey, iLabelId, bValue, CHECKMARK_CONTROL);
    }
    else if (strSettingsType.Equals("int"))
    {
      int iValue = currentNode->Attribute("value") ? atoi(currentNode->Attribute("value")) : 0;
      int iMin   = currentNode->Attribute("min") ? atoi(currentNode->Attribute("min")) : 0;
      int iStep  = currentNode->Attribute("step") ? atoi(currentNode->Attribute("step")) : 1;
      int iMax   = currentNode->Attribute("max") ? atoi(currentNode->Attribute("max")) : 255;
      CStdString strFormat(currentNode->Attribute("format"));
      setting = new CSettingInt(0, strKey, iLabelId, iValue, iMin, iStep, iMax, SPIN_CONTROL_INT, strFormat);
    }
    else if (strSettingsType.Equals("float"))
    {
      float fValue = currentNode->Attribute("value") ? (float) atof(currentNode->Attribute("value")) : 0;
      float fMin   = currentNode->Attribute("min") ? (float) atof(currentNode->Attribute("min")) : 0;
      float fStep  = currentNode->Attribute("step") ? (float) atof(currentNode->Attribute("step")) : 0;
      float fMax   = currentNode->Attribute("max") ? (float) atof(currentNode->Attribute("max")) : 0;
      setting = new CSettingFloat(0, strKey, iLabelId, fValue, fMin, fStep, fMax, SPIN_CONTROL_FLOAT);
    }
    else if (strSettingsType.Equals("enum"))
    {
      CStdString strEnums(currentNode->Attribute("lvalues"));
      if (!strEnums.IsEmpty())
      {
        map<int,int> enums;
        vector<CStdString> valuesVec;
        CUtil::Tokenize(strEnums, valuesVec, "|");
        for (unsigned int i = 0; i < valuesVec.size(); i++)
          enums.insert(make_pair(atoi(valuesVec[i]), atoi(valuesVec[i])));
        int iValue = currentNode->Attribute("value") ? atoi(currentNode->Attribute("value")) : 0;
        setting = new CSettingInt(0, strKey, iLabelId, iValue, enums, SPIN_CONTROL_TEXT);
      }
    }
    else
    {
      CStdString strValue(currentNode->Attribute("value"));
      setting = new CSettingString(0, strKey, iLabelId, strValue, EDIT_CONTROL_INPUT, !bConfigurable, -1);
    }

    if (setting)
    {
      //TODO add more types if needed

      /* set the visibility */
      setting->SetVisible(bConfigurable);

      /* set the order */
      int iOrder(0);
      currentNode->Attribute("order", &iOrder);
      /* if the order attribute is invalid or 0, then the setting will be added at the end */
      if (iOrder < 0)
        iOrder = 0;
      setting->SetOrder(iOrder);
      if (iOrder > iMaxOrder)
       iMaxOrder = iOrder;

      /* and add this new setting */
      m_settings[strKey] = setting;
    }

    currentNode = currentNode->NextSiblingElement("setting");
  }

  /* add the settings without an order attribute or an invalid order attribute set at the end */
  for (map<CStdString, CSetting *>::iterator it = m_settings.begin(); it != m_settings.end(); it++)
  {
    if (it->second->GetOrder() == 0)
      it->second->SetOrder(++iMaxOrder);
  }
}
开发者ID:abschicken,项目名称:xbmc,代码行数:94,代码来源:Peripherals.cpp

示例6: GFGoodBuy

void __stdcall GFGoodBuy(struct SGFGoodBuyInfo const &gbi, unsigned int iClientID)
	{
		returncode = DEFAULT_RETURNCODE;

			const GoodInfo *packageInfo = GoodList::find_by_id(gbi.iGoodID);
			/*
			if (packageInfo->iType == 0)
			{
			PrintUserCmdText(iClientID, L"This should be a commodity (equipment?) purchase");
			}
			*/
			if (packageInfo->iType == 1)
			{
			//PrintUserCmdText(iClientID, L"This should be an equipment (maybe?) purchase");
			uint iBase;
			pub::Player::GetBase(iClientID, iBase);
			bool aminiceitem = true;
			string itemname;
			int wearecool = 0;
			
				//in this case, it's more efficent to check if it's an item under watch first.

				for (map<uint, string>::iterator iter = mapACItems.begin(); iter!=mapACItems.end(); iter++)
				{
					if (iter->first == gbi.iGoodID)
					{
									//PrintUserCmdText(iClientID, L"I have found this commodity");
									//We iterate through the base names to see if it's a non-POB base
									list<uint>::iterator i = mapACBases.begin();
									while (i != mapACBases.end())
									{
										if (*i == iBase)
										{
											
												if (mapACSales[iClientID].items.find(gbi.iGoodID) != mapACSales[iClientID].items.end())
												{
														--mapACSales[iClientID].items.find(gbi.iGoodID)->second;
													
															//PrintUserCmdText(iClientID, L"DEBUG: I have found this sale, letting the purchase go through.");
															aminiceitem = true;
															wearecool = 1;

															wstring wscCharname = (const wchar_t*) Players.GetActiveCharacterName(iClientID);
															wstring wscBaseName = HkGetBaseNickByID(iBase);
															
															//PrintUserCmdText(iClientID, L"DEBUG: %i purchases left.", mapACSales[iClientID].items.find(gbi.iGoodID)->second);
															wstring wscMsgLog = L"<%sender> has bought back <%item> from base <%basename> (%isale purchases left)";
															wscMsgLog = ReplaceStr(wscMsgLog, L"%sender", wscCharname.c_str());
															wscMsgLog = ReplaceStr(wscMsgLog, L"%basename", wscBaseName.c_str());
															wscMsgLog = ReplaceStr(wscMsgLog, L"%item", stows(iter->second).c_str());
															wscMsgLog = ReplaceStr(wscMsgLog, L"%isale", stows(itos(mapACSales[iClientID].items.find(gbi.iGoodID)->second))).c_str();
															string scText = wstos(wscMsgLog);
															Logging("%s", scText.c_str());

															if (mapACSales[iClientID].items.find(gbi.iGoodID)->second == 0)
															{
																mapACSales[iClientID].items.erase(gbi.iGoodID);
																//PrintUserCmdText(iClientID, L"DEBUG: no purchases left");
															}

															break;
													
												}

											if (wearecool == 0)
											{
											//PrintUserCmdText(iClientID, L"DEBUG: I have found this base, not good");
											aminiceitem = false;
											itemname = iter->second;
											}
										}
										i++;
									}
					}

					if (aminiceitem == false)
					{
						returncode = SKIPPLUGINS_NOFUNCTIONCALL;
						wstring wscCharname = (const wchar_t*) Players.GetActiveCharacterName(iClientID);
							wstring wscBaseName = HkGetBaseNickByID(iBase);
							
							pub::Player::SendNNMessage(iClientID, pub::GetNicknameId("nnv_anomaly_detected"));
							wstring wscMsgU = L"MF: %name has been permabanned. (Type 2)";
							wscMsgU = ReplaceStr(wscMsgU, L"%name", wscCharname.c_str());

							HkMsgU(wscMsgU);

							wstring wscMsgLog = L"<%sender> was permabanned for attempting to buy an illegal item <%item> from base <%basename> (see DSAM)";
							wscMsgLog = ReplaceStr(wscMsgLog, L"%sender", wscCharname.c_str());
							wscMsgLog = ReplaceStr(wscMsgLog, L"%basename", wscBaseName.c_str());
							wscMsgLog = ReplaceStr(wscMsgLog, L"%item", stows(itemname).c_str());

							LogCheater(iClientID, wscMsgLog);
					}
				}
			}
			else if (packageInfo->iType == 3)
			{
					uint iBase;
					pub::Player::GetBase(iClientID, iBase);
//.........这里部分代码省略.........
开发者ID:HeIIoween,项目名称:FLHook,代码行数:101,代码来源:Main.cpp

示例7: FindBest

// recursive function, returns maximum depth of this path
int FindBest(int MoneyLeft, int Depth)
{
    vector<int>::iterator it;
    map<ChangeGiven, int>::iterator iter;
    map<int,int>::iterator solit;
//  table of partial solutions, key is the type of coin, value the minimum number of coins possible; best path for this amount of money will be remembered
    map<int,int> PartialSolutions;
    pair<int,int> Best;
//  depth is increased for every level in the recursion and serves as an orientation; numcoins is a buffer variable
    int NewDepth=Depth+1, MaxDepth, NumCoins, BestCoin;
    bool check=false;
//  iterate through the list of coins
    for (it=CoinList.begin(); it!=CoinList.end(); it++)
    {
// 	check if coin is still eligible
        if ((MoneyLeft - (*it)) > 0)
        {
// 	  iterate through the list of visited states
            for (iter=Table.begin(); iter!=Table.end(); iter++)
            {
// 	      check if state was visited before; set check variable to true if yes
                if ((MoneyLeft-(*it)) == iter->first.second)
                {
                    NumCoins = iter->second;
                    check = true;
		    break;
                }
            }
// 	  if it is a new state, call function again
            if (check == false)
            {
                MaxDepth = FindBest((MoneyLeft-(*it)), NewDepth);
                NumCoins = MaxDepth - NewDepth;
            }
            // 	make entry for coin
            Best.first = *it;
            Best.second = NumCoins;
            PartialSolutions.insert(Best);
        }
// 	if this leads to a solution, return depth for determining the number of coins
        else if ((MoneyLeft - (*it)) == 0)
        {
// 	    type of coin
            Best.first = *it;
// 	    amount of money left
            Best.second = *it;
            Table[Best] = 1;
            return NewDepth; // or Depth?
        }
        check = false;

    }
    NumCoins = 100000;
//  iterate over possible paths and remember the best
    for (solit=PartialSolutions.begin(); solit!=PartialSolutions.end(); solit++)
    {
        if (solit->second < NumCoins)
        {
            NumCoins = solit->second;
            BestCoin = solit->first;
        }
    }
    Best.first = BestCoin;
    Best.second = MoneyLeft;
    Table[Best] = NumCoins;
//  prepare return value
    MaxDepth = NewDepth + NumCoins;
    return MaxDepth;
}
开发者ID:russiaonice,项目名称:apbc_testing,代码行数:70,代码来源:change_testing2a.cpp

示例8: UdmMain


//.........这里部分代码省略.........
		}
	}

	std::string module_name;
	auto script_file_it = componentParameters.find(_bstr_t(L"script_file"));
	if (script_file_it == componentParameters.end())
	{
		std::wstring scriptFilename;
		scriptFilename = openfilename(L"Python Scripts (*.py)\0*.py\0");
		if (scriptFilename.length() == 0)
		{
			return;
		}
		TCHAR fullpath[MAX_PATH];
		TCHAR* filepart;
		if (!GetFullPathNameW(scriptFilename.c_str(), sizeof(fullpath)/sizeof(fullpath[0]), fullpath, &filepart)) {
		} else {
			*(filepart-1) = '\0';

			newpath += separator + static_cast<const char*>(CStringA(fullpath));
			PySys_SetPath(const_cast<char*>(newpath.c_str()));

            module_name = static_cast<const char*>(CStringA(filepart));
		}
	}
	else
	{
		if (script_file_it->second.vt != VT_BSTR || SysStringLen(script_file_it->second.bstrVal) == 0)
		{
			throw udm_exception("No script_file specified");
		}
		module_name = _bstr_t(script_file_it->second.bstrVal);
		if (module_name != "" && PathIsRelativeA(module_name.c_str())) {
			std::replace(module_name.begin(), module_name.end(), '/', '\\');
			if (module_name.rfind('\\') != std::string::npos)
			{
				std::string path = module_name.substr(0, module_name.rfind('\\'));

				newpath = workingDir + "\\CyPhyPythonScripts\\" + path + separator + newpath;
				newpath = workingDir + "\\" + path + separator + newpath;
				PySys_SetPath(const_cast<char*>(newpath.c_str()));
				module_name = module_name.substr(module_name.rfind('\\') + 1);
			}
			else
			{
				newpath = workingDir + "\\CyPhyPythonScripts" + separator + newpath;
				newpath = workingDir + separator + newpath;
				PySys_SetPath(const_cast<char*>(newpath.c_str()));
			}

			//newpath += separator + fullpath;
			//PySys_SetPath(const_cast<char*>(newpath.c_str()));
		}
	}
	{
		PyObject_RAII ret = PyRun_StringFlags("import site\n", Py_file_input, main_namespace, main_namespace, NULL);
		if (ret == NULL && PyErr_Occurred())
		{
			throw python_error(GetPythonError());
		}
	}

	if (module_name.rfind(".py") != std::string::npos)
	{
		module_name = module_name.substr(0, module_name.rfind(".py"));
	}
开发者ID:mcanthony,项目名称:meta-core,代码行数:67,代码来源:UdmApp.cpp

示例9: adjustBundle_ssba

int adjustBundle_ssba(vector<CloudPoint> &pointcloud,
                        Mat &camIntrinsic,
                        map<int, vector<KeyPoint> > &imgpts,
                        map<int, Matx34d> &Pmats)
{
    int     i, j, k;
    int     N, M, K;

    N = Pmats.size();
    M = pointcloud.size();
    K = Count2DMeasurements_ssba(pointcloud);
	
    printf("\nadjustBundle_ssba: \n");
    printf("  N (cams) = %d, M (points) = %d, K (measurements) = %d\n", N, M, K);
	
	/********************************************************************************/
	/*	Use SSBA-3.0 for sparse bundle adjustment									*/
	/********************************************************************************/
	
	StdDistortionFunction distortion;
	
	//conver camera intrinsics to BA datastructs
	Matrix3x3d KMat;
	makeIdentityMatrix(KMat);
    KMat[0][0] = camIntrinsic.at<double>(0,0); //fx
    KMat[1][1] = camIntrinsic.at<double>(1,1); //fy
    KMat[0][1] = camIntrinsic.at<double>(0,1); //skew
    KMat[0][2] = camIntrinsic.at<double>(0,2); //ppx
    KMat[1][2] = camIntrinsic.at<double>(1,2); //ppy
	
	double const f0 = KMat[0][0];
    //cout << "intrinsic before bundle = "; displayMatrix(KMat);

	Matrix3x3d Knorm = KMat;
	// Normalize the intrinsic to have unit focal length.
	scaleMatrixIP(1.0/f0, Knorm);
	Knorm[2][2] = 1.0;
	
	
	//conver 3D point cloud to BA datastructs
    vector<int> pointIdFwdMap(M);
    map<int, int> pointIdBwdMap;

    vector<Vector3d> Xs(M);
    for (j = 0; j < M; j++)
	{
		int pointId = j;

		Xs[j][0] = pointcloud[j].pt.x;
		Xs[j][1] = pointcloud[j].pt.y;
		Xs[j][2] = pointcloud[j].pt.z;

		pointIdFwdMap[j] = pointId;
		pointIdBwdMap.insert(make_pair(pointId, j));
	}

	
    //convert cameras to BA datastructs
	vector<int> camIdFwdMap(N,-1);
	map<int, int> camIdBwdMap;
    vector<CameraMatrix> cams(N);

    map<int, Matx34d>::iterator itcam;

    for(i=0,itcam=Pmats.begin(); itcam!=Pmats.end(); i++,itcam++) {
		int camId = i;
        Matrix3x3d  R;
        Vector3d    T;
		
        Matx34d& P = itcam->second;
		
		R[0][0] = P(0,0); R[0][1] = P(0,1); R[0][2] = P(0,2); T[0] = P(0,3);
		R[1][0] = P(1,0); R[1][1] = P(1,1); R[1][2] = P(1,2); T[1] = P(1,3);
		R[2][0] = P(2,0); R[2][1] = P(2,1); R[2][2] = P(2,2); T[2] = P(2,3);
		
        camIdFwdMap[i] = itcam->first;
        camIdBwdMap.insert(make_pair(itcam->first, camId));
		
		cams[i].setIntrinsic(Knorm);
		cams[i].setRotation(R);
		cams[i].setTranslation(T);
	}

    //convert 2D measurements to BA datastructs
	vector<Vector2d > measurements;
	vector<int> correspondingView;
	vector<int> correspondingPoint;

    map<int,int>            *m;
    map<int,int>::iterator  itm;
	
	measurements.reserve(K);
	correspondingView.reserve(K);
	correspondingPoint.reserve(K);
	
    for(k = 0; k < pointcloud.size(); k++) {
        m = &( pointcloud[k].img_kp );

        for(itm=m->begin(); itm!=m->end(); itm++) {
            int         vid, pid;
//.........这里部分代码省略.........
开发者ID:bushuhui,项目名称:SequenceSFM,代码行数:101,代码来源:sfm_ba_ssba.cpp

示例10: FindSimilarKmer

void ClsMultiThread::FindSimilarKmer(map<string, St_KmerIndex>& mpCombine, vector<St_KmerInfo>& vKmerRegular)
{
    //1: Get the number of CPU
    string strNum = exec("nproc");
    if(strNum.substr(strNum.length()-1,1) == "\n")
        strNum = strNum.substr(0, strNum.length()-1);
    int iCpuNum = atoi(strNum.c_str());

    //2: Divid KmerRegular Table evenly by the number of cpu
    int iLen = ceil((float)vKmerRegular.size() / iCpuNum);
    vector<St_SimilarKmer> vSubGroupKmer;
    vSubGroupKmer.resize(iCpuNum);
    for(int i=0; i<iCpuNum; i++)
    {
        int iStart = i * iLen;
        int iEnd = (i+1)*iLen;
        if(iEnd < vKmerRegular.size())
            vSubGroupKmer[i].vRegKmer.insert(vSubGroupKmer[i].vRegKmer.end(),
                                             vKmerRegular.begin() + iStart, vKmerRegular.begin() + iEnd);
        else
            vSubGroupKmer[i].vRegKmer.insert(vSubGroupKmer[i].vRegKmer.end(),
                                             vKmerRegular.begin() + iStart,
                                             vKmerRegular.end());
        vSubGroupKmer[i].mpSuperKmer.insert(mpCombine.begin(), mpCombine.end());
    }

    //Create Threads
    int start_s = time(NULL);
    pthread_t tids[iCpuNum];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for(int i=0; i<iCpuNum; i++)
    {
        int ret = pthread_create(&tids[i], &attr, ClsThreadFunc::SimilarDetect, (void*)&(vSubGroupKmer[i]));
        if(ret != 0)
            cout << "Thread error: " << ret << endl;
    }
    pthread_attr_destroy(&attr);

    void* status;
    for(int i=0; i<iCpuNum; i++)
    {
        int ret = pthread_join(tids[i], &status);
        if(ret != 0)
            cout << "Thread Error: " << ret << endl;
        else
            cout << "Thread Status: " << (long)status << endl;
    }
    //pthread_exit(NULL);
    int stop_s = time(NULL);
    double dRuningTime = difftime(stop_s, start_s);
    string strTimeFormat = ::GetHMSTimeFormat(dRuningTime);
    cout << "Running Time: " << strTimeFormat << endl;

    //Arrange the kmer
    for(map<string, St_KmerIndex>::iterator itr = mpCombine.begin(); itr != mpCombine.end(); itr++)
    {
        int iBase = itr->second.iCount;
        int iAccumulate = 0;
        for(vector<St_SimilarKmer>::iterator subItr = vSubGroupKmer.begin();
            subItr != vSubGroupKmer.end(); subItr++)
        {
            iAccumulate += subItr->mpSuperKmer[itr->first].iCount - iBase;
        }
        itr->second.iCount = iBase + iAccumulate;
    }
    //好折腾啊!!!!!!!!
    //2: 将剩下的没能归组的再进行合并,得到总的没有归组的kmer
    vKmerRegular.clear();
    for(vector<St_SimilarKmer>::iterator itr = vSubGroupKmer.begin();
        itr != vSubGroupKmer.end(); itr++)
    {
        vKmerRegular.insert(vKmerRegular.end(), itr->vRegKmer.begin(), itr->vRegKmer.end());
    }
}
开发者ID:lxwgcool,项目名称:Huffman_Coding,代码行数:77,代码来源:clsmultithread.cpp

示例11: infer

// infer until fixpoint, which may not be appropriate in the presence of retraction
void infer(vector<Rule> &rules) {
  bool changed = true;
  map<constint_t, size_t> sizes;
  map<constint_t, Index>::const_iterator atomit = atoms.begin();
  for (; atomit != atoms.end(); ++atomit) {
    sizes[atomit->first] = atomit->second.size();
  }
  size_t ncycles = 0;
  while (changed) {
    cerr << "  Cycle " << ++ncycles << "..." << endl;
    changed = false;
#ifndef ANY_ORDER
    Index assertions (Order(0, 1, 2));
    Index retractions (Order(0, 1, 2));
#endif
    int rulecount = 0;
    vector<Rule>::iterator rule = rules.begin();
    for (; rule != rules.end(); ++rule) {
      cerr << "    Rule " << (rule - rules.begin()) + 1 << "..." << endl;
#ifdef ANY_ORDER
      Index assertions (Order(0, 1, 2));
      Index retractions (Order(0, 1, 2));
#endif
      Relation results;
      set<varint_t> allvars;
      query(rule->condition, allvars, results);
      act(rule->action_block, results, assertions, retractions);
#ifndef ANY_ORDER
    }
#endif
    size_t nretractions = 0;
    Index::iterator it = retractions.begin();
    for (; it != retractions.end(); ++it) {
      if (idxspo.erase(*it) > 0) {
        idxpos.erase(*it);
        idxosp.erase(*it);
        changed = true;
        ++nretractions;
      }
    }
    cerr << "  " << nretractions << " retractions, ";
    size_t nassertions = 0;
    it = assertions.begin();
    for (; it != assertions.end(); ++it) {
      if (idxspo.insert(*it).second) {
        idxpos.insert(*it);
        idxosp.insert(*it);
        changed = true;
        ++nassertions;
      }
    }
    cerr << nassertions << " assertions." << endl;
#ifdef ANY_ORDER
    }
#endif
    atomit = atoms.begin();
    for (; atomit != atoms.end(); ++atomit) {
      changed = changed || sizes[atomit->first] != atomit->second.size();
      sizes[atomit->first] = atomit->second.size();
    }
  }
开发者ID:jrweave,项目名称:phd,代码行数:62,代码来源:infer-rules.cpp

示例12: loadTrainingSet

// 加载训练集数据,在加载评分数据的过程中加载用户和商家数据
void loadTrainingSet(map<string, User> &userMap, map<string, Business> &businessMap, set<Review> &reviewSet, const map<string, Category> &categoryMap)
{
    ifstream trainingReviewFile = ifstream(FolderName + "yelp_training_set/yelp_training_set_review.json");

    // 对于training_set_review根据uid和bid进行排序,便于直接生成稀疏矩阵
    if (trainingReviewFile.is_open()) {
        while (!trainingReviewFile.eof()) {
            string line;
            getline(trainingReviewFile, line);
            size_t start = line.find("\"user_id\"");
            string uid = line.substr(start+12, 22);
            string bid = line.substr(line.length() - 24, 22);
            start = line.find("\"stars\"", 124);
            int stars = atoi(line.substr(start+9, 1).c_str());
            start = line.find("\"date\":", 124);
            int year = atoi(line.substr(start+9, 4).c_str());
            int month = atoi(line.substr(start+14, 2).c_str());
            int day = atoi(line.substr(start+17, 2).c_str());
            int date = year*365+month*30+day;
            // 判断用户id是否已经出现在userMap中,如果没有则将新出现的用户数据插入到userMap中
            // 否则,修改userMap中对应的用户数据(reviewCount和平均分)
            map<string, User>::iterator userIter = userMap.find(uid);
            if (userIter == userMap.end()) {
                userMap.insert(make_pair(uid, User(0, stars, 1, "")));
            }
            else
            {
                // 先计算总得打分,最后计算平均分,business类似
                ++(userIter->second.reviewCount);
                userIter->second.starVec.push_back(stars);
            }
            // businessMap的更新和userMap类似
            map<string, Business>::iterator businessIter = businessMap.find(bid);
            if (businessIter == businessMap.end()) {
                businessMap.insert(make_pair(bid, Business(0, stars, 0, 1, "")));
            }
            else
            {
                ++(businessIter->second.reviewCount);
                businessIter->second.starVec.push_back(stars);
            }
            
            reviewSet.insert(Review(uid, bid, stars, date));
        }
    }
    else
    {
        cout << "can't open trainingReviewFile" << endl;
    }
    trainingReviewFile.close();
    
    
    // 根据用户ID的字符串顺序调整用户在矩阵中的位置
    // 计算用户打分的平均分以及打分的RMSE
    int sequence = 0;
    for (map<string, User>::iterator iter = userMap.begin(); iter != userMap.end(); ++iter) {
        iter->second.avgStar = calculateVectorAvg(iter->second.starVec);
        iter->second.RMSE = calculateVectorRMSE(iter->second.starVec, iter->second.avgStar);
        iter->second.sequence = sequence++;
    }
    
    // 根据商家ID的字符串顺序调整商家在矩阵中的位置
    // 计算商家打分的平均分以及打分的RMSE
    sequence = 0;
    for (map<string, Business>::iterator iter = businessMap.begin(); iter != businessMap.end(); ++iter) {
        // 没有review_count小于3的business,等于3的有2531
        iter->second.avgStar = calculateVectorAvg(iter->second.starVec);
        iter->second.RMSE = calculateVectorRMSE(iter->second.starVec, iter->second.avgStar);
        iter->second.sequence = sequence++;
    }
    
    // load training_set_user to userMap
    // 用户数据文件中的数据修改上一步得到的用户数据,评分数和平均分以用户文件中的数据为准
    ifstream trainingSetUserFile(FolderName + "yelp_training_set/yelp_training_set_user.json");
    if (trainingSetUserFile.is_open()) {
        while (!trainingSetUserFile.eof()) {
            string line;
            getline(trainingSetUserFile, line);
            size_t start, end;
            start = line.find("\"user_id\":", 48);
            string uid = line.substr(start+12, 22);
            
            start = line.find("\"name\"", 80);
            end = line.find(",", start);
            string name = line.substr(start + 9, end - start - 10);
            
            start = line.find("\"average_stars\"", 96);
            end = line.find(",", start+17);
            float avg_stars = atof(line.substr(start+17, end - start - 17).c_str());
            start = line.find("\"review_count\"", end);
            end = line.find(",", start);
            int review_count = atoi(line.substr(start+16, end-start-16).c_str());
            map<string, User>::iterator userIter = userMap.find(uid);
            // if (userIter != userMap.end()) 一定为真
            // id 为:KQnq1p-PlWUo-qPEtWtmMw 的用户在training_set_user里面的平均分是0,review_count是17;
            // 从review里计算的平均分是3,review_cnt是1
            if (avg_stars > 0) {
                // TESTK
                userIter->second.avgStar = avg_stars;
//.........这里部分代码省略.........
开发者ID:hustwcw,项目名称:RecSys2013,代码行数:101,代码来源:main.cpp

示例13: calcKendall

//**********************************************************************************************************************
int CorrAxesCommand::calcKendall(map<string, vector<float> >& axes, ofstream& out) {
	try {
		
		//format data
		vector< vector<spearmanRank> > scores; scores.resize(numaxes);
		for (map<string, vector<float> >::iterator it = axes.begin(); it != axes.end(); it++) {
			vector<float> temp = it->second;
			for (int i = 0; i < temp.size(); i++) {
				spearmanRank member(it->first, temp[i]);
				scores[i].push_back(member);  
			}
		}
		
		//sort each axis
		for (int i = 0; i < numaxes; i++) {  sort(scores[i].begin(), scores[i].end(), compareSpearman); }
		
		//convert scores to ranks of xi in each axis
		for (int i = 0; i < numaxes; i++) {
			
			vector<spearmanRank*> ties;
			int rankTotal = 0;
			for (int j = 0; j < scores[i].size(); j++) {
				rankTotal += (j+1);
				ties.push_back(&(scores[i][j]));
				
				if (j != scores[i].size()-1) { // you are not the last so you can look ahead
					if (scores[i][j].score != scores[i][j+1].score) { // you are done with ties, rank them and continue
						for (int k = 0; k < ties.size(); k++) {
							float thisrank = rankTotal / (float) ties.size();
  							(*ties[k]).score = thisrank;
						}
						ties.clear();
						rankTotal = 0;
					}
				}else { // you are the last one
					for (int k = 0; k < ties.size(); k++) {
						float thisrank = rankTotal / (float) ties.size();
						(*ties[k]).score = thisrank;
					}
				}
			}
		}
		
		//for each otu
		for (int i = 0; i < lookupFloat[0]->getNumBins(); i++) {
		
			if (metadatafile == "") {  out << i+1;	}
			else {  out << metadataLabels[i];		}
			
			//find the ranks of this otu - Y
			vector<spearmanRank> otuScores;
			for (int j = 0; j < lookupFloat.size(); j++) {
				spearmanRank member(lookupFloat[j]->getGroup(), lookupFloat[j]->getAbundance(i));
				otuScores.push_back(member);
			}
						
			sort(otuScores.begin(), otuScores.end(), compareSpearman);
			
			map<string, float> rankOtus;
			vector<spearmanRank> ties;
			int rankTotal = 0;
			for (int j = 0; j < otuScores.size(); j++) {
				rankTotal += (j+1);
				ties.push_back(otuScores[j]);
				
				if (j != otuScores.size()-1) { // you are not the last so you can look ahead
					if (otuScores[j].score != otuScores[j+1].score) { // you are done with ties, rank them and continue
						for (int k = 0; k < ties.size(); k++) {
							float thisrank = rankTotal / (float) ties.size();
  							rankOtus[ties[k].name] = thisrank;
						}
						ties.clear();
						rankTotal = 0;
					}
				}else { // you are the last one
					for (int k = 0; k < ties.size(); k++) {
						float thisrank = rankTotal / (float) ties.size();
						rankOtus[ties[k].name] = thisrank;
					}
				}
			}
			
			
			vector<double> pValues(numaxes);
			
			//calc spearman ranks for each axis for this otu
			for (int j = 0; j < numaxes; j++) {
			
				int numCoor = 0;
				int numDisCoor = 0;
				
				vector<spearmanRank> otus; 
				vector<spearmanRank> otusTemp;
				for (int l = 0; l < scores[j].size(); l++) {   
					spearmanRank member(scores[j][l].name, rankOtus[scores[j][l].name]);
					otus.push_back(member);
				}
				
				int count = 0;
//.........这里部分代码省略.........
开发者ID:azerxu,项目名称:mothur,代码行数:101,代码来源:corraxescommand.cpp

示例14: FH

vector<segment* > load::insert_bedgraph_to_segment_joint(map<string, vector<segment *> > A , 
	string forward, string reverse, int rank ){
	
	
	
	map<string, node> NT;
	typedef map<string, vector<segment *> >::iterator it_type_5;
	for(it_type_5 c = A.begin(); c != A.end(); c++) {
		NT[c->first] 	= node(c->second);
	}
	int start, stop, N, j;
	double coverage;
	N 	= 0,j 	= 0;
	int strand;
	int o_st, o_sp;
	vector<string> lineArray;
	string chrom, prevchrom, line;
	vector<segment *> segments;
	double center;
	vector<string> FILES(2);
	FILES[0]=forward, FILES[1]=reverse;
	string FILE;
	for (int i =0; i < 2; i++){
		if (i==0){
			strand=1;
		}else{
			strand=-1;
		}
		FILE=FILES[i];
		ifstream FH(FILE);
		if (FH){
			prevchrom="";
			while (getline(FH, line)){
				lineArray 	= splitter2(line, "\t");
				if (lineArray.size()==4){
					chrom 		= lineArray[0];
					start=stoi(lineArray[1]),stop=stoi(lineArray[2]), coverage = abs(stod(lineArray[3]));
					center 	= (stop + start) /2.;
					if (NT.find(chrom)!=NT.end()){
						vector<double> x(2);
						x[0]=center, x[1] = coverage;
						NT[chrom].insert_coverage(x, strand);
						
					}
				}
				else{
					printf("\n***error in line: %s, not bedgraph formatted\n", line.c_str() );
					segments.clear();
					return segments;
				}
			}
			FH.close();
			
		}else{
			cout<<"could not open forward bedgraph file: "<<FILE<<endl;
			segments.clear();
			return segments;
		}
	}
	//now we want to get all the intervals and make a vector<segment *> again...
	vector<segment *>NS;
	typedef map<string, node>::iterator it_type_6;
	for (it_type_6 c = NT.begin(); c!=NT.end(); c++){
		c->second.retrieve_nodes(NS);
	}

	return NS;
}
开发者ID:dmalmer,项目名称:EMG,代码行数:68,代码来源:load.cpp

示例15: test_environment

int test_environment (map<pair<enc_char, enc_char>, int> env_counts, multimap<pair<enc_char, enc_char>, vector<wstring> >& mods, TownWords& first_unigrams, TownBigrams& first_bigrams, TownWords second_unigrams, TownBigrams second_bigrams, enc_char first_char, enc_char second_char) {
  map<pair<enc_char, enc_char>, int>::iterator it3;
  int total_changed = 0;
  float diff = 0;
  TownWords unigram_counts;
  TownBigrams bigram_counts;
  merge_lists (first_unigrams, second_unigrams, unigram_counts);
  merge_lists (first_bigrams, second_bigrams, bigram_counts);
  float prev_prob = LM_POWER*find_prob (bigram_counts, orig_uni_cts, orig_bi_cts, unigram_probs, bigram_probs);
  for (it3=env_counts.begin(); it3 != env_counts.end(); it3++) {
    TownWords unigram_copy = first_unigrams;
    TownBigrams bigram_copy = first_bigrams;
    wcout << decoding[it3->first.first] << "~" << decoding[it3->first.second] << endl;
    TownWords::iterator it4;
    TownBigrams::iterator it5;
    TownWords::iterator it6;
    vector<wstring> curr_mods;
    for (it4=first_unigrams.begin(); it4 != first_unigrams.end(); it4++) {
      Word curr_word = split_word(it4->first);
      //wcout << it4->first << endl;
      if (/*second_unigrams.count(it4->first) == 0 &&*/ modify_word(it3->first, curr_word, first_char, second_char) && curr_word.size() > 0) {
	wstring combined = combine_word (curr_word);
	curr_mods.push_back (it4->first);
	//wcout << combined << endl;
	unigram_copy[combined] += it4->second;
	unigram_copy.erase (it4->first);
	for (it5=bigram_copy.begin(); it5 != bigram_copy.end(); it5++) {
	  if (it5->second.count(it4->first) == 1) {
	    it5->second[combined] += it5->second[it4->first];
	    it5->second.erase (it4->first);
	  }
	}
	for (it6=bigram_copy[it4->first].begin(); it6 != bigram_copy[it4->first].end(); it6++)
	  bigram_copy[combined][it6->first] += it6->second;
	bigram_copy.erase (it4->first);
      }
    }
    unigram_counts.clear();
    bigram_counts.clear();
    merge_lists (unigram_copy, second_unigrams, unigram_counts);
    merge_lists (bigram_copy, second_bigrams, bigram_counts);
    float curr_prob = LM_POWER*find_prob (bigram_counts, orig_uni_cts, orig_bi_cts, unigram_probs, bigram_probs) + CHANGE_BASE;
    /*int c = 0;
    TownWords::iterator it;
    TownBigrams::iterator it2;
    for (it2=first_bigrams.begin(); it2 != first_bigrams.end(); it2++) {
      for (it=it2->second.begin(); it != it2->second.end(); it++)
	c += it->second;
    }
    wcout << c << endl;
    c = 0;
    for (it2=bigram_copy.begin(); it2 != bigram_copy.end(); it2++) {
      for (it=it2->second.begin(); it != it2->second.end(); it++)
	c += it->second;
    }
    wcout << c << endl;*/
    wcout << prev_prob << endl;
    wcout << curr_prob << endl;
    diff = curr_prob - prev_prob;
    wcout << diff << endl;
    TownWords* first_replace;
    wcout << curr_mods.size() << endl;
    if (diff >= -100) {
      first_unigrams = unigram_copy;
      first_bigrams = bigram_copy;
      mods.insert (pair<pair<enc_char, enc_char>, vector<wstring> > (it3->first, curr_mods));
      total_changed += curr_mods.size();
    }
    wcout << total_changed << endl;
  }
  return total_changed;
}
开发者ID:anneCarlson,项目名称:Igbo,代码行数:72,代码来源:compare-with-lm2.cpp


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