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


C++ prev函数代码示例

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


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

示例1: findLadders

    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
    
        dict.insert(start);
        dict.insert(end);
         
        vector<string> vdict(dict.begin(), dict.end()); // vector dictionary: id -> word mapping in dict
        unordered_map<string, int> ids;  // index dictionary: word -> id mapping in vdict
        vector<vector<int> > prev(dict.size()); // store the previous words in BFS
        vector<int> distance(dict.size(), -1); // store the distance from start
         
        // build string - index mapping, transfer problem to graph search
        // use interger instead of string to eliminate cost of string matching
        for(int i = 0; i < vdict.size(); i++)
            ids[vdict[i]] = i;        

        
        // find the index of start and end words
        int vbeg=0, vend=0;
        while(vdict[vbeg] != start) vbeg++;
        while(vdict[vend] != end) vend++;
         
        // use queue for BFS to search path from start to end
        queue<int> que;
        que.push(vbeg);
        distance[vbeg]=0;
        
        while(!que.empty()){
            int now =  que.front();
            que.pop();
            
            if(now == vend){
                break;
            }
            
            int d = distance[now]+1;
            
            vector<int> adj;
            ids.erase(vdict[now]);
            
            for(int i = 0; i < vdict[now].size(); i ++){
                char w = vdict[now][i];
                for(char j = 'a'; j <= 'z'; j ++){
                    vdict[now][i] = j;
                    if(ids.count(vdict[now])){
                        adj.push_back(ids[vdict[now]]);
                    }
                    vdict[now][i] = w;
                }
            }
            
            
            for(int i = 0; i < adj.size(); i ++){
                if(distance[adj[i]] == -1){
                    distance[adj[i]] = d;
                    que.push(adj[i]);
                    prev[adj[i]].push_back(now);
                    
                }
                else if(distance[adj[i]] == d){
                    prev[adj[i]].push_back(now);
                }
            }
            
        }
        

        results.clear();
        path.clear();
        genpath(vbeg, vend, vdict, prev, path);
        return results;
        
    }
开发者ID:vincentpc,项目名称:leetcode,代码行数:75,代码来源:wordladder2.cpp

示例2: add_pack


//.........这里部分代码省略.........
	    return;
	}
	else
	    obj->o_flags |= ISFOUND;

    inpack++;
    if (from_floor)
    {
	detach(lvl_obj, item);
	mvaddch(hero.y, hero.x, (roomin(&hero) == NULL ? PASSAGE : FLOOR));
    }
    /*
     * Search for an object of the same type
     */
    exact = FALSE;
    for (ip = pack; ip != NULL; ip = next(ip))
    {
	op = (struct object *) ldata(ip);
	if (obj->o_type == op->o_type)
	    break;
    }
    if (ip == NULL)
    {
	/*
	 * Put it at the end of the pack since it is a new type
	 */
	for (ip = pack; ip != NULL; ip = next(ip))
	{
	    op = (struct object *) ldata(ip);
	    if (op->o_type != FOOD)
		break;
	    lp = ip;
	}
    }
    else
    {
	/*
	 * Search for an object which is exactly the same
	 */
	while (ip != NULL && op->o_type == obj->o_type)
	{
	    if (op->o_which == obj->o_which)
	    {
		exact = TRUE;
		break;
	    }
	    lp = ip;
	    if ((ip = next(ip)) == NULL)
		break;
	    op = (struct object *) ldata(ip);
	}
    }
    if (ip == NULL)
    {
	/*
	 * Didn't find an exact match, just stick it here
	 */
	if (pack == NULL)
	    pack = item;
	else
	{
	    lp->l_next = item;
	    item->l_prev = lp;
	    item->l_next = NULL;
	}
    }
    else
    {
	/*
	 * If we found an exact match.  If it is a potion, food, or a 
	 * scroll, increase the count, otherwise put it with its clones.
	 */
	if (exact && ISMULT(obj->o_type))
	{
	    op->o_count++;
	    discard(item);
	    item = ip;
	    goto picked_up;
	}
	if ((item->l_prev = prev(ip)) != NULL)
	    item->l_prev->l_next = item;
	else
	    pack = item;
	item->l_next = ip;
	ip->l_prev = item;
    }
picked_up:
    /*
     * Notify the user
     */
    obj = (struct object *) ldata(item);
    if (notify && !silent)
    {
	if (!terse)
	    addmsg("You now have ");
	msg("%s (%c)", inv_name(obj, !terse), pack_char(obj));
    }
    if (obj->o_type == AMULET)
	amulet = TRUE;
}
开发者ID:RoguelikeRestorationProject,项目名称:rogue3.6,代码行数:101,代码来源:pack.c

示例3: erase

 void erase(set<SetElem>::iterator it) {
     if (it != data.begin())
         prev(it)->next = it->next;
     data.erase(it);
 }
开发者ID:bicsi,项目名称:code_snippets,代码行数:5,代码来源:linear_convex_set.cpp

示例4: findNodeOrientation

 bool findNodeOrientation (const TrigCyclIter &cur, bool convex, bool convexInit)
 {
   TrigCyclIter prev( cur ); --prev;
   TrigCyclIter next( cur ); ++next;
   return findNodeOrientation( *prev, *cur, *next, convex, convexInit );
 }
开发者ID:ileben,项目名称:GameEngine,代码行数:6,代码来源:gePolyMesh.cpp

示例5: maktab

void
maktab(void)			/* define the tab stops of the table */
{
	int	icol, ilin, tsep, k, ik, vforml, il, s, text;
	char	*ss;

	for (icol = 0; icol < ncol; icol++) {
		doubled[icol] = acase[icol] = 0;
		Bprint(&tabout, ".nr %2s 0\n", reg(icol, CRIGHT));
		for (text = 0; text < 2; text++) {
			if (text)
				Bprint(&tabout, ".%2s\n.rm %2s\n", reg(icol, CRIGHT),
				    reg(icol, CRIGHT));
			for (ilin = 0; ilin < nlin; ilin++) {
				if (instead[ilin] || fullbot[ilin]) 
					continue;
				vforml = ilin;
				for (il = prev(ilin); il >= 0 && vspen(table[il][icol].col); il = prev(il))
					vforml = il;
				if (fspan(vforml, icol)) 
					continue;
				if (filler(table[ilin][icol].col)) 
					continue;
				if ((flags[icol][stynum[ilin]] & ZEROW) != 0) 
					continue;
				switch (ctype(vforml, icol)) {
				case 'a':
					acase[icol] = 1;
					ss = table[ilin][icol].col;
					s = (int)(uintptr)ss;
					if (s > 0 && s < 128 && text) {
						if (doubled[icol] == 0)
							Bprint(&tabout, ".nr %d 0\n.nr %d 0\n",
							    S1, S2);
						doubled[icol] = 1;
						Bprint(&tabout, ".if \\n(%c->\\n(%d .nr %d \\n(%c-\n",
						    s, S2, S2, (int)s);
					}
				case 'n':
					if (table[ilin][icol].rcol != 0) {
						if (doubled[icol] == 0 && text == 0)
							Bprint(&tabout, ".nr %d 0\n.nr %d 0\n",
							    S1, S2);
						doubled[icol] = 1;
						if (real(ss = table[ilin][icol].col) && !vspen(ss)) {
							s = (int)(uintptr)ss;
							if (tx(s) != text) 
								continue;
							Bprint(&tabout, ".nr %d ", TMP);
							wide(ss, FN(vforml, icol), SZ(vforml, icol)); 
							Bprint(&tabout, "\n");
							Bprint(&tabout, ".if \\n(%d<\\n(%d .nr %d \\n(%d\n",
							    S1, TMP, S1, TMP);
						}
						if (text == 0 && real(ss = table[ilin][icol].rcol) && !vspen(ss) && !barent(ss)) {
							Bprint(&tabout, ".nr %d \\w%c%s%c\n",
							    TMP, F1, ss, F1);
							Bprint(&tabout, ".if \\n(%d<\\n(%d .nr %d \\n(%d\n", S2, TMP, S2,
							     TMP);
						}
						continue;
					}
				case 'r':
				case 'c':
				case 'l':
					if (real(ss = table[ilin][icol].col) && !vspen(ss)) {
						s = (int)(uintptr)ss;
						if (tx(s) != text) 
							continue;
						Bprint(&tabout, ".nr %d ", TMP);
						wide(ss, FN(vforml, icol), SZ(vforml, icol)); 
						Bprint(&tabout, "\n");
						Bprint(&tabout, ".if \\n(%2s<\\n(%d .nr %2s \\n(%d\n",
						     reg(icol, CRIGHT), TMP, reg(icol, CRIGHT), TMP);
					}
				}
			}
		}
		if (acase[icol]) {
			Bprint(&tabout, ".if \\n(%d>=\\n(%2s .nr %2s \\n(%du+2n\n", 
			     S2, reg(icol, CRIGHT), reg(icol, CRIGHT), S2);
		}
		if (doubled[icol]) {
			Bprint(&tabout, ".nr %2s \\n(%d\n", reg(icol, CMID), S1);
			Bprint(&tabout, ".nr %d \\n(%2s+\\n(%d\n", TMP, reg(icol, CMID), S2);
			Bprint(&tabout, ".if \\n(%d>\\n(%2s .nr %2s \\n(%d\n", TMP,
			    reg(icol, CRIGHT), reg(icol, CRIGHT), TMP);
			Bprint(&tabout, ".if \\n(%d<\\n(%2s .nr %2s +(\\n(%2s-\\n(%d)/2\n",
			     TMP, reg(icol, CRIGHT), reg(icol, CMID), reg(icol, CRIGHT), TMP);
		}
		if (cll[icol][0]) {
			Bprint(&tabout, ".nr %d %sn\n", TMP, cll[icol]);
			Bprint(&tabout, ".if \\n(%2s<\\n(%d .nr %2s \\n(%d\n",
			    reg(icol, CRIGHT), TMP, reg(icol, CRIGHT), TMP);
		}
		for (ilin = 0; ilin < nlin; ilin++)
			if (k = lspan(ilin, icol)) {
				ss = table[ilin][icol-k].col;
				if (!real(ss) || barent(ss) || vspen(ss) ) 
					continue;
//.........这里部分代码省略.........
开发者ID:Earnestly,项目名称:plan9,代码行数:101,代码来源:t6.c

示例6: prev

bool Vertex::angleIsConvex() {
    SkPoint vPrev = prev()->point() - point(),
            vNext = next()->point() - point();
    // TODO(turk): There might be overflow in fixed-point.
    return SkPoint::CrossProduct(vNext, vPrev) >= 0;
}
开发者ID:angerangel,项目名称:livecode-thirdparty,代码行数:6,代码来源:SkConcaveToTriangles.cpp

示例7: convert_arc

void 
convert_arc(const dimeEntity *entity, const dimeState *state, 
	    dxfLayerData *layerData, dxfConverter *converter)
{
  dimeArc *arc = (dimeArc*) entity;

  dimeMatrix matrix;
  state->getMatrix(matrix);

  dimeVec3f e = arc->getExtrusionDir();
  dxfdouble thickness = arc->getThickness();

  if (e != dimeVec3f(0,0,1)) {
    dimeMatrix m;
    dimeEntity::generateUCS(e, m);
    matrix.multRight(m);
  }
  e = dimeVec3f(0,0,1);

  dimeVec3f center;
  arc->getCenter(center);

  dimeParam param;
  if (arc->getRecord(38, param)) {
    center[2] = param.double_data;
  }
  
  dxfdouble radius = arc->getRadius();
  
  double end = arc->getEndAngle();

  while (end < arc->getStartAngle()) {
    end += 360.0;
  }

  double delta = DXFDEG2RAD(end - arc->getStartAngle());

  if (delta == 0.0) {
#ifndef NDEBUG
    fprintf(stderr,"ARC with startAngle == endAngle!\n");
#endif
    end += 2*M_PI;
    delta = DXFDEG2RAD(end - arc->getStartAngle());
  }
  
  int ARC_NUMPTS = converter->getNumSub();
  if (ARC_NUMPTS <= 0) { // use maxerr
    ARC_NUMPTS = calc_num_sub(converter->getMaxerr(), radius);
  }

  // find the number of this ARC that fits inside 2PI
  int parts = (int) DXFABS((2*M_PI) / delta);
  
  // find # pts to use for arc
  // add one to avoid arcs with 0 line segments
  int numpts = ARC_NUMPTS / parts + 1;
  if (numpts > ARC_NUMPTS) numpts = ARC_NUMPTS;
  
  double inc = delta / numpts;
  double rad = DXFDEG2RAD(arc->getStartAngle());
  int i;

  dimeVec3f v;
  dimeVec3f prev(center[0] + radius * cos(rad),
		 center[1] + radius * sin(rad),
		 center[2]);
  rad += inc;
  
  for (i = 1; i < numpts; i++) {
    v = dimeVec3f(center[0] + radius * cos(rad),
		  center[1] + radius * sin(rad),
		  center[2]);
    if (thickness == 0.0) {
      layerData->addLine(prev, v, &matrix);
    }
    else {
      layerData->addQuad(prev, v, v + e * thickness, prev + e * thickness,
			 &matrix);
    }
    prev = v;
    rad += inc;
  }
  rad = DXFDEG2RAD(end);
  v = dimeVec3f(center[0] + radius * cos(rad),
		center[1] + radius * sin(rad),
		center[2]);
  if (thickness == 0.0) {
    layerData->addLine(prev, v, &matrix);
  }
  else {
    layerData->addQuad(prev, v, v + e * thickness, prev + e * thickness,
		       &matrix);
  }
}
开发者ID:Alexpux,项目名称:dime,代码行数:94,代码来源:arcconvert.cpp

示例8: switch

void Posture::toWelcome(int i)
{
	int count = 0;
	ModelVideo model;
	if (i > models.size() - 1 || i == -1)
	{
		if (i == -1)
			models.clear();
		m_pmPageManager.GetModel(models, i);

		if (i != -1)
		{
			m_iPage = i / MAXATONCE;
			count = models.size() - (m_iPage)*MAXATONCE;
		}
		else
		{
			i = 0;
			m_iPage = 0;
			count = models.size();
		}
	}
	else
	{
		m_iPage = i / MAXATONCE;
		if (models.size() < i + MAXATONCE)
		{
			count = models.size() - i;
		}
		else
		{
			count = MAXATONCE;
		}
	}
	switch (count)
	{
	case 0:
		return;
	case 1:
		m_wwPosWin = new WelcomeWindow(this, count, models[i], model, model, model);
		CloseCurrentWindow();
		break;
	case 2:
		m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], model, model);
		CloseCurrentWindow();
		break;
	case 3:
		m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], models[i+2], model);
		CloseCurrentWindow();
		break;
	case 4:
		m_wwPosWin = new WelcomeWindow(this, count, models[i], models[i+1], models[i+2], models[i+3]);
		CloseCurrentWindow();
		break;
	}
	this->setCentralWidget(m_wwPosWin);
	m_wtCurrentWin = WELCOME;
	modelList.clear();

	connect(m_wwPosWin, SIGNAL(display(const ModelVideo&)), this, SLOT(toDisplay(const ModelVideo&)));
	connect(m_wwPosWin, SIGNAL(toProfileMode(const QString&)), this, SLOT(toProfileMode(const QString&)));
	connect(m_wwPosWin, SIGNAL(prev()), this, SLOT(prevWelcome()));
	connect(m_wwPosWin, SIGNAL(next()), this, SLOT(nextWelcome()));
	connect(m_wwPosWin, SIGNAL(toUpload()), this, SLOT(toUploadMode()));
	connect(m_wwPosWin, SIGNAL(toHome()), this, SLOT(toHomeWin()));
	connect(m_wwPosWin, SIGNAL(logout()), this, SLOT(logout()));
	connect(m_wwPosWin, SIGNAL(refresh()), this, SLOT(firstToHome()));
	
	this->setFixedSize(WINDOW_W*xscale, WINDOW_H*yscale);
	this->move((QApplication::desktop()->width() - WINDOW_W*xscale) / 2,
			   (QApplication::desktop()->height() - WINDOW_H*yscale) / 2);
}
开发者ID:aaronguo1996,项目名称:posture,代码行数:72,代码来源:posture.cpp

示例9: QHBoxLayout

void PlayerControls::setupButtons(QMenu *appMenu)
{
    QHBoxLayout *layout = new QHBoxLayout();

    QHBoxLayout *leftLayout = new QHBoxLayout();
    leftLayout->setAlignment(Qt::AlignLeft);

    QHBoxLayout *centerLayout = new QHBoxLayout();
    centerLayout->setAlignment(Qt::AlignCenter);

    QHBoxLayout *rightLayout = new QHBoxLayout();
    rightLayout->setAlignment(Qt::AlignRight);

    // Menu button
    m_wbAppMenu = new StyledButton(QIcon(QPixmap(":icons/menu")), tr("Menu"));
    m_wbAppMenu->setFixedHeight(28);
    m_wbAppMenu->setIconSize(QSize(16, 16));
    m_wbAppMenu->setMenu(appMenu);

    // Prev
    m_wbPrev = new StyledButton(QIcon(QPixmap(":icons/prev")), "Prev");
    m_wbPrev->setFixedHeight(28);
    m_wbPrev->setIconSize(QSize(16, 16));
    connect(m_wbPrev, SIGNAL(clicked()), SIGNAL(prev()));

    // Play
    m_wbPlay = new StyledButton(QIcon(QPixmap(":icons/play")), "Play");
    m_wbPlay->setFixedHeight(28);
    m_wbPlay->setIconSize(QSize(16, 16));
    m_wbPlay->setCheckable(true);
    connect(m_wbPlay, SIGNAL(clicked()), SIGNAL(play()));

    // Next
    m_wbNext = new StyledButton(QIcon(QPixmap(":icons/next")), "Next");
    m_wbNext->setFixedHeight(28);
    m_wbNext->setIconSize(QSize(16, 16));
    m_wbNext->setLayoutDirection(Qt::RightToLeft);
    connect(m_wbNext, SIGNAL(clicked()), SIGNAL(next()));

    // Shuffle
    m_wbShuffle = new StyledButton(QIcon(QPixmap(":icons/circle_empty")), "Shuffle");
    m_wbShuffle->setCheckable(true);
    m_wbShuffle->setFixedHeight(28);
    m_wbShuffle->setIconSize(QSize(16, 16));
    setShuffle(Settings::instance()->getValue("player/shuffle").toInt());
    connect(m_wbShuffle, SIGNAL(clicked()), SLOT(setShuffle()));

    // Repeat
    m_wbRepeat = new StyledButton(QIcon(QPixmap(":icons/circle_empty")), "Repeat");
    m_wbRepeat->setCheckable(true);
    m_wbRepeat->setFixedHeight(28);
    m_wbRepeat->setIconSize(QSize(16, 16));
    setRepeat(Settings::instance()->getValue("player/repeat").toInt());
    connect(m_wbRepeat, SIGNAL(clicked()), SLOT(setRepeat()));

    // Status
    m_wbStatus = new StyledButton(QIcon(QPixmap(":icons/vk")), "");
    m_wbStatus->setCheckable(true);
    m_wbStatus->setFixedSize(28,28);
    m_wbStatus->setIconSize(QSize(20, 20));
    m_wbStatus->setTransparent(true);
    connect(m_wbStatus, SIGNAL(clicked(bool)), SLOT(setStatusState(bool)));
    setStatusState(Settings::instance()->getValue("player/status").toBool());

    m_wbLastfm = new StyledButton(QIcon(QPixmap(":icons/lf")), "");
    m_wbLastfm->setCheckable(true);
    m_wbLastfm->setFixedSize(28,28);
    m_wbLastfm->setIconSize(QSize(20, 20));
    m_wbLastfm->setTransparent(true);
    connect(m_wbLastfm, SIGNAL(clicked(bool)), SLOT(setLastfmState(bool)));
    setLastfmState(Settings::instance()->getValue("lastfm/scrobbling").toBool());

    layout->addLayout(leftLayout);
    layout->addLayout(centerLayout);
    layout->addLayout(rightLayout);

    leftLayout->addWidget(m_wbAppMenu);

    centerLayout->addWidget(m_wbShuffle);
    centerLayout->addSpacing(20);
    centerLayout->addWidget(m_wbPrev);
    centerLayout->addWidget(m_wbPlay);
    centerLayout->addWidget(m_wbNext);
    centerLayout->addSpacing(20);
    centerLayout->addWidget(m_wbRepeat);

    rightLayout->addWidget(m_wbStatus);
    rightLayout->addWidget(m_wbLastfm);

    m_mainLayout->addLayout(layout, 2, 1);
    m_mainLayout->setAlignment(layout, Qt::AlignTop);

    bool isAcc = Settings::instance()->getValue("general/account_use").toBool();

    if(!isAcc) {
        m_wbStatus->setDisabled(true);
    }
}
开发者ID:maxvanceffer,项目名称:pulsar,代码行数:98,代码来源:playercontrols.cpp

示例10: prev

	void operator--(int) { prev(); }
开发者ID:nyankosoft,项目名称:amorphous,代码行数:1,代码来源:indexed_vector.hpp

示例11: handle_event_prev

static int handle_event_prev()
{
    return (prev());
}
开发者ID:eerimoq,项目名称:simba,代码行数:4,代码来源:main.c

示例12: triangulate

static int triangulate(int n, const int* verts, int* indices, int* tris)
{
	int ntris = 0;
	int* dst = tris;
	
	// The last bit of the index is used to indicate if the vertex can be removed.
	for (int i = 0; i < n; i++)
	{
		int i1 = next(i, n);
		int i2 = next(i1, n);
		if (diagonal(i, i2, n, verts, indices))
			indices[i1] |= 0x80000000;
	}
	
	while (n > 3)
	{
		int minLen = -1;
		int mini = -1;
		for (int i = 0; i < n; i++)
		{
			int i1 = next(i, n);
			if (indices[i1] & 0x80000000)
			{
				const int* p0 = &verts[(indices[i] & 0x0fffffff) * 4];
				const int* p2 = &verts[(indices[next(i1, n)] & 0x0fffffff) * 4];
				
				int dx = p2[0] - p0[0];
				int dy = p2[2] - p0[2];
				int len = dx*dx + dy*dy;
				
				if (minLen < 0 || len < minLen)
				{
					minLen = len;
					mini = i;
				}
			}
		}
		
		if (mini == -1)
		{
			// Should not happen.
/*			printf("mini == -1 ntris=%d n=%d\n", ntris, n);
			for (int i = 0; i < n; i++)
			{
				printf("%d ", indices[i] & 0x0fffffff);
			}
			printf("\n");*/
			return -ntris;
		}
		
		int i = mini;
		int i1 = next(i, n);
		int i2 = next(i1, n);
		
		*dst++ = indices[i] & 0x0fffffff;
		*dst++ = indices[i1] & 0x0fffffff;
		*dst++ = indices[i2] & 0x0fffffff;
		ntris++;
		
		// Removes P[i1] by copying P[i+1]...P[n-1] left one index.
		n--;
		for (int k = i1; k < n; k++)
			indices[k] = indices[k+1];
		
		if (i1 >= n) i1 = 0;
		i = prev(i1,n);
		// Update diagonal flags.
		if (diagonal(prev(i, n), i1, n, verts, indices))
			indices[i] |= 0x80000000;
		else
			indices[i] &= 0x0fffffff;
		
		if (diagonal(i, next(i1, n), n, verts, indices))
			indices[i1] |= 0x80000000;
		else
			indices[i1] &= 0x0fffffff;
	}
	
	// Append the remaining triangle.
	*dst++ = indices[0] & 0x0fffffff;
	*dst++ = indices[1] & 0x0fffffff;
	*dst++ = indices[2] & 0x0fffffff;
	ntris++;
	
	return ntris;
}
开发者ID:Refuge89,项目名称:Hearthstone,代码行数:86,代码来源:RecastMesh.cpp

示例13: while

    void CalendarEventCoordinator::UpdateNodes( float dt )
    {
        // Now issue events as they come up, including anything currently in the past or present
        while( parent->GetSimulationTime().time >= times_and_coverages.begin()->first)
        {
            int grandTotal = 0;
            int limitPerNode = -1;

            // intervention class names for informative logging
            std::ostringstream intervention_name;
            intervention_name << std::string( json::QuickInterpreter(intervention_config._json)["class"].As<json::String>() );

            auto qi_as_config = Configuration::CopyFromElement( (intervention_config._json), "campaign" );
            _di = InterventionFactory::getInstance()->CreateIntervention(qi_as_config);
            // including deeper information for "distributing" interventions (e.g. calendars)
            formatInterventionClassNames( intervention_name, &json::QuickInterpreter(intervention_config._json) );

            // Only visit individuals if this is NOT an NTI. Check...
            // Check to see if intervention is an INodeDistributable...
            INodeDistributableIntervention *ndi = InterventionFactory::getInstance()->CreateNDIIntervention(qi_as_config);
            INodeDistributableIntervention *ndi2 = nullptr;

            LOG_DEBUG_F("[UpdateNodes] limitPerNode = %d\n", limitPerNode);
            for (auto nec : cached_nodes)
            {
                if (ndi)
                {
                    throw NotYetImplementedException( __FILE__, __LINE__, __FUNCTION__ );
#if 0
                    ndi2 = InterventionFactory::getInstance()->CreateNDIIntervention( qi_as_config );
                    if(ndi2)
                    {
                        float duration = -1;
                        if (times_and_coverages.size() > 1)
                        {
                            auto iter = times_and_coverages.end(); 
                            //A node-targeted intervention issued through the calender coordinator lasts until the next NDI.  
                            //Is there an overlap of one day here?  Should there be a -1?
                            duration = (float)(prev(iter,2)->first - prev(iter, 1)->first);   
                        }
                        
                        INodeDistributableInterventionParameterSetterInterface* pNDIPSI = nullptr;
                        if (s_OK == ndi2->QueryInterface(GET_IID(INodeDistributableInterventionParameterSetterInterface), (void**)&pNDIPSI) )
                        {
                            pNDIPSI->SetDemographicCoverage(times_and_coverages.begin()->second);
                            pNDIPSI->SetMaxDuration(duration);
                        }
                                                
                        if (!ndi2->Distribute( nec, this ) )
                        {
                            LOG_INFO_F("UpdateNodes() distributed '%s' intervention to node %d\n", intervention_name.str().c_str(), nec->GetId().data );
                        }
                        ndi2->Release();
                    }
#endif
                }
                else
                {
                    try
                    {
                        // For now, distribute evenly across nodes. 
                        int totalIndivGivenIntervention = nec->VisitIndividuals( this, limitPerNode );
                        grandTotal += totalIndivGivenIntervention;
                        LOG_INFO_F( "UpdateNodes() gave out %d interventions at node %d\n", totalIndivGivenIntervention, nec->GetId().data );
                    }                   
                    catch( const json::Exception &e )
                    {
                        throw GeneralConfigurationException( __FILE__, __LINE__, __FUNCTION__, e.what() );
                    }
                }
            }
            delete qi_as_config;
            qi_as_config = nullptr;

            times_and_coverages.erase(times_and_coverages.begin());
            LOG_DEBUG_F("%d Distributions remaining from CalendarEventCoordinator\n", times_and_coverages.size());
            if( times_and_coverages.empty() )
            {
                LOG_DEBUG_F("Signaling for disposal of CalendarEventCoordinator\n");
                distribution_complete = true; // we're done, signal disposal ok
                break;
            }
        }
        return;
    }
开发者ID:clorton,项目名称:EMOD,代码行数:85,代码来源:CalendarEventCoordinator.cpp

示例14: rcBuildRegionsMonotone

/// @par
/// 
/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
/// Contours will form simple polygons.
/// 
/// If multiple regions form an area that is smaller than @p minRegionArea, then all spans will be
/// re-assigned to the zero (null) region.
/// 
/// Partitioning can result in smaller than necessary regions. @p mergeRegionArea helps 
/// reduce unecessarily small regions.
/// 
/// See the #rcConfig documentation for more information on the configuration parameters.
/// 
/// The region data will be available via the rcCompactHeightfield::maxRegions
/// and rcCompactSpan::reg fields.
/// 
/// @warning The distance field must be created using #rcBuildDistanceField before attempting to build regions.
/// 
/// @see rcCompactHeightfield, rcCompactSpan, rcBuildDistanceField, rcBuildRegionsMonotone, rcConfig
bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
							const int borderSize, const int minRegionArea, const int mergeRegionArea)
{
	rcAssert(ctx);
	
	ctx->startTimer(RC_TIMER_BUILD_REGIONS);
	
	const int w = chf.width;
	const int h = chf.height;
	unsigned short id = 1;
	
	rcScopedDelete<unsigned short> srcReg = (unsigned short*)rcAlloc(sizeof(unsigned short)*chf.spanCount, RC_ALLOC_TEMP);
	if (!srcReg)
	{
		ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'src' (%d).", chf.spanCount);
		return false;
	}
	memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);

	const int nsweeps = rcMax(chf.width,chf.height);
	rcScopedDelete<rcSweepSpan> sweeps = (rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP);
	if (!sweeps)
	{
		ctx->log(RC_LOG_ERROR, "rcBuildRegionsMonotone: Out of memory 'sweeps' (%d).", nsweeps);
		return false;
	}
	
	
	// Mark border regions.
	if (borderSize > 0)
	{
		// Make sure border will not overflow.
		const int bw = rcMin(w, borderSize);
		const int bh = rcMin(h, borderSize);
		// Paint regions
		paintRectRegion(0, bw, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
		paintRectRegion(w-bw, w, 0, h, id|RC_BORDER_REG, chf, srcReg); id++;
		paintRectRegion(0, w, 0, bh, id|RC_BORDER_REG, chf, srcReg); id++;
		paintRectRegion(0, w, h-bh, h, id|RC_BORDER_REG, chf, srcReg); id++;
		
		chf.borderSize = borderSize;
	}
	
	rcIntArray prev(256);

	// Sweep one line at a time.
	for (int y = borderSize; y < h-borderSize; ++y)
	{
		// Collect spans from this row.
		prev.resize(id+1);
		memset(&prev[0],0,sizeof(int)*id);
		unsigned short rid = 1;
		
		for (int x = borderSize; x < w-borderSize; ++x)
		{
			const rcCompactCell& c = chf.cells[x+y*w];
			
			for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
			{
				const rcCompactSpan& s = chf.spans[i];
				if (chf.areas[i] == RC_NULL_AREA) continue;
				
				// -x
				unsigned short previd = 0;
				if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
				{
					const int ax = x + rcGetDirOffsetX(0);
					const int ay = y + rcGetDirOffsetY(0);
					const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
					if ((srcReg[ai] & RC_BORDER_REG) == 0 && chf.areas[i] == chf.areas[ai])
						previd = srcReg[ai];
				}
				
				if (!previd)
				{
					previd = rid++;
					sweeps[previd].rid = previd;
					sweeps[previd].ns = 0;
					sweeps[previd].nei = 0;
				}

//.........这里部分代码省略.........
开发者ID:arrian,项目名称:3d-engine,代码行数:101,代码来源:RecastRegion.cpp

示例15: fourSum

vector<vector<int>> fourSum(vector<int>& nums, int target) {
        // method 1
        // 先排序然后左右夹逼
        // time complexity O(n^3) space complexity O(1)
        vector<vector<int>> result;
        if (nums.size() < 4) 
        return result;
        sort(nums.begin(), nums.end());
        auto last = nums.end();
        for (auto a = nums.begin(); a < prev(last, 3); ++a) { // prev之前3个位置
            for (auto b = next(a); b < prev(last, 2); ++b) {  // next(b)b的下一个位置
                auto c = next(b);
                auto d = prev(last);                          // last前一个位置
                while (c < d) {
                    if (*a + *b + *c + *d < target) {
                        ++c;
                    } 
                    else if (*a + *b + *c + *d > target) 
                        --d;
                        else{
                        result.push_back({ *a, *b, *c, *d });
                        ++c;
                        --d;
                        }
                    }
                }
        }
        sort(result.begin(), result.end());   // vector排序?
        result.erase(unique(result.begin(), result.end()), result.end());  // unique()从输入序列中“删除”所有相邻的重复元素
        return result; // 把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址
        
  
  
  // method 2
  // average O(n^2)􅖌worst O(n^4) space O(n^2)
  vector<vector<int>> result;
  if (nums.size() < 4) return result;
  sort(nums.begin(), nums.end());
  unordered_multimap<int, pair<int, int>> cache;
  for (int i = 0; i + 1 < nums.size(); ++i)
	  for (int j = i + 1; j < nums.size(); ++j)
		  cache.insert(make_pair(nums[i] + nums[j], make_pair(i, j)));
  for (auto i = cache.begin(); i != cache.end(); ++i) {
	  int x = target - i->first;
	  auto range = cache.equal_range(x);
	  for (auto j = range.first; j != range.second; ++j) {
		  auto a = i->second.first;
		  auto b = i->second.second;
		  auto c = j->second.first;
		  auto d = j->second.second;
		  if (a != c && a != d && b != c && b != d) {       // a b c d 是序号
			  vector<int> vec = { nums[a], nums[b], nums[c], nums[d] };
			  sort(vec.begin(), vec.end());
			  result.push_back(vec);
		  }
	  }
  }
  sort(result.begin(), result.end());
  result.erase(unique(result.begin(), result.end()), result.end());
  return result;
}
开发者ID:wszk1992,项目名称:LeetCode-Team,代码行数:61,代码来源:18.+4Sum.cpp


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