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


C++ QStack::empty方法代码示例

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


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

示例1: isExpressionValid

/* return true if expression is mathematically correct
 * Currently only checks...
 * brackets
 * Makes sure there's not a space or '*' after of before each '*'
 */
bool MathStringParser::isExpressionValid(const QString &str) {
    QStack<char> bracketStack;
    for (int i = 0; i < str.size(); ++i) {
        if (str[i] == ' ') {
            if (!bracketStack.empty()) {
                return false;
            }
        } else if (str[i] == '(') {
            bracketStack.push('(');
        } else if (str[i] == ')') {
            if (bracketStack.empty()) {
                return false;
            } else {
                bracketStack.pop();
            }
        }
    }

    if (!bracketStack.empty()) {
        return false;
    }

    if (str.contains("**") || str.contains(" *") ||
            str.contains("* ")) {
        return false;
    }

    return true;
}
开发者ID:bgstewart,项目名称:Integrator,代码行数:34,代码来源:mathstringparser.cpp

示例2: scanDirectory

void CollectionScanner::scanDirectory(QDir directory) {

    QStack<QDir> stack;
    stack.push(directory);
    while(!stack.empty()) {

        const QDir dir = stack.pop();
        const QFileInfoList flist = dir.entryInfoList(
                    QDir::NoDotAndDotDot |
                    QDir::Dirs | QDir::Files | QDir::Readable
                    );

        QFileInfo fileInfo;
        Q_FOREACH(fileInfo, flist) {
            if(fileInfo.isFile() ) {
                processFile(fileInfo);
            } else if (fileInfo.isDir()) {
                QString subDirPath = fileInfo.absoluteFilePath();
#ifdef APP_MAC
                if (directoryBlacklist.contains(subDirPath)) {
                    qDebug() << "Skipping directory" << subDirPath;
                    continue;
                }
#endif
                QDir subDir(subDirPath);
                stack.push(subDir);
            }
        }
    }

}
开发者ID:PhillipMwaniki,项目名称:musique,代码行数:31,代码来源:collectionscanner.cpp

示例3: cur

void KoTextWriter::Private::writeBlocks(QTextDocument *document, int from, int to, QHash<QTextList *, QString> &listStyles, QTextTable *currentTable, QTextList *currentList)
{
    pairedInlineObjectsStackStack.push(currentPairedInlineObjectsStack);
    currentPairedInlineObjectsStack = new QStack<KoInlineObject*>();
    QTextBlock block = document->findBlock(from);

    // Here we are going to detect all sections that
    // are positioned entirely inside selection.
    // They will stay untouched, and others will be omitted.

    // So we are using stack to detect them, by going through
    // the selection and finding open/close pairs.
    QSet<QString> entireWithinSectionNames;
    QStack<QString> sectionNamesStack;
    QTextCursor cur(document);
    cur.setPosition(from);
    while (to == -1 || cur.position() <= to) {
        if (cur.block().position() >= from) { // Begin of the block is inside selection.
            foreach (const KoSection *sec, KoSectionUtils::sectionStartings(cur.blockFormat())) {
                sectionNamesStack.push_back(sec->name());
            }
        }

        if (to == -1 || cur.block().position() + cur.block().length() - 1 <= to) { // End of the block is inside selection.
            foreach (const KoSectionEnd *sec, KoSectionUtils::sectionEndings(cur.blockFormat())) {
                if (!sectionNamesStack.empty() && sectionNamesStack.top() == sec->name()) {
                    sectionNamesStack.pop();
                    entireWithinSectionNames.insert(sec->name());
                }
            }
        }
开发者ID:ChrisJong,项目名称:krita,代码行数:31,代码来源:KoTextWriter_p.cpp

示例4: nodevisited

QList<ListDigraph::Node> ProcessModel::topolSortReachableFrom(const QList<ListDigraph::Node>& s) {
	ListDigraph::NodeMap<bool > nodevisited(graph, false);
	QList<ListDigraph::Node> res;
	QStack<ListDigraph::Node> stack;
	ListDigraph::Node curnode;
	ListDigraph::Node pnode;
	ListDigraph::Node snode;
	QList<ListDigraph::Node> reachable = reachableFrom(s);

	// Reserve memory
	res.reserve(countNodes(graph));
	stack.reserve(countNodes(graph));

	for (int i = 0; i < s.size(); i++) {
		if (s[i] != INVALID) {
			stack.push(s[i]);
		}
	}

	bool psched;
	while (!stack.empty()) {
		curnode = stack.pop();

		if (!nodevisited[curnode]) { // This node has not been visited yet

			// Check whether all predecessors in reachable are scheduled
			psched = true;
			for (ListDigraph::InArcIt iait(graph, curnode); iait != INVALID; ++iait) {
				pnode = graph.source(iait);
				if (reachable.contains(pnode)) { // Consider only nodes which can be reached from s
					if (!nodevisited[pnode]) {
						psched = false;
						break;
					}
				}
			}

			if (psched) { // All predecessors have been visited
				res.append(curnode);
				nodevisited[curnode] = true;

				// Push the succeeding nodes
				for (ListDigraph::OutArcIt oait(graph, curnode); oait != INVALID; ++oait) {
					snode = graph.target(oait);
					if (!nodevisited[snode]) {
						stack.push(snode);
					}
				}
			} else {
				stack.prepend(curnode);
			}

		} // Else ignore the visited node
	}

	return res;
}
开发者ID:DrSobik,项目名称:IPPS,代码行数:57,代码来源:ProcessModel.cpp

示例5: getClosingBracketIndex

int MathStringParser::getClosingBracketIndex(const QString &str, int pos) {
    QStack<char> bracketStack;
    //qDebug() << str << pos;
    while (pos < str.size()) {
        if (str[pos] == '(') {
            bracketStack.push('(');
        } else if (str[pos] == ')') {
            bracketStack.pop();
            if (bracketStack.empty()) {
                return pos;
            }
        }
        ++pos;
    }

    if (pos == str.size() || !bracketStack.empty()) {
        return -1;
    }

    return str.size()-1;
}
开发者ID:bgstewart,项目名称:Integrator,代码行数:21,代码来源:mathstringparser.cpp

示例6: on_pushButton_clicked

void MainWindow::on_pushButton_clicked()
{
    QStack<QString> stk;
    QString str = ui->textEdit->toPlainText(), str2=str;
    bool f=false;
    bool Pr=false, f2=true,f3=true;

    for(int i=0; i<str.count();i++)
        if ((str.at(i)=='0')||(str.at(i)=='1'))
              Pr= true;
    else
            Pr = false;


//        if(str.count("0")!=str.count("1"))
//            f3=false;

    if(str.isEmpty()||(Pr==false))//||(f3=false))
    {
        ui->textEdit_2->insertPlainText("Error");
    }
        else
        {
         for(int i=0;i<str.count();i++)
            {
             if (str.at(i)=='0')
             {
                 stk.push("0");
                 f=true;

             }
             if ((str.at(i)=='1'))
                 if(!stk.empty())
                 stk.pop();
                 else
                 {
                 ui->textEdit_2->insertPlainText("Error");
                 f2=false;
                 break;
                 }


       }
    }


    if ((f==true)&&(stk.isEmpty())&&(f2))
        ui->textEdit_2->insertPlainText("Right");
}
开发者ID:curiousbraain,项目名称:1,代码行数:49,代码来源:mainwindow.cpp

示例7: searchDepthFirst

Node* NavMesh::searchDepthFirst(Node *start, Node* goal)
{
    QStack<Node*> stack;
    stack.push(start);
    while( !stack.empty() )
    {
        Node* node = stack.pop();
        if ( node->visited() ) 
            continue;
        if ( node == goal ) 
            return node;
        node->setVisited(true);
        AdjacencyList::Iterator arc;
        for( arc = node->adjacents.begin(); arc != node->adjacents.end(); ++arc )
        {
            if ( ! (*arc)->to->visited() )
                stack.push( (*arc)->to );
        }
    }
    return 0;
}
开发者ID:BackupTheBerlios,项目名称:qsim-svn,代码行数:21,代码来源:navmesh.cpp

示例8: scanRoot

void Project::scanRoot()
{
    QStack<QDir> directoryStack;
    directoryStack.push(m_root);

    while (!directoryStack.empty()) {
        QDir directory(directoryStack.pop());
        qint64 updated = QDateTime::currentDateTime().toTime_t();
        QFileInfoList entries(directory.entryInfoList(QDir::NoFilter, QDir::DirsLast));

        for (int i = 0; i < entries.length(); i++) {
            if (entries[i].fileName() == "." || entries[i].fileName() == "..")
                continue;

            QString absolutePath(entries[i].absoluteFilePath());
            addOrUpdateEntry(getRelativePath(absolutePath), updated);

            if (entries[i].isDir())
                directoryStack.push(QDir(absolutePath));
        }
    }
}
开发者ID:mrobinson,项目名称:pecera,代码行数:22,代码来源:Project.cpp

示例9: checkSectionModelLevel

void TestKoTextEditor::checkSectionModelLevel(TestDocument *doc)
{
    // Assuming here that Formatting level is OK
    // Below I will rebuild sections structure from scratch
    // and compare it then with a KoSectionModel

    QVector<SectionHandle *> allSections, rootSections;
    QStack<SectionHandle *> sectionStack;

    QTextBlock curBlock = doc->m_document->firstBlock();
    // This kind of cycle should visit all blocks
    // including ones in tables and frames.
    while (curBlock.isValid()) {
        QList<KoSection *> secStartings = KoSectionUtils::sectionStartings(curBlock.blockFormat());
        QList<KoSectionEnd *> secEndings = KoSectionUtils::sectionEndings(curBlock.blockFormat());

        foreach(KoSection *sec, secStartings) {
            SectionHandle *handle = new SectionHandle(sec);
            if (sectionStack.empty()) {
                rootSections.push_back(handle);
                handle->parent = 0;
            } else {
                sectionStack.top()->children.push_back(handle);
                handle->parent = sectionStack.top()->sec;
            }

            allSections.push_back(handle);
            sectionStack.push(handle);
        }

        foreach(KoSectionEnd *secEnd, secEndings) {
            sectionStack.pop();
        }

        curBlock = curBlock.next();
    }
开发者ID:woylaski,项目名称:kexi,代码行数:36,代码来源:TestKoTextEditor.cpp

示例10: RPN

void Parser::RPN()
{
    if (sourceStr.at(0) == '-') sourceStr = "0"+sourceStr;
    sourceStr.replace("(-","(0-");
    sourceStr.replace("( -","(0-");
    sourceStr.replace("+"," + ");
    sourceStr.replace("-"," - ");
    sourceStr.replace("*"," * ");
    sourceStr.replace("/"," / ");
    sourceStr.replace("^"," ^ ");
    sourceStr.replace(")"," ) ");
    sourceStr.replace("("," ( ");
    QStringList tokens;
    QStringList op;
    op << "+" << "-" << "*" << "/" << "^";

    QStack <QString> stack;
    rpnStr = "";
    tokens = sourceStr.split(QRegExp("\\s+"));

    qDebug() << "tokens: " << tokens;

    for (int it = 0; it < tokens.size(); ++it)
    {
        qDebug() << "rpnStr: " << rpnStr ;
        if ((tokens.at(it).at(0) >='0' && tokens.at(it).at(0) <='9')
                ||
                (tokens.at(it).at(0) >='a' && tokens.at(it).at(0) <='z') )
        {
            rpnStr += tokens.at(it); rpnStr += " "; continue;
        }
        if (tokens.at(it) == "(")
        {
            stack.push(tokens.at(it)); continue;
        }
        if (tokens.at(it) == ")")
        {
            while (stack.top() != "(")
            {
                rpnStr += stack.pop(); rpnStr += " ";
            }
            stack.pop(); continue;
        }
        if (op.indexOf(tokens.at(it)) >= 0)
        {
            if (tokens.at(it) == "^")
            {
                stack.push(tokens.at(it)); continue;
            }
            if (tokens.at(it) == "*" || tokens.at(it) == "/")
            {
                if (!stack.isEmpty())
                {
                    while(!stack.isEmpty() && (stack.top() == "^") )
                    {
                        rpnStr += stack.pop(); rpnStr += " ";
                    }
                }
                stack.push(tokens.at(it)); continue;
            }
            if (tokens.at(it) == "+" || tokens.at(it) == "-")
            {
                if (!stack.isEmpty())
                {
                    while(!stack.isEmpty() && (stack.top() == "^" || stack.top() == "/" || stack.top() == "*" || stack.top() == "+" || stack.top() == "-"))
                    {
                        rpnStr += stack.pop(); rpnStr += " ";
                    }
                }
                stack.push(tokens.at(it)); continue;
            }
        }
    }
    while (!stack.empty())
    {
        if (stack.top() != "")
        {
            rpnStr += stack.pop(); rpnStr += " ";
        }
        else
        {
            stack.pop();
        }
    }
    qDebug() << "rpnStr: " << rpnStr ;
    qDebug() << "source: " << sourceStr;
}
开发者ID:Aleksandar7kr,项目名称:ETU,代码行数:87,代码来源:parser.cpp

示例11: parse

bool SimpleJsonParser::parse(const QByteArray& json)
{
	resetState();

	m_source = json;
	m_ptr = m_source.data();
	m_end = m_ptr + m_source.length();

	QStack<QString> stack;
	QVariantMap result;

	QVector<Token> expectedTokens;
	expectedTokens.push_back(Token_Begin);
	Token prevToken = Token_ERROR;

	QString lastStr;
	QString prefix;
	QString lastKey;

	for (;;) {
		Token token = nextToken();
		if (expectedTokens.indexOf(token) < 0) {
			DBGLOG(LOG_ERROR, 2, QString::fromUtf8("unexpected token %1").arg(token));
			return false;
		}
		switch (token) {
		case Token_ERROR:
			return false;
		case Token_EOF:
			if (!stack.empty()) {
				DBGLOG(LOG_ERROR, 2, QString::fromUtf8("unblanced { }, bad json!"));
				return false;
			}
			m_result = result;
			return true;
		case Token_Begin:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token BEGIN"));
			if (stack.empty()) {
				stack.push_back(QString::fromUtf8(""));
			} else {
				stack.push_back(prefix);
				prefix.append(lastKey);
				prefix.append(QChar::fromAscii('.'));
			}
			expectedTokens.clear();
			expectedTokens.push_back(Token_End);
			expectedTokens.push_back(Token_String);
			break;
		case Token_End:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token END"));
			prefix = stack.pop();
			if (!stack.empty()) {
				expectedTokens.clear();
				expectedTokens.push_back(Token_Comma);
				expectedTokens.push_back(Token_End);
			} else {
				expectedTokens.push_back(Token_EOF);
			}
			break;
		case Token_Comma:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token COMMA"));
			expectedTokens.clear();
			expectedTokens.push_back(Token_End);
			expectedTokens.push_back(Token_String);
			break;
		case Token_Colon:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token COLON"));
			expectedTokens.clear();
			expectedTokens.push_back(Token_Begin);
			expectedTokens.push_back(Token_String);
			expectedTokens.push_back(Token_Number);
			break;
		case Token_String:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token STRING [%1]").arg(QString::fromUtf8(m_str)));

			if (prevToken == Token_Colon) {
				DBGLOG(LOG_DEBUG, 12, QString::fromUtf8("submit '%3%1'='%2'").arg(lastKey).arg(QString::fromUtf8(m_str)).arg(prefix));
				result.insert(prefix + lastKey, QString::fromUtf8(m_str));
			} else {
				lastKey = QString::fromUtf8(m_str);
			}

			// TODO:
			expectedTokens.clear();
			expectedTokens.push_back(Token_End);
			expectedTokens.push_back(Token_Comma);
			expectedTokens.push_back(Token_Colon);
			break;
		case Token_Number:
			DBGLOG(LOG_DEBUG, 8, QString::fromUtf8("token NUMBER [%1]").arg(m_num));
			DBGLOG(LOG_DEBUG, 12, QString::fromUtf8("submit '%3%1'=%2").arg(lastKey).arg(m_num).arg(prefix));
			result.insert(prefix + lastKey, m_num);
			expectedTokens.clear();
			expectedTokens.push_back(Token_End);
			expectedTokens.push_back(Token_Comma);
			break;
		}

		prevToken = token;
	}
//.........这里部分代码省略.........
开发者ID:daddyreb,项目名称:Bigit_Genie,代码行数:101,代码来源:oputil.cpp

示例12: main_parser

QString RPN_utility::main_parser(QString &formula) {


    QString output_string;
    QTextStream iss(&formula);

    QTextStream output(&output_string);
    QStack <QString> s;


    QString token;

    while(!iss.atEnd())
    {
        iss >> token;

        //If token is a number
        if( isnumber(token) || ( token.length() == 1 &&  token[0].isLetter() ) ) {
            output << token << " ";

        //if function separator
        } else if (token[0] ==  ',') {

            while (s.top() != "(" ) {
                output << s.top() << " ";
                s.pop();
            }

        //If token is an operator
        } else if( token.length() == 1 && isoperator(token) ) {

                       while ( !s.isEmpty() && ( (TAB_OP[token[0]].second == LEFT && TAB_OP[token[0]].first <= TAB_OP[s.top()[0]].first)
                                        ||
                                    (TAB_OP[token[0]].second == RIGHT && TAB_OP[token[0]].first < TAB_OP[s.top()[0]].first)
                                  )
                  ) {
                output << s.top() << " ";
                s.pop();
            }
            s.push(token);

       //Si c'est une fonction
       } else if (token.length() > 1 ) {
        s.push(token);


       //Si c'est une parenthèse ouvrante
       } else if (token == "(" ) {
            s.push(token);

       //Si c'est une parenthèse fermante
       } else if (token == ")" ) {

            while (s.top() != "(" ) {
                output << s.top() << " ";
                s.pop();
            }
            s.pop();

            if ( !s.empty() && s.top().length() > 1 ) {
                output << s.top() << " ";
                s.pop();
            }


        }

        token = "";



    }

    while (!s.empty()) {
        output << s.top() << " ";
        s.pop();
    }

    output.flush();
    return output_string;

}
开发者ID:NobilisNC,项目名称:Projet_cpp,代码行数:82,代码来源:rpn_utility.cpp

示例13: run

void FileIndexThread::run()
{
    struct PathToIndex
    {
        QString path;
        bool    recursive;
        QStringList filter;
    };

#ifdef Q_OS_UNIX
    static const QList<PathToIndex> pathsToIndex = {
        { "/usr/share/applications", true, { "*.desktop" } },
        { QDir(QDir::homePath()).relativeFilePath(".local/share/applications"), true, { "*.desktop" } },
        { QDir(QDir::homePath()).relativeFilePath("Desktop"), true, { "*.desktop" } },
    };
#elif defined(Q_OS_WIN)
    QList<PathToIndex> pathsToIndex = {
        { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Desktop").toString(), true, { "*.lnk" } },
        { QSettings("HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders", QSettings::NativeFormat).value("Common Start Menu").toString(), true, { "*.lnk" } },
    };

    {
        // There are newer API functions for this; but they are only for Vista and newer
        WCHAR szPath[MAX_PATH];
        HRESULT hr = SHGetFolderPathW(0, CSIDL_STARTMENU, 0, 0, szPath);
        if (SUCCEEDED(hr))
            pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } });

        hr = SHGetFolderPathW(0, CSIDL_DESKTOPDIRECTORY, 0, 0, szPath);
        if (SUCCEEDED(hr))
            pathsToIndex.push_back({ QString::fromWCharArray(szPath), true, { "*.lnk" } });
    }
#else
#error "Not implemented for this operating system"
#endif

    for (const PathToIndex& pathInfo : pathsToIndex)
    {
        const QString pathString = expandEnvironmentPath(pathInfo.path);
        QStack<QString> dirstack;
        dirstack.push_back(expandEnvironmentPath(pathString));

        while (dirstack.empty() == false)
        {
            QDir path(dirstack.pop());
            path.setNameFilters(pathInfo.filter);

            for (const QString& filename : path.entryList())
            {
                int dot = filename.lastIndexOf('.');
                const QString basename = dot > 0 ? filename.left(dot) : filename;

                dbLock.lockForWrite();
                this->db.add(basename, basename, path.absoluteFilePath(filename), QStringList());
                dbLock.unlock();
            }

            // For now, no symlink traversal to avoid loops
            for (const QString& dirname : path.entryList(QStringList(), QDir::AllDirs | QDir::NoSymLinks | QDir::NoDotAndDotDot))
            {
                dirstack.push_back(path.absoluteFilePath(dirname));
            }
        }
    }

#ifdef Q_OS_WIN
    const QString systemPath = getWindowsSystemPath();

    for (const QString& filename : QDir(systemPath).entryList({ "*.cpl" }))
    {
        readCpl(filename, this->db, this->dbLock);
    }
#endif

    emit indexDone();
}
开发者ID:jslick,项目名称:KeyRunner,代码行数:76,代码来源:fileindexthread.cpp

示例14: expandMacrosShellQuote


//.........这里部分代码省略.........
                    pos += 2;
                    continue;
                } else {
                    state.current = paren;
                    state.dquote = false;
                }
            } else if (cc == '{') {
                sstack.push( state );
                state.current = subst;
            } else if (!state.dquote) {
                if (cc == '\'') {
                    sstack.push( state );
                    state.current = dollarquote;
                } else if (cc == '"') {
                    sstack.push( state );
                    state.current = doublequote;
                    state.dquote = true;
                }
            }
            // always swallow the char -> prevent anomalies due to expansion
        } else if (cc == '`') {
            str.replace( pos, 1, QLatin1String("$( " )); // add space -> avoid creating $((
            pos2 = pos += 3;
            for (;;) {
                if (pos2 >= str.length()) {
                    pos = pos2;
                    return false;
                }
                cc = str.unicode()[pos2].unicode();
                if (cc == '`')
                    break;
                if (cc == '\\') {
                    cc = str.unicode()[++pos2].unicode();
                    if (cc == '$' || cc == '`' || cc == '\\' ||
                        (cc == '"' && state.dquote))
                    {
                        str.remove( pos2 - 1, 1 );
                        continue;
                    }
                }
                pos2++;
            }
            str[pos2] = QLatin1Char(')');
            sstack.push( state );
            state.current = paren;
            state.dquote = false;
            continue;
        } else if (state.current == doublequote) {
            if (cc == '"')
                state = sstack.pop();
        } else if (cc == '\'') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = singlequote;
            }
        } else if (cc == '"') {
            if (!state.dquote) {
                sstack.push( state );
                state.current = doublequote;
                state.dquote = true;
            }
        } else if (state.current == subst) {
            if (cc == '}')
                state = sstack.pop();
        } else if (cc == ')') {
            if (state.current == math) {
                if (str.unicode()[pos + 1].unicode() == ')') {
                    state = sstack.pop();
                    pos += 2;
                } else {
                    // false hit: the $(( was a $( ( in fact
                    // ash does not care, but bash does
                    pos = ostack.top().pos;
                    str = ostack.top().str;
                    ostack.pop();
                    state.current = paren;
                    state.dquote = false;
                    sstack.push( state );
                }
                continue;
            } else if (state.current == paren)
                state = sstack.pop();
            else
                break;
        } else if (cc == '}') {
            if (state.current == KMacroExpander::group)
                state = sstack.pop();
            else
                break;
        } else if (cc == '(') {
            sstack.push( state );
            state.current = paren;
        } else if (cc == '{') {
            sstack.push( state );
            state.current = KMacroExpander::group;
        }
        pos++;
    }
    return sstack.empty();
}
开发者ID:crayonink,项目名称:calligra-2,代码行数:101,代码来源:kmacroexpander_unix.cpp

示例15: evaluer

Litterale* Expression::evaluer() const{
    QString s = value;
    //On vire les '
    s=s.remove(0,1);
    s=s.remove(s.length()-1,s.length());
    QString::iterator it = s.begin();
    //QString contenant le résultat
    QString postfix;

    //Stack d'opérations
    QStack<QString> stack;

    //Map des opérateurs
    const QMap<QString, Operateur*> op_map = OperateurFactory::getMap();

    //Map de tous les symboles
    const QMap<QString,WordIdentifier*>& interpretation_map = Controleur::getInterpretationMap();

    //Traduction de Infix vers Postfix

    QString tmp;
    bool found;

    while(it!=s.end()){
        found=false;

        if(*it==' ' || *it==','){
            it++;
            continue;
        }

        //Verification que ce n'est pas une litterale avec 2 symboles exemple : Expression ou Programme
        if(tmp == "" && interpretation_map.find(*it)!=interpretation_map.end()){
            WordIdentifier *identifier = interpretation_map.find(*it).value();
            WordIdentifier *try1;
            WordIdentifier *try2;

            try1=dynamic_cast<RecursiveEncapsulatorIdentifier*>(identifier);
            try2=dynamic_cast<EncapsulatorIdentifier*>(identifier);
            if(try1 || try2)
            {
                    throw LitteraleException("Litterale "+ QString(*it) +" non permise","Inconnu");
            }
        }

        //On tombe dans le cas ou on a une valeur
        while(it!=s.end() && ((*it<='9' && *it>='0') || (interpretation_map.find(*it)!=interpretation_map.end()))){
              tmp+=*it;
              if(it!=s.end())
                  it++;
        }
        //Pour vider ce qu'on a trouvé
        if(tmp!=""){
            postfix+=tmp+" ";
            tmp.clear();
            found=true;

        }

        //On tombe dans le cas d'un morçeau de texte
        if((*it<='Z' && *it>='A')){
            while(it!=s.end() && ((*it<='Z' && *it>='A') || (*it<='9' && *it>='0'))){
                tmp+=* it;
                if(it!=s.end())
                    it++;
            }
            if(isOperator(tmp)){
                found=true;
                while(!stack.empty() && stack.top() != "(" && CompareOperators(stack.top(),tmp)<=0){
                    postfix += stack.top()+" ";
                    stack.pop();
                }
            stack.push(tmp);
            tmp.clear();
            }
            else if(isVariable(tmp)){
                found=true;
                Litterale* l = VariablesManager::getVariable(tmp);
                if(estdeType<Programme>(l))
                    throw OperateurException("Un programme est dans l'expression !");

                QString rep = l->toString();
                int length_it = s.indexOf(tmp);
                s.replace(tmp,rep);
                it = s.begin();
                for(int i=0; i<length_it;i++,it++);
                tmp.clear();

            }
            else
                throw(LitteraleException("Le mot "+tmp+" est inconnu","Inconnu"));

        }

        if(*it=='('){
            stack.push(*it);
            if(it!=s.end())
                it++;
            found=true;
        }
//.........这里部分代码省略.........
开发者ID:gabriel-hurtado,项目名称:UTComputer,代码行数:101,代码来源:litterales.cpp


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