int main()
{
    MyMap *mymap = new MyMap();
    vector<int> *sum_vec;
    const Key *key;
    int len;
    int p[MaxLen];
    srand( unsigned(time(NULL)));
    for(int c = 0; c < MaxNum; ++c)
    {
        len = rand() % MaxLen + 1;
        int sum = 0;
        for(int i = 0; i < len; ++i)
        {
            p[i] = rand() % MaxNum;
            sum += p[i];
        }
        key = new Key(p, len);
        sum_vec = new vector<int>();
        sum_vec->push_back(sum);
        mymap->insert(make_pair(*key, sum_vec));
        delete key;
    }
    for(MyMap::iterator it = mymap->begin(); it != mymap->end(); ++it)
    {
        delete it->second;
    }
    delete mymap;
    return 0;
}
 static typename DerivedF::Scalar  add_vertex(const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 1> &values,
                                              const Eigen::Matrix<typename DerivedV::Scalar, Eigen::Dynamic, 3> &points,
                                              unsigned int i0,
                                              unsigned int i1,
                                              PointMatrixType &vertices,
                                              int &num_vertices,
                                              MyMap &edge2vertex)
 {
   // find vertex if it has been computed already
   MyMapIterator it = edge2vertex.find(EdgeKey(i0, i1));
   if (it != edge2vertex.end()) 
     return it->second;
   ;
   
   // generate new vertex
   const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> & p0 = points.row(i0);
   const Eigen::Matrix<typename DerivedV::Scalar, 1, 3> & p1 = points.row(i1);
   
   typename DerivedV::Scalar s0 = fabs(values[i0]);
   typename DerivedV::Scalar s1 = fabs(values[i1]);
   typename DerivedV::Scalar t  = s0 / (s0+s1);
   
   
   num_vertices++;
   if (num_vertices > vertices.rows())
     vertices.conservativeResize(vertices.rows()+10000, Eigen::NoChange);
   
   vertices.row(num_vertices-1)  = (1.0f-t)*p0 + t*p1;
   edge2vertex[EdgeKey(i0, i1)] = num_vertices-1;
   
   return num_vertices-1;
 }
Esempio n. 3
0
int main(int argc, char * argv[]) {
    if (argc == 0) {
        cout << "usage: " << argv[0] << "[File1 [File2 [File3 [...]]]]" << endl;
    }
    for (int i = 1; i < argc; i++) {
        cout << "File: " << argv[i] << endl;
        printNames(argv[i]);

        MyMap::iterator it = names.begin();
        while (it != names.end()) {
            //cout << it->first << ": " << it->second << endl;
            sortiert.push_back(it);
            it++;
        }
        //partial_sort (sortiert.begin(), sortiert.bein() + 20, sortiert.end(), mySort);
        partial_sort (sortiert.begin(), sortiert.begin() + 20, sortiert.end(), myObject);

        size_t c = 0;
        for (MyVec::iterator it = sortiert.begin(); it != sortiert.end() && c < 20; it++, c++) {
            cout << (*it)->first << ": " << (*it)->second << endl;
        }
        cout << "==============================" << endl;

        names.clear();
    }
}
Esempio n. 4
0
void VS10Inst::ValidateDestMask()
{
    char temp[256];
    typedef std::map<char, int> MyMap;
    typedef MyMap::value_type MyPair;
    static const MyPair pairs[] = 
    {
        MyPair('x',1),
        MyPair('y',2),
        MyPair('z',3),
        MyPair('w',4),
    };
    static const MyMap swizzleMap(pairs, pairs+(sizeof(pairs)/sizeof(pairs[0])));

    if ( dst.mask[0] == 0 ) return;
    int i = 1;
    while ( i < 4 && dst.mask[i] != 0 )
    {
        MyMap::const_iterator lastMaskIt = swizzleMap.find(dst.mask[i-1]);
        MyMap::const_iterator curMaskIt = swizzleMap.find(dst.mask[i]);
        if (lastMaskIt == swizzleMap.end() || curMaskIt == swizzleMap.end() ||
            lastMaskIt->second >= curMaskIt->second)
//        if ( dst.mask[i-1] >= dst.mask[i] )
        {
            char mask[5];
            strncpy( mask, dst.mask, 4 );
            mask[4] = 0;
            sprintf( temp, "(%d) Error: destination register has invalid mask: %s\n", line, mask );
            errors.set( temp );
            break;
        }
        i++;
    }
}
/* Function: getFrequencyTable
 * Usage: MyMap<ext_char, int> freq = getFrequencyTable(file);
 * --------------------------------------------------------
 * This function will also set the frequency of the EOF
 * character to be 1, which ensures that any future encoding
 * tree built from these frequencies will have an encoding for
 * the EOF character.
 */
MyMap<ext_char, int> getFrequencyTable(ibstream& infileStream) {
    MyMap<ext_char, int> resultFrequenciesMap;
    ext_char nextChar;

    while ((nextChar = infileStream.get()) != EOF) {
        modifyMap(resultFrequenciesMap, nextChar);
    }

    resultFrequenciesMap.add(EOF, 1);
    return resultFrequenciesMap;
}
/* Function: modifyMap
 * -------------------
 * Modifies param frequenciesMap entries
 * for current char key.
 */
void modifyMap(MyMap<ext_char, int>& frequenciesMap,
               ext_char nextSymbol) {
    if (frequenciesMap.containsKey(nextSymbol)) {
        /* Modifies map entry - increments symbol value */
        int symbValue = frequenciesMap[nextSymbol];
        frequenciesMap.put(nextSymbol, ++symbValue);
    }else{
        /* Adds new map entry for this symbol */
        int symbApearence = 1;
        frequenciesMap.put(nextSymbol, symbApearence);
    }
}
Esempio n. 7
0
bool Test_STL()
{
    TTRACE(_T("====================================================="));
    typedef std::map<int, char> MyMap;
    MyMap map;
    map.insert(std::make_pair(1, 'A'));
    map.insert(std::make_pair(2, 'B'));
    std::for_each(map.begin(), map.end(), pair_second(Printer()));
    std::for_each(map.begin(), map.end(), pair_second(&Print));

    return true;
}
Esempio n. 8
0
bool IndexerImpl::save(string filenameBase)
{
    ofstream outfile(filenameBase+".txt");
    if ( ! outfile )		 
	{
	    cerr << "Error: Cannot create data.txt!" << endl;
	    return false;
	}
    //Map to store locations to grab from array
    MyMap<int, int>* h2pull = new MyMap<int, int>;
    //Save size of urlToCount to outfile
    outfile << urlToCount->size() << endl;
    string word;
    vector<point>* value = urlToCount->getFirst(word);
    while (value!=NULL)
    {
        //save word and size of vector
        outfile << word << " " << value->size() << endl;
        vector<point>::iterator it = value->begin();
        while (it!=value->end())
        {
            int hash = it->m_hash;
            outfile << hash << " " << it->m_count << endl;
            h2pull->associate(hash%MAX_MAP_SIZE, hash%MAX_MAP_SIZE);
            it++;
        }
        value = urlToCount->getNext(word);
    }
    //Save size of h2pull (number of elements in array to visit)
    outfile << h2pull->size() << endl;
    int temp;
    int* location = h2pull->getFirst(temp);
    while (location!=NULL)
    {
        int size = idToUrl[temp]->size();
        outfile << temp << " " << size <<endl;
        int hash;
        string* url = idToUrl[temp]->getFirst(hash);
        while(url!=NULL)
        {
            outfile << hash << " "<< *url << endl;
            url = idToUrl[temp]->getNext(hash);
        }
        location = h2pull->getNext(temp);
    }
    
    delete h2pull;
    return true;
}
Esempio n. 9
0
bool saveMyMap(string filename, MyMap<KeyType, ValueType>& m)
{
    // save contents of m to a file
    ofstream stream("filename");    // Create an ofstream object to create the file
    if (! stream) return false;     // Return false if we can't create the file
    writeItem(stream, m.size());    // Save the number of associations in m to stream
    KeyType x;
    ValueType* y = m.getFirst(x);
    for (int i = 0; i < m.size(); i++) {
        writeItem(stream, x);
        writeItem(stream, *y);
        y = m.getNext(x);
    }
    return true;
}
Esempio n. 10
0
int main ()
{
  MyMap amap;
  amap.insert("one", 1);
  amap.insert("two", 2);
  amap.insert("three", 3);
  //amap["three"].push_back(3);
  //amap["three"].push_back(3);
  //cout << amap["one"];
  amap.find("one");
  amap.find("two");
  amap.find("three");

  return 0;
}
Esempio n. 11
0
void tst_QMap::clear()
{
    {
	MyMap map;
	map.clear();
	QVERIFY( map.isEmpty() );
	map.insert( "key", MyClass( "value" ) );
	map.clear();
	QVERIFY( map.isEmpty() );
	map.insert( "key0", MyClass( "value0" ) );
	map.insert( "key0", MyClass( "value1" ) );
	map.insert( "key1", MyClass( "value2" ) );
	map.clear();
	QVERIFY( map.isEmpty() );
    }
    QCOMPARE( MyClass::count, int(0) );
}
Esempio n. 12
0
bool IndexerImpl::incorporate(string url, WordBag& wb)
{
    // adding to urlToId map, adding to idToUrl map
    int* temp = urlToId.find(url);
    if (temp != nullptr) return false;
    
    string word;
    int retrieveCount;
    bool getCount = wb.getFirstWord(word, retrieveCount);
    if (getCount == false) return false;
    
    int ID = rand() %100000;
    while (idToUrl.find(ID) != nullptr) { ID = rand() %100000; }
    urlToId.associate(url, ID); // add to urlToId map
    idToUrl.associate(ID, url); // add to idToUrl map
    
    while (getCount) {
        if (wordToIdCounts.find(word) != nullptr) {
            vector<Pair> *x = wordToIdCounts.find(word);
            x->push_back(Pair(ID, retrieveCount));
        }
        else {
            vector<Pair> y;
            y.push_back(Pair(ID, retrieveCount));
            wordToIdCounts.associate(word, y);
        }
        getCount = wb.getNextWord(word, retrieveCount);
    }
    return true;
//    The user calls the incorporate() method to add all the words in the provided WordBag argument to the index. If incorporate() has previously been called with the same url argument, it returns false, doing nothing. Otherwise, it updates the index by adding all the words and returns true. Incorporating a WordBag containing W distinct words to an index that already contains N words must take far less than O(WN) time, because adding one word mapping (e.g., "fun" → { "www.b.com", 1 }) to an index that already contains N words must take far less than O(N) time.
}
Esempio n. 13
0
vector<UrlCount> IndexerImpl::getUrlCounts(string word)
{
    vector<UrlCount> x;
    strToLower(word);
    if (wordToIdCounts.find(word) == nullptr) return x;
    vector<Pair> y = *wordToIdCounts.find(word);
    for (int i=0; i<y.size(); i++) {
        string Url = *(idToUrl.find(y[i].m_ID));
        int tempCount = y[i].m_count;
        UrlCount temp;
        temp.url = Url;
        temp.count = tempCount;
        x.push_back(temp);
    }
    return x;
    
//    The getUrlCounts() method returns a vector of UrlCounts for the specified word. The getUrlCounts() method must be case-insensitive, so it must return the same result for, e.g., "zits", "ZITS", or "ZitS" as the word argument. There is no requirement that the UrlCounts in the vector returned by this method be in any particular order. Each UrlCount in the vector holds a URL string and the count associated with that word in the WordBag incorporated with that URL (representing the number of times that word appeared on the web page at that URL). A given URL string must occur only once within the vector of matches. If your index contains N words, your getUrlCounts() method must return a vector of UrlCounts in far less than O(N) time.
}
Esempio n. 14
0
bool loadMyMap(string filename, MyMap<KeyType, ValueType>& m)
{
    m.clear();
    ifstream stream("filename");
    if (!stream) return false;
    int size = m.size();
    if (!readItem(stream, size)) return false; // Read the number of associations in m from stream, returning false if we can't
    KeyType x;
    ValueType y;
    for (int i = 0; i < size; i++) {
        if (!readItem(stream, x)) return false;
        stream.ignore(10000, '\n');
        if (!readItem(stream, y)) return false;
        stream.ignore(10000, '\n');
        m.associate(x, y);
    }
    return true;
}
Esempio n. 15
0
void tst_ExceptionSafety::exceptionMap() {

    {
        MyMap map;
        MyMap map2;
        MyMap map3;

        throwType = ThrowNot;
        for (int i = 0; i<10; i++)
            map[ FlexibleThrowerSmall(i) ] = FlexibleThrowerSmall(i);

        return; // further test are deactivated until Map is fixed.

        for( int i = ThrowAtCopy; i<=ThrowAtComparison; i++ ) {
            try {
                throwType = (ThrowType)i;
                map[ FlexibleThrowerSmall(10) ] = FlexibleThrowerSmall(10);
            } catch(...) {
            }
            QCOMPARE( map.size(), 10 );
            QCOMPARE( map[ FlexibleThrowerSmall(1) ], FlexibleThrowerSmall(1) );
        }

        map2 = map;
        try {
            throwType = ThrowLater;
            map2[ FlexibleThrowerSmall(10) ] = FlexibleThrowerSmall(10);
        } catch(...) {
        }
        /* qDebug("%d %d", map.size(), map2.size() );
        for( int i=0; i<map.size(); i++ )
            qDebug( "Value at %d: %d",i, map.value(FlexibleThrowerSmall(i), FlexibleThrowerSmall()).value() );
        QCOMPARE( map.value(FlexibleThrowerSmall(1), FlexibleThrowerSmall()), FlexibleThrowerSmall(1) );
        qDebug( "Value at %d: %d",1, map[FlexibleThrowerSmall(1)].value() );
        qDebug("%d %d", map.size(), map2.size() );
        */
        QCOMPARE( map[ FlexibleThrowerSmall(1) ], FlexibleThrowerSmall(1) );
        QCOMPARE( map.size(), 10 );
        QCOMPARE( map2[ FlexibleThrowerSmall(1) ], FlexibleThrowerSmall(1) );
        QCOMPARE( map2.size(), 10 );

    }
    QCOMPARE(objCounter, 0 ); // check that every object has been freed
}
Esempio n. 16
0
void GameScene::changeMap(Point startPoint,int mapPoint){
	this->removeChildByName("map");
	this->removeChildByTag(sGlobal->mapNum);
	sGlobal->mapNum = mapPoint;
	MyMap* myMap = MyMap::create();
	sGlobal->map = myMap->m_map;
	sGlobal->myMap = myMap;
	myMap->setPosition(Point(100, 100));
	myMap->m_map->setPosition(Point(-100, -100));
	this->addChild(myMap, 5, sGlobal->mapNum);
	this->addChild(myMap->m_map,6,"map");
	/*myMap->setPosition(Point(0, 0));*/
	myMap->m_map->addChild(sGlobal->hero);
	/*sGlobal->map->addChild(sGlobal->hero);*/
	sGlobal->hero->setTiledMap(sGlobal->map);
	sGlobal->hero->setPosition(sGlobal->myMap->positionForTileCoord(startPoint));
	/*this->addHero(sGlobal->map, sGlobal->myMap->positionForTileCoord(startPoint-Point(2,2)));*/
	CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("WhenInSchool.mp3", true);
}
Esempio n. 17
0
bool IndexerImpl::incorporate(string url, WordBag& wb)
{

    int hash;
    //Generates a hash of url as well as index for linear probing
    int modhash = hashurl(url,hash);
    //If the head bucket of the array is not initialized, initialize it
    if (idToUrl[modhash]==NULL)
        idToUrl[modhash]=new MyMap<int,string>;
    //Checks to see if this url has already been passed to incorporate
    if (idToUrl[modhash]->find(hash)!=NULL)
        return false;
    //Adds url to hash-url map
    if (idToUrl[modhash]->size()==0)
        indexes.push_back(modhash);
    idToUrl[modhash]->associate(hash,url);
    
    
    string word;
    int count;
    //Iterates through W distinct words in wordbag. O(W)
    bool gotAWord = wb.getFirstWord(word, count);
    while (gotAWord)
    {
        //Accounts for case-insensitive indexing.
        strToLower(word);
        point bucket = point(hash,count);
        //Find if word already exists. O(log N).
        vector<point>* temp = urlToCount->find(word);
        if (temp==NULL)
        {
            //The word does not yet exist in the index
            //Create a temp vector
            temp = new vector<point>;
        }
        temp->push_back(bucket);
        //Map word to temp Map of urlhash to wordcount
        urlToCount->associate(word, *temp);
        gotAWord = wb.getNextWord(word,count);
    }
    //Final BigO is O(WlogN) which is less than O(WN)
    return true;
}
Esempio n. 18
0
bool IndexerImpl::load(string filenameBase)
{
    //Deletes existing map of url to count
    clear();
    urlToCount = new MyMap<string, vector<point> >;
    ifstream infile(filenameBase+".txt");
    if ( ! infile )
	{
	    cerr << "Error: Cannot open data.txt!" << endl;
	    return false;
	}
    int urlToCountsize;
    infile >> urlToCountsize;
    infile.ignore(10000, '\n');
    string tempword;
    int vectorsize;
    for (int i=0;i<urlToCountsize;i++)
    {
        infile >> tempword;
        infile >> vectorsize;
        infile.ignore(10000, '\n');
        vector<point> tempvec;
        for (int j=0;j<vectorsize;j++)
        {
            int hash, count;
            infile >> hash;
            infile >> count;
            infile.ignore(10000, '\n');
            tempvec.push_back(point(hash,count));
        }
        urlToCount->associate(tempword, tempvec);
    }
    int idToUrlsize;
    infile >> idToUrlsize;
    infile.ignore(10000, '\n');
    for (int j=0;j<idToUrlsize;j++)
    {
        int index, count;
        infile >> index;
        infile >> count;
        infile.ignore(10000, '\n');
        for (int i=0;i<count;i++)
        {
            int key;
            string url;
            infile >> key;
            infile >> url;
            infile.ignore(10000, '\n');
            if (idToUrl[index]==NULL)
                idToUrl[index]=new MyMap<int, string>;
            idToUrl[index]->associate(key, url);
        }
    }
    return true;
}
int main()
{
	//начальная инициализация map
	MyMap m;
	//использование value_type для формирование пары "ключ - значение"
	m.insert(MyMap::value_type(1,"Ivanov"));
	//можно непосредственно использовать тип pair
	m.insert(pair<int,string>(2,"Petrov"));
	//использование функции make_pair
	m.insert(make_pair(3,"Sidorov"));


	for(auto x: m)
	{
		//использование свойств итератора:
		//first для обращения к ключу,
		//second для обращение к значению
		cout << x.first << " " << x.second << endl;
	}
	
	return 0;
}
bool WordBagImpl::getNextWord(string& word, int& count)
{
	int *getNextVal = m_map.getNext(word);

	if (getNextVal == nullptr)
		return false;

	else
	{
		count = *getNextVal;
		return true;
	}
}
Esempio n. 21
0
bool WordBagImpl::getNextWord(string& word, int& count)
{
    string key;
    int* c = m_token->getNext(key);
    if (c == NULL)
        return false;
    else
    {
        word = key;
        count = *c;
        return true;
    }
}
Esempio n. 22
0
int main()
{
    MyMap<string, int> months;

    months["january"] = 31;
    months["february"] = 28;
    months["march"] = 31;
    months["april"] = 30;
    months["may"] = 31;
    months["june"] = 30;
    months["july"] = 31;
    months["august"] = 31;
    months["september"] = 30;
    months["october"] = 31;
    months["november"] = 30;
    months["december"] = 31;

    cout << "Map size: " << months.size() << endl;
    if (months.empty())
        cout << "Map is empty!" << endl;
    else
        cout << "Map is not empty!" << endl;

    cout << "june -> " << months["june"] << endl;
    cout << "blabla -> " << months["blabla"] << endl;
    cout << endl;

    display(months);

    MyMap<string, int>::iterator it;
    it = months.find("blabla");
    months.erase(it);

    display(months);

    return 0;
}
/* Function: buildCypherTable
 * ---------------------------
 * Modifies param cypher table map
 * by entries [symbol][symbol Huffman code]
 * for this huffman tree.
 * Makes DFS from root to every symbol-leaf to
 * cocantenate currentCypher code value.
 *
 *
 * @param currentCypher        symbol
 * @param node                 root of Huffman tree
 * @param cypherTable          cypher table map to fill by entries
 */
void buildCodesTableForTree(string currentSymbolCode,
                             Node* node,
                             MyMap<ext_char, string>& charsCodesTable) {
    /* This node is fork end */
    if ((node->leftChild == NULL) && (node->rightChild == NULL)) {
        charsCodesTable.add(node->symbol, currentSymbolCode);
    }else{
        /* This node has childs */
        if (node->leftChild != NULL) {
            string leftCypher = currentSymbolCode + "0";
            buildCodesTableForTree(leftCypher, node->leftChild, charsCodesTable);
        }
        if (node->rightChild != NULL) {
            string rightCypher = currentSymbolCode + "1";
            buildCodesTableForTree(rightCypher, node->rightChild, charsCodesTable);
        }
    }
}
Esempio n. 24
0
vector<UrlCount> IndexerImpl::getUrlCounts(string word)
{
    strToLower(word);
    vector<UrlCount> output;
    //First locates the word in urlToCount Map. O(log N) steps
    vector<point>* temp = urlToCount->find(word);
    //If word is not found in index, return empty vector
    if (temp==NULL)
        return output;
    vector<point>::iterator it = temp->begin();
    //Iterates through the vector mapped to the word. O(log N) + V steps where V is the size of the vector
    while (it!=temp->end())
    {
        UrlCount copy;
        copy.count=it->m_count;
        int id = it->m_hash;
        string url = *(idToUrl[id%MAX_MAP_SIZE]->find(id));
        copy.url=url;
        output.push_back(copy);
        it++;
    }
    //Final BigO is O(logN + V) which is less than O(N + V)
    return output;  
}
Esempio n. 25
0
void MyMenu::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) {
    
    //先检测路径在~调用回调
    
    if (m_pSelectedItem) {
        //TODO
//        if (m_pSelectedItem->getTag() == myTiledMenuItemTag)
        {
            
            //点击主建筑时
            
            MyMap* myMap = (MyMap*)map;
            if (!isActive && isMoved) {
                
                //未激活建筑 同时移动地图时,不激活建筑
                
                CC_UNUSED_PARAM(pTouch);
                CC_UNUSED_PARAM(pEvent);
                CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
                m_pSelectedItem->unselected();
                m_eState = kCCMenuStateWaiting;
            } else if(!isActive && !isMoved) {
                
                //未激活建筑时点击建筑时(不移动地图),激活建筑,取消其他建筑
                
                ((MyMap*)map)->cancelAllBuilding();
                CCMenu::ccTouchEnded(pTouch, pEvent);
            } else if(isActive && isMoved) {
                
                //激活建筑并拖动建筑
                
                if (myMap->collisionDetection()) {
                    
                    //落点有碰撞,播错误提示并取消
                    
                    CC_UNUSED_PARAM(pTouch);
                    CC_UNUSED_PARAM(pEvent);
                    CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
                    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_error.wav");
                    m_pSelectedItem->unselected();
                    m_eState = kCCMenuStateWaiting;
                } else {
                    //落点无碰撞,放置建筑
                    cacheLoc = this->getPosition();
                    CCPoint loc = getPositionByTiled();
                    MyMenu::reorderZandTouchPriority(999999-this->getPosition().y, kCCMenuHandlerPriority-loc.x-loc.y);
                    ((MyMap*)map)->dispearTip();
                    CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_place.wav");
                    CCMenu::ccTouchEnded(pTouch, pEvent);
                }
            } else if(isActive && !isMoved) {
                
                //建筑激活并且没有移动
                if(!myMap->isBuild()) {
                    
                    //不在建筑模式下,取消选择
                    
                    if (!((MyMap*)map)->collisionDetection()) {
                        
                        //没有在碰撞区,成功取消,并设置Y的位置
                        
                        ((MyMap*)map)->cancelAllBuilding();
                        
                        CCPoint loc = getPositionByTiled();
                        MyMenu::reorderZandTouchPriority(999999-this->getPosition().y, kCCMenuHandlerPriority-loc.x-loc.y);
                        
                    } else {
                        
                        //在碰撞区,播错误声音,不取消
                        
                        CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_error.wav");
                        
                    }
                    CC_UNUSED_PARAM(pTouch);
                    CC_UNUSED_PARAM(pEvent);
                    CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
                    m_pSelectedItem->unselected();
                    m_eState = kCCMenuStateWaiting;
                } else {
                    //在建筑模式下,
                    if (!((MyMap*)map)->collisionDetection()) {
                        
                        //没有在碰撞区
                        
                        CCPoint loc = getPositionByTiled();
                        MyMenu::reorderZandTouchPriority(999999-this->getPosition().y, kCCMenuHandlerPriority-loc.x-loc.y);
                        CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_place.wav");
                        CCMenu::ccTouchEnded(pTouch, pEvent);
                    } else {
                        
                        //在碰撞区,播错误声音,不取消
                        
                        CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_error.wav");
                        CC_UNUSED_PARAM(pTouch);
                        CC_UNUSED_PARAM(pEvent);
                        CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
                        m_pSelectedItem->unselected();
                        m_eState = kCCMenuStateWaiting;
                        
                    }
                }
                
            }
            
        }
        //todo
//        else
        {
            // 点击按键或者其他
            CCMenu::ccTouchEnded(pTouch, pEvent);
        }
    } else {
        CCMenu::ccTouchEnded(pTouch, pEvent);
    }
    isMoved = false;
    moveEnabled = false;
    
//    ((MyMap*)map)->dispearTip();
    
//    if(m_pSelectedItem && m_pSelectedItem->getTag() != myTiledMenuItemTag && !isMoved) {
//        CCMenu::ccTouchEnded(pTouch, pEvent);
//        isMoved = false;
//        return;
//    }
//    if (!isActive && isMoved) {
//        CC_UNUSED_PARAM(pTouch);
//        CC_UNUSED_PARAM(pEvent);
//        CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
//        if (m_pSelectedItem)
//        {
//            m_pSelectedItem->unselected();
//        }
//        m_eState = kCCMenuStateWaiting;
//        moveEnabled = false;
//        isMoved = false;
//        return;
//    }
//    if(isActive && !isMoved && !((MyMap*)map)->isBuild()) {
//        if (!((MyMap*)map)->collisionDetection()) {
//            ((MyMap*)map)->cancelAllBuilding();
//            
//            CCPoint loc = getPositionByTiled();
//            MyMenu::reorderZandTouchPriority(999999-this->getPosition().y, kCCMenuHandlerPriority-loc.x-loc.y);
//            
//        } else {
//            CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_error.wav");
//            
//        }
//        CC_UNUSED_PARAM(pTouch);
//        CC_UNUSED_PARAM(pEvent);
//        CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
//        if (m_pSelectedItem)
//        {
//            m_pSelectedItem->unselected();
//        }
//        m_eState = kCCMenuStateWaiting;
//        moveEnabled = false;
//        isMoved = false;
//        return;
//    }
//    
//    if (!isActive && !isMoved) {
//        ((MyMap*)map)->cancelAllBuilding();
//        CCMenu::ccTouchEnded(pTouch, pEvent);
//        return;
//    }
//    
//    if(isActive && moveEnabled && !((MyMap*)map)->collisionDetection()) {
//        cacheLoc = this->getPosition();
//        CCPoint loc = getPositionByTiled();
//        MyMenu::reorderZandTouchPriority(999999-this->getPosition().y, kCCMenuHandlerPriority-loc.x-loc.y);
//        ((MyMap*)map)->dispearTip();
//        if(isMoved) {
//            CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_place.wav");
//        }
//        CCMenu::ccTouchEnded(pTouch, pEvent);
//    } else {
//        CC_UNUSED_PARAM(pTouch);
//        CC_UNUSED_PARAM(pEvent);
//        CCAssert(m_eState == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
//        CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("sfx_error.wav");
//        if (m_pSelectedItem)
//        {
//            m_pSelectedItem->unselected();
//        }
//        m_eState = kCCMenuStateWaiting;
//    }
//    ((MyMap*)map)->moveArrowTip(getPositionByTiled(), contentSizeByTiled.width);
//    moveEnabled = false;
//    isMoved = false;
//    CCLog("%f",999999-this->getPosition().y);
    
    
}
Esempio n. 26
0
int main()
{
  //using namespace std;
  int number1 = 100;
  int number2 = 20000;
  string str1 = IntToString(number1);
  string str2 = IntToString(number2);
  string comma(", ");
  str1 += comma;
  str1 += str2;
  cout << str1 << endl;
  MyMap amap;
  amap.insert(str1,1);
  amap.find(str1);
  const char* strL;
  strL = str1.c_str();
  regex_t preg;
  size_t nmatch = 3;
  regmatch_t pmatch[nmatch];
  int i, j;
  string restring1;
  string restring2;
  if (regcomp(&preg, "([[:digit:]]+), ([[:digit:]]+)", REG_EXTENDED|REG_NEWLINE) != 0) {
    printf("regex compile failed.\n");
    exit(1);
  }
  printf("String = %s\n", strL);
  if (regexec(&preg, strL, nmatch, pmatch, 0) != 0) {
    printf("No match.\n");
  } else {
    for (i = 0; i < nmatch; i++) { /* nmatch にマッチした件数が入る */
      printf("Match position = %d, %d , str = ", (int)pmatch[i].rm_so, (int)pmatch[i].rm_eo);
      if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0) {
	for (j = pmatch[i].rm_so ; j < pmatch[i].rm_eo; j++) {
	  //putchar(strL[j]);
          if(i==1){
          restring1+=strL[j];
	  }
          if(i==2){
	   restring2+=strL[j];
	  }
	}
      }
      printf("\n");
    }
  }

  regfree(&preg);
  cout << restring1 <<endl;
  cout << restring2 <<endl;
  assert(typeid(restring1) == typeid(string));
  assert(typeid(restring2) == typeid(string));
  int renumber1,renumber2;
  istringstream istr1(restring1);
  istr1 >> renumber1;
  cout << renumber1 <<endl;
  assert(typeid(renumber2) == typeid(int));
  istringstream istr2(restring2);
  istr2 >> renumber2;
  cout << renumber2 <<endl;
  assert(typeid(renumber2) == typeid(int));
  return 0;
}
Esempio n. 27
0
/*
 *  Method that determines the colors of silhouettes and background
 *
 *  @param  imageMatrix 2d array that contains color's
 *  @param  width The width of the image
 *  @param  height The height of the image
 *  @param  backgroundColor Variable that indicate background color
 */
void SilCounter::identifyColors(int** imageMatrix, int width, int height,int& backgroundColor){
    // map with key color and value amount of pixels with this color
    MyMap<int,int> colorFreq;

    // walk through 2d array and fill the map
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            colorFreq[imageMatrix[i][j]]++;
        }
    }

    // variables that will contain two most frequent colors
    int mostFreqFirst[2] = {0, 0};
    int mostFreqSecond[2] = {0, 0};

    // searching for two most frequent colors
    for(MyMap<int,int>::iterator it = colorFreq.begin(); it != colorFreq.end(); it++){
        if(it.node->value > mostFreqFirst[1]){
            mostFreqFirst[0] = it.node->key;
            mostFreqFirst[1] = it.node->value;
        }
    }
    for(MyMap<int,int>::iterator it = colorFreq.begin(); it != colorFreq.end(); it++){
        if((it.node->key > mostFreqSecond[1]) && (it.node->key != mostFreqFirst[0] )){
            mostFreqSecond[0] = it.node->key;
            mostFreqSecond[1] = it.node->value;
        }
    }

    // find average between most frequent colors
    int averageValue = (mostFreqFirst[0] + mostFreqSecond[0]) / 2;

    // set all colors that is lower then average to qrequent color with lower index to 0 and vice versa
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            imageMatrix[i][j] < averageValue ? imageMatrix[i][j] = 0 : imageMatrix[i][j] = 1;
        }
    }

    // check the perimeter of the image to identify pixels with what value are more often
    // it will be a background color
    int zeroCounter = 0;
    int oneCounter = 0;

    // checking upper and lower bounds
    for(int i = 0; i < width; i++){
        imageMatrix[0][i] ? oneCounter++ : zeroCounter++;

        imageMatrix[height-1][i] ? oneCounter++ : zeroCounter++;
    }

    // checking sides
    for(int i = 0; i < height; i++){
        imageMatrix[i][0] ? oneCounter++ : zeroCounter++;

        imageMatrix[i][width-1] ? oneCounter++ : zeroCounter++;
    }
    // set background color
    if(oneCounter > zeroCounter ){
        backgroundColor = 1;
    }
}
Esempio n. 28
0
File: main.cpp Progetto: CCJY/coliru
int main(int argc, char **argv)
{
	MyMap<Foo> const m(Foo(1));
	m.do_something();	
}
int main ()
{
   using namespace boost::interprocess;

   //Remove shared memory on construction and destruction
   struct shm_remove
   {
   //<-
   #if 1
      shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
      ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
   #else
   //->
      shm_remove() { shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
   //<-
   #endif
   //->
   } remover;

   //Shared memory front-end that is able to construct objects
   //associated with a c-string. Erase previous shared memory with the name
   //to be used and create the memory segment at the specified address and initialize resources
   //<-
   #if 1
   managed_shared_memory segment(create_only,test::get_process_id_name(), 65536);
   #else
   //->
   managed_shared_memory segment
      (create_only 
      ,"MySharedMemory" //segment name
      ,65536);          //segment size in bytes
   //<-
   #endif
   //->

   //Note that map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>,
   //so the allocator must allocate that pair.
   typedef int    KeyType;
   typedef float  MappedType;
   typedef std::pair<const int, float> ValueType;

   //Alias an STL compatible allocator of for the map.
   //This allocator will allow to place containers
   //in managed shared memory segments
   typedef allocator<ValueType, managed_shared_memory::segment_manager> 
      ShmemAllocator;

   //Alias a map of ints that uses the previous STL-like allocator.
   //Note that the third parameter argument is the ordering function
   //of the map, just like with std::map, used to compare the keys.
   typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MyMap;

   //Initialize the shared memory STL-compatible allocator
   ShmemAllocator alloc_inst (segment.get_segment_manager());

   //Construct a shared memory map.
   //Note that the first parameter is the comparison function,
   //and the second one the allocator.
   //This the same signature as std::map's constructor taking an allocator
   MyMap *mymap = 
      segment.construct<MyMap>("MyMap")      //object name
                                 (std::less<int>() //first  ctor parameter
                                 ,alloc_inst);     //second ctor parameter

   //Insert data in the map
   for(int i = 0; i < 100; ++i){
      mymap->insert(std::pair<const int, float>(i, (float)i));
   }
   return 0;
}
Esempio n. 30
0
void tst_QMap::count()
{
    {
	MyMap map;
	MyMap map2( map );
	QCOMPARE( map.count(), 0 );
	QCOMPARE( map2.count(), 0 );
	QCOMPARE( MyClass::count, int(0) );
	// detach
	map2["Hallo"] = MyClass( "Fritz" );
	QCOMPARE( map.count(), 0 );
        QCOMPARE( map2.count(), 1 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 1 );
#endif
    }
    QCOMPARE( MyClass::count, int(0) );

    {
	typedef QMap<QString, MyClass> Map;
	Map map;
	QCOMPARE( map.count(), 0);
	map.insert( "Torben", MyClass("Weis") );
	QCOMPARE( map.count(), 1 );
	map.insert( "Claudia", MyClass("Sorg") );
	QCOMPARE( map.count(), 2 );
	map.insert( "Lars", MyClass("Linzbach") );
	map.insert( "Matthias", MyClass("Ettrich") );
	map.insert( "Sue", MyClass("Paludo") );
	map.insert( "Eirik", MyClass("Eng") );
	map.insert( "Haavard", MyClass("Nord") );
	map.insert( "Arnt", MyClass("Gulbrandsen") );
	map.insert( "Paul", MyClass("Tvete") );
	QCOMPARE( map.count(), 9 );
	map.insert( "Paul", MyClass("Tvete 1") );
	map.insert( "Paul", MyClass("Tvete 2") );
	map.insert( "Paul", MyClass("Tvete 3") );
	map.insert( "Paul", MyClass("Tvete 4") );
	map.insert( "Paul", MyClass("Tvete 5") );
	map.insert( "Paul", MyClass("Tvete 6") );

	QCOMPARE( map.count(), 9 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	Map map2( map );
	QVERIFY( map2.count() == 9 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	map2.insert( "Kay", MyClass("Roemer") );
	QVERIFY( map2.count() == 10 );
	QVERIFY( map.count() == 9 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 19 );
#endif

	map2 = map;
	QVERIFY( map.count() == 9 );
	QVERIFY( map2.count() == 9 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	map2.insert( "Kay", MyClass("Roemer") );
	QVERIFY( map2.count() == 10 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 19 );
#endif

	map2.clear();
	QVERIFY( map.count() == 9 );
	QVERIFY( map2.count() == 0 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	map2 = map;
	QVERIFY( map.count() == 9 );
	QVERIFY( map2.count() == 9 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	map2.clear();
	QVERIFY( map.count() == 9 );
	QVERIFY( map2.count() == 0 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 9 );
#endif

	map.remove( "Lars" );
	QVERIFY( map.count() == 8 );
	QVERIFY( map2.count() == 0 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 8 );
#endif

	map.remove( "Mist" );
	QVERIFY( map.count() == 8 );
	QVERIFY( map2.count() == 0 );
#ifndef Q_CC_SUN
	QCOMPARE( MyClass::count, 8 );
#endif
    }
    QVERIFY( MyClass::count == 0 );

    {
	typedef QMap<QString,MyClass> Map;
	Map map;
	map["Torben"] = MyClass("Weis");
#ifndef Q_CC_SUN
	QVERIFY( MyClass::count == 1 );
#endif
	QVERIFY( map.count() == 1 );

	(void)map["Torben"].str;
	(void)map["Lars"].str;
#ifndef Q_CC_SUN
	QVERIFY( MyClass::count == 2 );
#endif
	QVERIFY( map.count() == 2 );

	const Map& cmap = map;
	(void)cmap["Depp"].str;
#ifndef Q_CC_SUN
	QVERIFY( MyClass::count == 2 );
#endif
	QVERIFY( map.count() == 2 );
	QVERIFY( cmap.count() == 2 );
    }
    QCOMPARE( MyClass::count, 0 );
    {
	for ( int i = 0; i < 100; ++i )
	{
	    QMap<int, MyClass> map;
	    for (int j = 0; j < i; ++j)
		map.insert(j, MyClass(QString::number(j)));
	}
	QCOMPARE( MyClass::count, 0 );
    }
    QCOMPARE( MyClass::count, 0 );
}