Esempio n. 1
0
void task4_6::solution::calculate()
{
    std::vector< std::string > strs;
    for ( int i = 0; i < lines_.size(); ++i )
    {
        try
        {
            boost::split( strs, lines_[i], boost::is_any_of( "=" ) );
            if ( strs.size() > 2 )
            {
                throw std::logic_error( "not correct expression at %1% line" );
            }

            std::string var_name = boost::trim_copy( strs[0] );
            std::string expression = boost::trim_copy( strs[1] );
            if(vars_.find( var_name ) != vars_.end())
            {
                throw std::logic_error(
                    ( boost::format( "such variable '%1%' already exists (%2%)" )
                    % var_name % "%1%" ).str() ); 
            }

            vars_[ var_name ] = calculate_rpn( to_rpn( expression ) );
        }
        catch ( const std::logic_error& e )
        {
            throw std::logic_error( ( boost::format( e.what() ) % ( i + 1 ) ).str() );
        }
    }
}
Esempio n. 2
0
int main( int argc, char *argv[] )
{
    (void) argc;
    (void) argv;

    std::cout << "Enter string for calculation: ";
    std::string input;
    std::getline(std::cin, input);
    std::cout << std::endl;

    std::chrono::high_resolution_clock clock;
    auto start = clock.now();

    try {
        const auto& tokens = to_tokens(input);
        std::cout << "tokens:" << std::endl;
        std::for_each(tokens.begin(), tokens.end(), [&tokens](const token& t) {
            std::cout << "value: " << t.get_value() << " type: " << t.get_type() << std::endl;
        });
        std::cout << std::endl;

        if(tokens.empty()) {
            throw std::runtime_error("Invalid tokens: empty input string");
        }

        const auto& rpn = to_rpn(tokens);
        std::cout << "RPN:" << std::endl;
        std::for_each(rpn.begin(), rpn.end(), [&tokens](const token& t) {
            std::cout << "value: " << t.get_value() << " type: " << t.get_type() << std::endl;
        });
        std::cout << std::endl;

        if(rpn.empty()) {
            throw std::runtime_error("Invalid rpn: empty input string");
        }

        const auto& result = calculate<double>(rpn, std::atof);
        std::cout << "result: " << result << std::endl;
    }
    catch(const std::exception& error) {
        std::cout << "Error: " << error.what() << std::endl;
    }

    auto end = clock.now();
    std::cout << "Input size: " << input.size() << " calculate: " << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << " us" << std::endl;
    return 0;
}