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

C++ std::map类代码示例

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

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



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

示例1: scanInstruction

void AArch64A57FPLoadBalancing::
scanInstruction(MachineInstr *MI, unsigned Idx, 
                std::map<unsigned, Chain*> &ActiveChains,
                std::set<std::unique_ptr<Chain>> &AllChains) {
  // Inspect "MI", updating ActiveChains and AllChains.

  if (isMul(MI)) {

    for (auto &I : MI->uses())
      maybeKillChain(I, Idx, ActiveChains);
    for (auto &I : MI->defs())
      maybeKillChain(I, Idx, ActiveChains);

    // Create a new chain. Multiplies don't require forwarding so can go on any
    // unit.
    unsigned DestReg = MI->getOperand(0).getReg();

    DEBUG(dbgs() << "New chain started for register "
          << TRI->getName(DestReg) << " at " << *MI);

    auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
    ActiveChains[DestReg] = G.get();
    AllChains.insert(std::move(G));

  } else if (isMla(MI)) {

    // It is beneficial to keep MLAs on the same functional unit as their
    // accumulator operand.
    unsigned DestReg  = MI->getOperand(0).getReg();
    unsigned AccumReg = MI->getOperand(3).getReg();

    maybeKillChain(MI->getOperand(1), Idx, ActiveChains);
    maybeKillChain(MI->getOperand(2), Idx, ActiveChains);
    if (DestReg != AccumReg)
      maybeKillChain(MI->getOperand(0), Idx, ActiveChains);

    if (ActiveChains.find(AccumReg) != ActiveChains.end()) {
      DEBUG(dbgs() << "Chain found for accumulator register "
            << TRI->getName(AccumReg) << " in MI " << *MI);

      // For simplicity we only chain together sequences of MULs/MLAs where the
      // accumulator register is killed on each instruction. This means we don't
      // need to track other uses of the registers we want to rewrite.
      //
      // FIXME: We could extend to handle the non-kill cases for more coverage.
      if (MI->getOperand(3).isKill()) {
        // Add to chain.
        DEBUG(dbgs() << "Instruction was successfully added to chain.\n");
        ActiveChains[AccumReg]->add(MI, Idx, getColor(DestReg));
        // Handle cases where the destination is not the same as the accumulator.
        if (DestReg != AccumReg) {
          ActiveChains[DestReg] = ActiveChains[AccumReg];
          ActiveChains.erase(AccumReg);
        }
        return;
      }

      DEBUG(dbgs() << "Cannot add to chain because accumulator operand wasn't "
            << "marked <kill>!\n");
      maybeKillChain(MI->getOperand(3), Idx, ActiveChains);
    }

    DEBUG(dbgs() << "Creating new chain for dest register "
          << TRI->getName(DestReg) << "\n");
    auto G = llvm::make_unique<Chain>(MI, Idx, getColor(DestReg));
    ActiveChains[DestReg] = G.get();
    AllChains.insert(std::move(G));

  } else {

    // Non-MUL or MLA instruction. Invalidate any chain in the uses or defs
    // lists.
    for (auto &I : MI->uses())
      maybeKillChain(I, Idx, ActiveChains);
    for (auto &I : MI->defs())
      maybeKillChain(I, Idx, ActiveChains);

  }
}
开发者ID:A2-Collaboration,项目名称:root,代码行数:79,代码来源:AArch64A57FPLoadBalancing.cpp


示例2: load_from_xml

/// Implements Base::load_from_xml()
void Joint::load_from_xml(XMLTreeConstPtr node, std::map<std::string, BasePtr>& id_map)
{
  std::map<std::string, BasePtr>::const_iterator id_iter;

  // ***********************************************************************
  // don't verify that the node is correct, b/c Joint will 
  // be subclassed
  // ***********************************************************************
  
  // load the parent data
  Visualizable::load_from_xml(node, id_map);

  // read the lower limits, if given
  const XMLAttrib* lolimit_attr = node->get_attrib("lower-limits");
  if (lolimit_attr)
    lolimit_attr->get_vector_value(lolimit);

  // read the upper limits, if given
  const XMLAttrib* hilimit_attr = node->get_attrib("upper-limits");
  if (hilimit_attr)
    hilimit_attr->get_vector_value(hilimit);

  // read the maximum actuator force, if given
  const XMLAttrib* maxforce_attr = node->get_attrib("max-forces");
  if (maxforce_attr)
    maxforce_attr->get_vector_value(maxforce);

  // read the joint positions, if given
  const XMLAttrib* q_attr = node->get_attrib("q");
  if (q_attr)
    q_attr->get_vector_value(q);
  else
    q.set_zero(num_dof());

  // read the joint velocities, if given
  const XMLAttrib* qd_attr = node->get_attrib("qd");
  if (qd_attr)
    qd_attr->get_vector_value(qd);

  // read the joint positions, if given
  const XMLAttrib* q_init_attr = node->get_attrib("q-tare");
  if (q_init_attr)
  {
    _determine_q_tare = false;
    q_init_attr->get_vector_value(_q_tare);
  }
  else
    _determine_q_tare = true;

  // read the Coulomb friction coefficient, if given
  const XMLAttrib* fc_attr = node->get_attrib("coulomb-friction-coeff");
  if (fc_attr)
    mu_fc = fc_attr->get_real_value();

  // read the viscous friction coefficient, if given
  const XMLAttrib* fv_attr = node->get_attrib("viscous-friction-coeff");
  if (fv_attr)
    mu_fv = fv_attr->get_real_value();

  // read the restitution coefficient, if given
  const XMLAttrib* resti_attr = node->get_attrib("restitution-coeff");
  if (resti_attr)
    limit_restitution = resti_attr->get_real_value();

  // read the articulated body, if given
  const XMLAttrib* ab_attr = node->get_attrib("articulated-body-id");
  if (ab_attr)
  {
    // get the ID
    const std::string& ID = ab_attr->get_string_value();

    // look for the ID -- only warn if it is not found
    if ((id_iter = id_map.find(ID)) == id_map.end())
    {
      #ifdef _DEBUG_XML_
      std::cout << "Joint::load_from_xml() warning - ";
      std::cout << "articulated body" << std::endl << "  '" << ID << "' not ";
      std::cout << "found" << std::endl << "  ** This warning could result ";
      std::cout << "from joints being constructed before articulated bodies ";
      std::cout << std::endl << "    and may not be serious..." << std::endl; 
      std::cout << "  offending node: " << std::endl << *node;
      #endif
    }
    else
      set_articulated_body(boost::dynamic_pointer_cast<RCArticulatedBody>(id_iter->second));
  }

  // read the inboard link id, if given
  const XMLAttrib* inboard_attr = node->get_attrib("inboard-link-id");
  if (inboard_attr)
  {
    // get the ID of the inboard link
    const std::string& id = inboard_attr->get_string_value();

    // complain if the link not found but don't treat it as an error-- there 
    // are circular dependencies
    if ((id_iter = id_map.find(id)) == id_map.end())
    {
      #ifdef _DEBUG_XML_
//.........这里部分代码省略.........
开发者ID:hsu,项目名称:Moby,代码行数:101,代码来源:Joint.cpp


示例3: Stream_id


//.........这里部分代码省略.........
        }
        printf("\n");
    }
    /// returns the data in the stream
    /** The returned data is located in a static buffer shared by all streams
     *  the data is valid until the next call to get_buffer()
     */
    unsigned char *get_buffer()
    {
        int p=0;
        for (std::list<Data_segment>::iterator it = m_segments.begin();
                it != m_segments.end(); it ++)
        {
            for (unsigned int i=0; i< it->m_datasize; i++)
            {
                m_buffer[p++]=it->m_data[i];
                if (p>=0xffff)
                    return m_buffer;
            }
        }
        return m_buffer;
    }
private:
    unsigned int                m_seq;
    int                     m_ser;
    bool                    m_content;
    bool                    m_nseq;
    std::list<Data_segment> m_segments;

    static unsigned char          m_buffer[0x10000];
};
unsigned char Stream::m_buffer[0x10000];

std::map<Stream_id,Stream> g_tcp_streams;



/// assemble_tcp builds datastreams out of tcp packets
/** TCP packets are inserted into streams. When the streams are closed
 *  the contained data is returned as a pointer the data
 *  it is up to the caller to free() the memory returned.
 */
unsigned char *
assemble_tcp (
    Payload &payload,
    in6addr_t *src_ip,
    in6addr_t *dst_ip,
    unsigned short src_port,
    unsigned short dst_port,
    unsigned int *rest,
    unsigned int seq,
    unsigned char *data,
    int len,
    char syn,
    char fin,
    char rst,
    char ack)
{
    Stream_id id ( *src_ip, *dst_ip, src_port, dst_port );
    Stream   &str = g_tcp_streams[id];
    bool data_avail = false;

    if (!str.has_content())
    {
        Data_segment seg( data, len);
        str.add( syn,seq, seg);
开发者ID:pawal,项目名称:PacketQ,代码行数:67,代码来源:tcp.cpp


示例4: uthread_terminate

int uthread_terminate(int tid)
{
	blockTimer();
	if(tid == 0)//if true: exits program
	{
//		terminate all threads:
		std::map<int, Thread*>::iterator threadIt;
		for (threadIt = gThreads.begin(); threadIt != gThreads.end(); ++threadIt)
		{
			Thread* tmp;
			switch(threadIt->second->getState() )
			{
			case(READY) :
					gReady.remove(threadIt->second->getID() );
					tmp = gThreads[threadIt->second->getID() ];
					gThreads.erase(threadIt);
					delete tmp;
					break;
			case(RUNNING) :
					gThreads.erase(threadIt);
//					gRunning = NULL;
					break;
			case(BLOCKED) :
					gBlocked.erase(threadIt->second->getID() );
					tmp = gThreads[threadIt->second->getID() ];
					gThreads.erase(threadIt);
					delete tmp;
					break;
			default :
				break;
			}

		}
		delete gRunning;
		gRunning = NULL;
		resumeTimer();
		exit(0);
	}
	if(gThreads.count(tid) == 0) //if true: thread doesn't exist
	{
		std::cerr<< TERMINATE_ERR << std::endl;
		resumeTimer();
		return FAILURE;
	}
	if(gThreads[tid]->getState() == RUNNING)//if true: deletes thread +  jumps to next thread
	{
		switchThreads(TERMINATED);
	}
//	if in ready or blocked: remove from lists (gReady/gBlocked + gThreads), and delete thread
	Thread* tmp = gThreads[tid];
	if (tmp->getState() == READY )
	{
		gReady.remove(tid);
	}
	if (tmp->getState() == BLOCKED)
	{
		gBlocked.erase(tid);
	}
	gThreads.erase(tid);
	gAvailableID.push(tid);
	delete tmp;
	resumeTimer();
	return SUCCESS;
}
开发者ID:OsoFlaco,项目名称:OS,代码行数:64,代码来源:uthreads.cpp


示例5: main

int main()
{
    {
        typedef std::pair<const int, double> V;
        V ar[] =
        {
            V(1, 1.5),
            V(2, 2.5),
            V(3, 3.5),
            V(4, 4.5),
            V(5, 5.5),
            V(7, 7.5),
            V(8, 8.5),
        };
        std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(m.size() == 7);
        assert(m.at(1) == 1.5);
        m.at(1) = -1.5;
        assert(m.at(1) == -1.5);
        assert(m.at(2) == 2.5);
        assert(m.at(3) == 3.5);
        assert(m.at(4) == 4.5);
        assert(m.at(5) == 5.5);
        try
        {
            m.at(6);
            assert(false);
        }
        catch (std::out_of_range&)
        {
        }
        assert(m.at(7) == 7.5);
        assert(m.at(8) == 8.5);
        assert(m.size() == 7);
    }
    {
        typedef std::pair<const int, double> V;
        V ar[] =
        {
            V(1, 1.5),
            V(2, 2.5),
            V(3, 3.5),
            V(4, 4.5),
            V(5, 5.5),
            V(7, 7.5),
            V(8, 8.5),
        };
        const std::map<int, double> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(m.size() == 7);
        assert(m.at(1) == 1.5);
        assert(m.at(2) == 2.5);
        assert(m.at(3) == 3.5);
        assert(m.at(4) == 4.5);
        assert(m.at(5) == 5.5);
        try
        {
            m.at(6);
            assert(false);
        }
        catch (std::out_of_range&)
        {
        }
        assert(m.at(7) == 7.5);
        assert(m.at(8) == 8.5);
        assert(m.size() == 7);
    }
}
开发者ID:32bitmicro,项目名称:libcxx,代码行数:67,代码来源:at.pass.cpp


示例6: while

//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
void RigWellLogExtractor::populateReturnArrays(std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo > &uniqueIntersections)
{
    // For same MD and same cell, remove enter/leave pairs, as they only touches the wellpath, and should not contribute.
    {
        std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it1 = uniqueIntersections.begin();
        std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it2 = uniqueIntersections.begin();

        std::vector<std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator> iteratorsToIntersectonsToErase;

        while (it2 != uniqueIntersections.end())
        {
            ++it2;
            if (it2 != uniqueIntersections.end())
            {
                if (RigWellLogExtractionTools::isEqualDepth(it1->first.measuredDepth, it2->first.measuredDepth))
                {
                    if (it1->first.hexIndex == it2->first.hexIndex)
                    {
                        // Remove the two from the map, as they just are a touch of the cell surface
                        CVF_TIGHT_ASSERT(!it1->first.isEnteringCell && it2->first.isEnteringCell);

                        iteratorsToIntersectonsToErase.push_back(it1);
                        iteratorsToIntersectonsToErase.push_back(it2);
                    }
                }
            }
            ++it1;
        }

        // Erase all the intersections that is not needed
        for (size_t erItIdx = 0; erItIdx < iteratorsToIntersectonsToErase.size(); ++erItIdx)
        {
            uniqueIntersections.erase(iteratorsToIntersectonsToErase[erItIdx]);
        }
    }

    // Copy the map into a different sorting regime, with enter leave more significant than cell index

    std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo > sortedUniqueIntersections;
    {
        std::map<RigMDCellIdxEnterLeaveKey, HexIntersectionInfo >::iterator it = uniqueIntersections.begin();
        while (it != uniqueIntersections.end())
        {
            sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(it->first.measuredDepth, it->first.isEnteringCell, it->first.hexIndex),
                it->second));
            ++it;
        }
    }

    // Add points for the endpoint of the wellpath, if it starts/ends inside a cell
    {
        // Add an intersection for the well startpoint that is inside the first cell
        std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it = sortedUniqueIntersections.begin();
        if (it != sortedUniqueIntersections.end() && !it->first.isEnteringCell) // Leaving a cell as first intersection. Well starts inside a cell.
        {
            // Needs wellpath start point in front
            HexIntersectionInfo firstLeavingPoint = it->second;
            firstLeavingPoint.m_intersectionPoint =  m_wellPath->m_wellPathPoints[0];
            firstLeavingPoint.m_face = cvf::StructGridInterface::NO_FACE;
            firstLeavingPoint.m_isIntersectionEntering = true;

            sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(m_wellPath->m_measuredDepths[0], 
                                                                                      true, 
                                                                                      firstLeavingPoint.m_hexIndex),
                                                            firstLeavingPoint));
        }

        // Add an intersection for the well endpoint possibly inside the last cell.
        std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::reverse_iterator rit = sortedUniqueIntersections.rbegin();
        if (rit != sortedUniqueIntersections.rend() && rit->first.isEnteringCell) // Entering a cell as last intersection. Well ends inside a cell.
        {
            // Needs wellpath end point at end
            HexIntersectionInfo lastEnterPoint = rit->second;
            lastEnterPoint.m_intersectionPoint =  m_wellPath->m_wellPathPoints.back();
            lastEnterPoint.m_isIntersectionEntering = false;
            lastEnterPoint.m_face = cvf::StructGridInterface::NO_FACE;

            sortedUniqueIntersections.insert(std::make_pair(RigMDEnterLeaveCellIdxKey(m_wellPath->m_measuredDepths.back(), 
                                                                                      false, 
                                                                                      lastEnterPoint.m_hexIndex),
                                                            lastEnterPoint));
        }
    }

    // Filter and store the intersections pairwise as cell enter-leave pairs 
    // Discard points that does not have a match .
    {
        std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it1 = sortedUniqueIntersections.begin();
        std::map<RigMDEnterLeaveCellIdxKey, HexIntersectionInfo >::iterator it2;

        while (it1 != sortedUniqueIntersections.end())
        {
            it2 = it1;
            ++it2;

            if (it2 == sortedUniqueIntersections.end()) break;

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


示例7: write

    void OBJWriter::write(const std::shared_ptr<gameplay::Model>& model,
                          const std::string& baseName,
                          const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap1,
                          const std::map<loader::TextureLayoutProxy::TextureKey, std::shared_ptr<gameplay::Material>>& mtlMap2,
                          const glm::vec3& ambientColor) const
    {
        Expects(model != nullptr);

        auto fullPath = m_basePath / baseName;

        Assimp::Exporter exporter;
        std::string formatIdentifier;
        for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i)
        {
            auto descr = exporter.GetExportFormatDescription(i);
            BOOST_ASSERT(descr != nullptr);

            std::string exporterExtension = std::string(".") + descr->fileExtension;

            if(exporterExtension == fullPath.extension().string())
            {
                formatIdentifier = descr->id;
                break;
            }
        }

        if(formatIdentifier.empty())
        {
            BOOST_LOG_TRIVIAL(error) << "Failed to find an exporter for the supplied file extension";
            BOOST_LOG_TRIVIAL(info) << "Here's the list of registered exporters";

            for(size_t i = 0; i < exporter.GetExportFormatCount(); ++i)
            {
                auto descr = exporter.GetExportFormatDescription(i);
                BOOST_ASSERT(descr != nullptr);

                BOOST_LOG_TRIVIAL(info) << descr->description << ", extension `" << descr->fileExtension << "`, id `" << descr->id << "`";
            }

            BOOST_THROW_EXCEPTION(std::runtime_error("Failed to find an exporter for the supplied file extension"));
        }

        std::unique_ptr<aiScene> scene = std::make_unique<aiScene>();
        BOOST_ASSERT(scene->mRootNode == nullptr);
        scene->mRootNode = new aiNode();

        {
            size_t totalPartCount = 0;
            for( const auto& mesh : model->getMeshes() )
            {
                totalPartCount += mesh->getPartCount();
            }

            scene->mNumMaterials = totalPartCount;
            scene->mMaterials = new aiMaterial*[totalPartCount];
            std::fill_n(scene->mMaterials, totalPartCount, nullptr);

            scene->mNumMeshes = totalPartCount;
            scene->mMeshes = new aiMesh*[totalPartCount];
            std::fill_n(scene->mMeshes, totalPartCount, nullptr);

            scene->mRootNode->mNumMeshes = totalPartCount;
            scene->mRootNode->mMeshes = new unsigned int[totalPartCount];
            for( size_t i = 0; i < totalPartCount; ++i )
                scene->mRootNode->mMeshes[i] = i;
        }

        for( size_t mi = 0, globalPartIndex = 0; mi < model->getMeshes().size(); ++mi )
        {
            BOOST_ASSERT(mi < scene->mNumMeshes);
            const auto& mesh = model->getMeshes()[mi];

            for( size_t pi = 0; pi < mesh->getPartCount(); ++pi , ++globalPartIndex )
            {
                BOOST_ASSERT(globalPartIndex < scene->mNumMaterials);
                const std::shared_ptr<gameplay::MeshPart>& part = mesh->getPart(pi);

                scene->mMeshes[globalPartIndex] = new aiMesh();
                aiMesh* outMesh = scene->mMeshes[globalPartIndex];

                allocateElementMemory(mesh, outMesh);
                copyVertexData(mesh, outMesh);

                BOOST_ASSERT(part->getPrimitiveType() == gameplay::Mesh::PrimitiveType::TRIANGLES && part->getIndexCount() % 3 == 0);
                outMesh->mMaterialIndex = globalPartIndex;
                scene->mMaterials[globalPartIndex] = new aiMaterial();
                scene->mMaterials[globalPartIndex]->AddProperty(new aiColor4D(ambientColor.r, ambientColor.g, ambientColor.b, 1), 1, AI_MATKEY_COLOR_AMBIENT);

                {
                    // try to find the texture for our material

                    using Entry = decltype(*mtlMap1.begin());
                    auto finder = [&part](const Entry& entry)
                        {
                            return entry.second == part->getMaterial();
                        };

                    auto texIt = std::find_if(mtlMap1.begin(), mtlMap1.end(), finder);

                    bool found = false;
//.........这里部分代码省略.........
开发者ID:stohrendorf,项目名称:EdisonEngine,代码行数:101,代码来源:objwriter.cpp


示例8: UpdateAI

    void UpdateAI(const uint32 diff)
    {
        if (!UpdateVictim())
        {
            if (checkTimer < diff)
            {
                if (phase != EVENT_NULL && phase != EVENT_FIGHT)
                {
                    bool found = false;
                    for (std::map<uint64, uint8>::iterator it = prisoners.begin(); it != prisoners.end(); it++)
                    {
                        if (it->second == phase)
                        {
                            if (Creature *pPrisoner = me->GetCreature(it->first))
                            {
                                if (pPrisoner->isAlive())
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (!found)
                        DoAction(uint8(phase) +1);
                }
                checkTimer = 2000;
            }
            else
                checkTimer -= diff;

            return;
        }

        if (AcidSpray_Timer < diff)
        {
            AddSpellToCast(me->getVictim(),SPELL_SLIME_SPRAY);
            AcidSpray_Timer = urand(4000, 12000);
        }
        else
            AcidSpray_Timer -=diff;

        if (PoisonBolt_Timer < diff)
        {
            AddSpellToCast(me->getVictim(), SPELL_POISON_BOLT);
            PoisonBolt_Timer = urand(4000, 12000);;
        }
        else
            PoisonBolt_Timer -=diff;

        if (PoisonSpawn_Timer < diff)
        {
            AddSpellToCast(me, SPELL_POISON_CLOUD);
            PoisonSpawn_Timer = 20000;
        }
        else
            PoisonSpawn_Timer -=diff;

        CastNextSpellIfAnyAndReady();
        DoMeleeAttackIfReady();
    }
开发者ID:Dolmero,项目名称:L4G_Core,代码行数:62,代码来源:boss_broggok.cpp


示例9: findDistance

/* Function that returns the ID of the most dangerous neighboring plane and its ZEM. */
sim::threatContainer sim::findGreatestThreat(PlaneObject &plane1, std::map<int, PlaneObject> &planes) {
    
	/* Set reference for origin (Northwest corner of the course)*/
	sim::coordinate origin;
	origin.latitude = 32.606573;
	origin.longitude = -85.490356;
	origin.altitude = 400;
    
	/* Set preliminary plane to avoid as non-existent and most dangerous ZEM as negative */
	int planeToAvoid = -1;
	int iPlaneToAvoid = -1;
	double mostDangerousZEM = -1.0;
	double iMostDangerousZEM = -1.0;
    
	/* Set the preliminary time-to-go high */
	double minimumTimeToGo = MINIMUM_TIME_TO_GO;
	double iMinimumTimeToGo = 3.5;

	/* Declare second plane and ID variable */
	PlaneObject plane2;
	int ID;
    
	/* Make a position vector representation of the current plane */
	double magnitude2, direction2;
	double magnitude = findDistance(origin.latitude, origin.longitude, 
		plane1.getCurrentLoc().latitude, plane1.getCurrentLoc().longitude);
	double direction = findAngle(origin.latitude, origin.longitude, 
		plane1.getCurrentLoc().latitude, plane1.getCurrentLoc().longitude);
	sim::mathVector p1(magnitude,direction);

	/* Make a heading vector representation of the current plane */
	sim::mathVector d1(1.0,toCartesian(plane1.getCurrentBearing()));
	
	/* Declare variables needed for this loop */
	sim::mathVector pDiff, dDiff;
	double timeToGo, zeroEffortMiss, distanceBetween, timeToDest, bearingDiff;
	std::map<int,sim::PlaneObject>::iterator it;
    
	for (it=planes.begin() ; it!= planes.end(); it++) {
		/* Unpacking plane to check */		
		ID = (*it).first;
		plane2 = (*it).second;
		
		/* If it's not in the Check Zone, check the other plane */
		distanceBetween = plane1.findDistance(plane2);
		if (distanceBetween > CHECK_ZONE || plane1.getID() == ID) continue;

		/* Making a position vector representation of plane2 */
		magnitude2 = findDistance(origin.latitude, origin.longitude, 
			plane2.getCurrentLoc().latitude, plane2.getCurrentLoc().longitude);
		direction2 = findAngle(origin.latitude, origin.longitude, 
			plane2.getCurrentLoc().latitude, plane2.getCurrentLoc().longitude);
		sim::mathVector p2(magnitude2,direction2);

		/* Make a heading vector representation of the other plane */
		sim::mathVector d2(1.0,toCartesian(plane2.getCurrentBearing()));

		/* Compute time-to-go */
		pDiff = p1-p2;
		dDiff = d1-d2;
		timeToGo = -1.0*pDiff.dotProduct(dDiff)/(MPS_SPEED*dDiff.dotProduct(dDiff));
		

		/* Compute Zero Effort Miss */
		zeroEffortMiss = sqrt(fabs(pDiff.dotProduct(pDiff) + 
			2.0*(MPS_SPEED*timeToGo)*pDiff.dotProduct(dDiff) + 
			pow(MPS_SPEED*timeToGo,2.0)*dDiff.dotProduct(dDiff)));
		
		if( zeroEffortMiss > DANGER_ZEM || (timeToGo > minimumTimeToGo && timeToGo > iMinimumTimeToGo) || timeToGo < 0 ) continue;
        
		timeToDest = plane1.findDistance(plane1.getDestination().latitude, 
			plane1.getDestination().longitude) / MPS_SPEED;

		/* If you're close to your destination and the other plane isn't
		much of a threat, then don't avoid it */ 
		if ( timeToDest < 5.0 && zeroEffortMiss > 3.0*MPS_SPEED ) continue;

		/* If you're likely to zigzag, don't avoid the other plane */
		bearingDiff = fabs(plane1.getCurrentBearing() - planes[ID].getCurrentBearing());
		if ( plane1.findDistance(planes[ID]) > 3.5*MPS_SPEED &&  bearingDiff < CHATTERING_ANGLE) continue;

		/* Second Threshold, to prevent planes from flying into others when trying to avoid less imminent collisions */
		if ( zeroEffortMiss <= SECOND_THRESHOLD && timeToGo <= iMinimumTimeToGo ) {
			iPlaneToAvoid = ID;
			iMostDangerousZEM = zeroEffortMiss;
			iMinimumTimeToGo = timeToGo;
			continue;
		}

		planeToAvoid = ID;
		mostDangerousZEM = zeroEffortMiss;
		minimumTimeToGo = timeToGo;
	}

	sim::threatContainer greatestThreat;
	if (iPlaneToAvoid > -1) {
		greatestThreat.planeID = iPlaneToAvoid;
		greatestThreat.ZEM = iMostDangerousZEM;
		greatestThreat.timeToGo = iMinimumTimeToGo;		
//.........这里部分代码省略.........
开发者ID:CptMacHammer,项目名称:sim,代码行数:101,代码来源:ripna.cpp


示例10: outputLog

namespace cocos2d { namespace plugin {

#define JAVAVM    cocos2d::PluginJniHelper::getJavaVM()

void PluginUtils::initPluginWrapper(android_app* app)
{
    PluginJniMethodInfo t;
    if (! PluginJniHelper::getStaticMethodInfo(t
        , "org/cocos2dx/plugin/PluginWrapper"
        , "initFromNativeActivity"
        , "(Landroid/app/Activity;)V"))
    {
        outputLog("PluginUtils", "Failed to init context of plugin");
        return;
    }

    t.env->CallStaticVoidMethod(t.classID, t.methodID, app->activity->clazz);
    t.env->DeleteLocalRef(t.classID);
}

jobject PluginUtils::createJavaMapObject(std::map<std::string, std::string>* paramMap)
{
    JNIEnv* env = getEnv();
	jclass class_Hashtable = env->FindClass("java/util/Hashtable");
	jmethodID construct_method = env->GetMethodID( class_Hashtable, "<init>","()V");
	jobject obj_Map = env->NewObject( class_Hashtable, construct_method, "");
	if (paramMap != NULL)
	{
		jmethodID add_method= env->GetMethodID( class_Hashtable,"put","(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
		for (std::map<std::string, std::string>::const_iterator it = paramMap->begin(); it != paramMap->end(); ++it)
		{
			env->CallObjectMethod(obj_Map, add_method, env->NewStringUTF(it->first.c_str()), env->NewStringUTF(it->second.c_str()));
		}
	}
    env->DeleteLocalRef(class_Hashtable);
    return obj_Map;
}

void PluginUtils::initJavaPlugin(PluginProtocol* pPlugin, jobject jObj, const char* className)
{
	cocos2d::plugin::PluginJavaData* pUserData = new cocos2d::plugin::PluginJavaData();
	pUserData->jobj = PluginUtils::getEnv()->NewGlobalRef(jObj);
	pUserData->jclassName = className;
	cocos2d::plugin::PluginUtils::setPluginJavaData(pPlugin, pUserData);
}

JNIEnv* PluginUtils::getEnv()
{
    bool bRet = false;
    JNIEnv* env = NULL;
    do 
    {
        if (JAVAVM->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK)
        {
        	outputLog("PluginUtils", "Failed to get the environment using GetEnv()");
            break;
        }

        if (JAVAVM->AttachCurrentThread(&env, 0) < 0)
        {
            outputLog("PluginUtils", "Failed to get the environment using AttachCurrentThread()");
            break;
        }

        bRet = true;
    } while (0);        

    if (!bRet) {
    	env = NULL; 
    }

    return env;
}

std::map<PluginProtocol*, PluginJavaData*> s_PluginObjMap;
std::map<std::string, PluginProtocol*> s_JObjPluginMap;

typedef std::map<PluginProtocol*, PluginJavaData*>::iterator ObjMapIter;
typedef std::map<std::string, PluginProtocol*>::iterator JObjPluginMapIter;

PluginJavaData* PluginUtils::getPluginJavaData(PluginProtocol* pKeyObj)
{
    PluginJavaData* ret = NULL;
    ObjMapIter it = s_PluginObjMap.find(pKeyObj);
    if (it != s_PluginObjMap.end()) {
        ret = it->second;
    }

    return ret;
}

PluginProtocol* PluginUtils::getPluginPtr(std::string className)
{
	PluginProtocol* ret = NULL;
	JObjPluginMapIter it = s_JObjPluginMap.find(className);
	if (it != s_JObjPluginMap.end()) {
		ret = it->second;
	}

	return ret;
//.........这里部分代码省略.........
开发者ID:1007650105,项目名称:RockChipmunk2D,代码行数:101,代码来源:PluginUtils.cpp


示例11: create_process

void delegate_runner::create_process() {
    char path[MAX_PATH + 1];

    if (GetFullPathNameA(program_to_run.c_str(), MAX_PATH, path, NULL))
    {
        program_to_run = path;
    }

    options.push_argument_front(program_to_run);

    if (options.use_cmd)
    {
        options.push_argument_front("--cmd");
    }

    options.use_cmd = true;

    const std::map< restriction_kind_t, std::string > cmd_units = {
        { restriction_user_time_limit, "ms" },
        { restriction_memory_limit, "B" },
        { restriction_processor_time_limit, "us" },
        { restriction_security_limit, "" },
        { restriction_write_limit, "B" },
        { restriction_load_ratio, "" },
        { restriction_idle_time_limit, "us" },
        { restriction_processes_count_limit, "" }
    };

    const std::map< restriction_kind_t, std::string > cmd_arg = {
        { restriction_user_time_limit, "tl" },
        { restriction_memory_limit, "ml" },
        { restriction_processor_time_limit, "d" },
        { restriction_security_limit, "s" },
        { restriction_write_limit, "wl" },
        { restriction_load_ratio, "lr" },
        { restriction_idle_time_limit, "y" },
        { restriction_processes_count_limit, "only-process" }
    };

    for (int i = 0; i < restriction_max; ++i)
    {
        if (restrictions.restrictions[i] != restriction_no_limit)
        {
            std::string argument = "-" + cmd_arg.find((restriction_kind_t)i)->second;

            argument += " " + std::to_string(restrictions.restrictions[i]);
            argument += cmd_units.find((restriction_kind_t)i)->second;

            options.push_argument_front(argument);
        }
    }

    auto process_pipes = [](options_class& options, const std::vector<std::string>& vals, const std::string& prefix) {
        for (auto i = vals.cbegin(); i != vals.cend(); ++i)
        {
            options.push_argument_front(prefix + *i);
        }
    };

    process_pipes(options, options.stderror, "--err=");
    process_pipes(options, options.stdoutput, "--out=");
    process_pipes(options, options.stdinput, "--in=");

    std::string working_directory = options.working_directory;

    if (working_directory.length() == 0)
    {
        char dir[MAX_PATH + 1];

        GetCurrentDirectoryA(MAX_PATH, dir);

        working_directory = dir;
    }

    options.push_argument_front("-wd \"" + working_directory + "\"");

    if (options.hide_report)
    {
        options.push_argument_front("-hr 1");
    }

    for (auto i = options.environmentVars.cbegin(); i != options.environmentVars.cend(); ++i)
    {
        options.push_argument_front("-D " + i->first + "=" + i->second);
    }

    if (options.json)
    {
        options.push_argument_front("--json");
    }

    options.push_argument_front("-env " + options.environmentMode);

    std::string shared_memory_name = "mem" + options.session.hash();

    options.push_argument_front("--shared-memory=" + shared_memory_name);

    CreateFileMappingA(
        INVALID_HANDLE_VALUE,
        NULL,
//.........这里部分代码省略.........
开发者ID:BabichMikhail,项目名称:Spawner,代码行数:101,代码来源:delegate.cpp


示例12: genControlInfo

void genControlInfo(int* oid,
                    size_t oid_size,
                    QueryData& results,
                    const std::map<std::string, std::string>& config) {
  Row r;
  if (oid_size == 0) {
    return;
  }

  r["oid"] = stringFromMIB(oid, oid_size);
  // Request the description (the canonical name) for the MIB.
  char response[CTL_MAX_VALUE] = {0};
  size_t response_size = CTL_MAX_VALUE;

  int request[CTL_MAXNAME + 2] = {0, CTL_DEBUG_DESCRIPTION};
  memcpy(request + 2, oid, oid_size * sizeof(int));
  if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) {
    return;
  }

  r["name"] = std::string(response);
  if (oid[0] > 0 && oid[0] < static_cast<int>(kControlNames.size())) {
    r["subsystem"] = kControlNames[oid[0]];
  }

  // Now request structure type.
  response_size = CTL_MAX_VALUE;
  request[1] = CTL_DEBUG_TYPE;
  if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) {
    // Cannot request MIB type (int, string, struct, etc).
    return;
  }

  size_t oid_type = 0;
  if (response_size > 0) {
    oid_type = ((size_t)response[0] & CTLTYPE);
    if ((oid_type == 0 || oid_type == CTLTYPE_INT) && response_size > 4) {
      // For whatever reason, macOS defines fewer CTLTYPE's than BSD, and
      // sometimes uses the format character instead of (or in addition to)
      // the CTLTYPE to specify the type. Here we detect a few such cases and
      // map them to CTLTYPE's.
      // TODO: Both CTLTYPE_INT and CTLTYPE_QUAD can be specified as unsigned
      // using a similar method.
      char type_char = response[4];
      switch (type_char) {
      case 'I':
        oid_type = CTLTYPE_INT;
        break;
      case 'L':
        if (sizeof(long) == sizeof(long long)) {
          oid_type = CTLTYPE_QUAD;
        } else if (sizeof(long) == sizeof(int)) {
          oid_type = CTLTYPE_INT;
        }
        break;
      case 'S':
        oid_type = CTLTYPE_STRUCT;
        break;
      case 'Q':
        oid_type = CTLTYPE_QUAD;
        break;
        // Otherwise leave the type as it was; we have no additional knowledge
      }
    }
    if (oid_type < kControlTypes.size()) {
      r["type"] = kControlTypes[oid_type];
    }
  }

  // Finally request MIB value.
  if (oid_type > CTLTYPE_NODE && oid_type < CTLTYPE_OPAQUE) {
    size_t value_size = 0;
    sysctl(oid, oid_size, 0, &value_size, 0, 0);

    if (value_size > CTL_MAX_VALUE) {
      // If the value size is larger than the max value, limit.
      value_size = CTL_MAX_VALUE;
    }

    sysctl(oid, oid_size, response, &value_size, 0, 0);
    if (oid_type == CTLTYPE_INT) {
      unsigned int value;
      memcpy(&value, response, sizeof(int));
      r["current_value"] = INTEGER(value);
    } else if (oid_type == CTLTYPE_STRING) {
      r["current_value"] = std::string(response);
    } else if (oid_type == CTLTYPE_QUAD) {
      unsigned long long value;
      memcpy(&value, response, sizeof(unsigned long long));
      r["current_value"] = INTEGER(value);
    }
  }

  // If this MIB was set using sysctl.conf add the value.
  if (config.count(r.at("name")) > 0) {
    r["config_value"] = config.at(r["name"]);
  }

  results.push_back(r);
}
开发者ID:theopolis,项目名称:osquery,代码行数:100,代码来源:sysctl_utils.cpp


示例13: ListArguments

inline void Symbol::InferExecutorArrays(
    const Context &context, std::vector<NDArray> *arg_arrays,
    std::vector<NDArray> *grad_arrays, std::vector<OpReqType> *grad_reqs,
    std::vector<NDArray> *aux_arrays,
    const std::map<std::string, NDArray> &args_map,
    const std::map<std::string, NDArray> &arg_grad_store,
    const std::map<std::string, OpReqType> &grad_req_type,
    const std::map<std::string, NDArray> &aux_map) const {

  const auto arg_name_list = ListArguments();
  std::vector<std::vector<mx_uint> > in_shapes, aux_shapes, out_shapes;
  std::map<std::string, std::vector<mx_uint> > arg_shapes;

  for (const auto &arg_name : arg_name_list) {
    auto iter = args_map.find(arg_name);
    if (iter != args_map.end()) {
      arg_shapes[arg_name] = iter->second.GetShape();
    }
  }

  InferShape(arg_shapes, &in_shapes, &aux_shapes, &out_shapes);

  for (size_t i = 0; i < in_shapes.size(); ++i) {
    const auto &shape = in_shapes[i];
    const auto &arg_name = arg_name_list[i];
    auto iter_arg = args_map.find(arg_name);
    if (iter_arg != args_map.end()) {
      arg_arrays->push_back(iter_arg->second);
    } else {
      arg_arrays->push_back(NDArray(shape, context, false));
      NDArray::SampleGaussian(0, 1, &arg_arrays->back());
    }
    auto iter_grad = arg_grad_store.find(arg_name);
    if (iter_grad != arg_grad_store.end()) {
      grad_arrays->push_back(iter_grad->second);
    } else {
      grad_arrays->push_back(NDArray(shape, context, false));
    }
    auto iter_req = grad_req_type.find(arg_name);
    if (iter_req != grad_req_type.end()) {
      grad_reqs->push_back(iter_req->second);
    } else if (arg_name.rfind("data") == arg_name.length() - 4
            || arg_name.rfind("label") == arg_name.length() - 5) {
      grad_reqs->push_back(OpReqType::kNullOp);
    } else {
      grad_reqs->push_back(OpReqType::kWriteTo);
    }
  }

  const auto aux_name_list = ListAuxiliaryStates();
  for (size_t i = 0; i < aux_shapes.size(); ++i) {
    const auto &shape = aux_shapes[i];
    const auto &aux_name = aux_name_list[i];
    auto iter_aux = aux_map.find(aux_name);
    if (iter_aux != aux_map.end()) {
      aux_arrays->push_back(iter_aux->second);
    } else {
      aux_arrays->push_back(NDArray(shape, context, false));
      NDArray::SampleGaussian(0, 1, &aux_arrays->back());
    }
  }
}
开发者ID:CoderHHX,项目名称:incubator-mxnet,代码行数:62,代码来源:symbol.hpp


示例14: initializeMemoryManagement

namespace Platform {

#ifdef OLYMPIA_LINUX_USE_MMAP
static std::map<void*, int> s_blockSizes;
#endif

void initializeMemoryManagement()
{
    return;
}

unsigned pageSize()
{
#if defined(OLYMPIA_LINUX) || defined(OLYMPIA_MAC)
    return sysconf(_SC_PAGE_SIZE);
#elif defined(OLYMPIA_WINDOWS)
    SYSTEM_INFO system_info;
    GetSystemInfo(&system_info);
    return system_info.dwPageSize;
#endif
}

void* allocateJSBlock(unsigned size)
{
    // See: JavaScriptCore/runtime/Collector.cpp
    OLYMPIA_ASSERT(size == BLOCK_SIZE);
#if defined(OLYMPIA_LINUX) //|| defined(OLYMPIA_MAC)
#if ENABLE(JSC_MULTIPLE_THREADS)
#error Need to initialize pagesize safely.
#endif
    static size_t pagesize = pageSize();

    size_t extra = 0;
    if (BLOCK_SIZE > pagesize)
        extra = BLOCK_SIZE - pagesize;

    void* mmapResult = mmap(NULL, BLOCK_SIZE + extra, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
    uintptr_t address = reinterpret_cast<uintptr_t>(mmapResult);

    size_t adjust = 0;
    if ((address & BLOCK_OFFSET_MASK) != 0)
        adjust = BLOCK_SIZE - (address & BLOCK_OFFSET_MASK);

    if (adjust > 0)
        munmap(reinterpret_cast<char*>(address), adjust);

    if (adjust < extra)
        munmap(reinterpret_cast<char*>(address + adjust + BLOCK_SIZE), extra - adjust);

    address += adjust;
    return reinterpret_cast<void*>(address);
#elif defined(OLYMPIA_WINDOWS)
#if COMPILER(MINGW) && !COMPILER(MINGW64)
    void* address = __mingw_aligned_malloc(BLOCK_SIZE, BLOCK_SIZE);
#else
    void* address = _aligned_malloc(BLOCK_SIZE, BLOCK_SIZE);
#endif
    memset(address, 0, BLOCK_SIZE);
	return address;
#elif defined(OLYMPIA_MAC)
    vm_address_t address = 0;
    vm_map(current_task(), &address, BLOCK_SIZE, BLOCK_OFFSET_MASK, VM_FLAGS_ANYWHERE | VM_TAG_FOR_COLLECTOR_MEMORY, MEMORY_OBJECT_NULL, 0, FALSE, VM_PROT_DEFAULT, VM_PROT_DEFAULT, VM_INHERIT_DEFAULT);
    return reinterpret_cast<void*>(address);
#endif
}

void freeJSBlock(void* address)
{
#if defined(OLYMPIA_LINUX)// || defined(OLYMPIA_MAC)
    munmap(reinterpret_cast<char*>(address), BLOCK_SIZE);
#elif defined(OLYMPIA_WINDOWS)
#if COMPILER(MINGW) && !COMPILER(MINGW64)
    __mingw_aligned_free(block);
#else
    _aligned_free(address);
#endif
#elif defined(OLYMPIA_MAC)
    vm_deallocate(current_task(), reinterpret_cast<vm_address_t>(address), BLOCK_SIZE);
#endif
} 

void* reserveVirtualMemory(size_t& totalBytes)
{
#ifdef OLYMPIA_LINUX
#ifdef OLYMPIA_LINUX_USE_MMAP
    void* p = mmap(0, totalBytes, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
    if (p != MAP_FAILED)
        s_blockSizes[p] = totalBytes;
    return p;
#else
    return malloc(totalBytes);
#endif
#elif defined(OLYMPIA_WINDOWS)
    return VirtualAlloc(0, totalBytes, MEM_RESERVE, PAGE_READWRITE);
#elif defined(OLYMPIA_MAC)
    return malloc(totalBytes);
#else
    OLYMPIA_CRASH();
#endif
}
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:


示例15: LoadGLTextures

该文章已有0人参与评论

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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