1

ACM IPC の問題の 1 つにコードを送信する必要がありますが、ご存知かもしれませんが、時間が非常に重要です。したがって、次のような入力を効率的に読み取る必要があります。最初の行には、関連付けられた整数値のシーケンスが含まれ、2 行目には、別のシーケンスに関連付けられた整数値のシーケンスが含まれます。例えば:

3 2 1 4 5 7 6    
3 1 2 5 6 7 4   
7 8 11 3 5 16 12 18   
8 3 11 7 16 18 12 5   
255  
255

1行目を配列に、2行目を別の行に入れ、両方を関数に渡す必要があります。

これらを C/C++ で読み込んで配置するにはどうすればよいですか? 私は C の方法で考えていましたが、私のアプローチには 2 つの while があります... 私は scanf で読み取ることを好みますが、解析は必要に応じて行うことができます。

この初心者を助けてください!

4

3 に答える 3

3

を使用して行を読み取りstd::getline()ます。次に、 a を使用しstd::stringstreamて各行を解析します。これは競技用であるため、実際のコードは必要ありません。

于 2010-02-17T14:33:14.837 に答える
1
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

typedef std::vector< int > ints_t;

void dump_ints( const ints_t& input )
{
    std::copy(
        input.begin(),
        input.end(),
        std::ostream_iterator< int >( std::cout, " " ) );
    std::cout << std::endl;
}

void foo( const ints_t& first, const ints_t& second )
{
    dump_ints( first );
    dump_ints( second );
}

bool parse_line( std::istream& is, ints_t* output )
{
    std::string line;
    if ( std::getline( is, line ) )
    {
        std::istringstream raw_ints( line );
        std::copy(
            std::istream_iterator< int >( raw_ints ),
            std::istream_iterator< int >(),
            std::back_inserter( *output ) );
        return true;
    }
    else
    {
        return false;
    }
}

bool parse( std::istream& is, ints_t* first, ints_t* second )
{
    const bool result = parse_line( is, first ) && parse_line( is, second );
    return result;
}

void run( std::istream& is )
{
    while ( is )
    {
        ints_t first;
        ints_t second;
        if ( parse( is, &first, &second ) )
        {
            foo( first, second );
        }
    }
}

int main()
{
    //if you want to read input from file use ifstream and comment istringstream 
//    std::ifstream is( "put_here_a_path_to_input_file" );
    std::istringstream is( 
        "3 2 1 4 5 7 6\n"
        "3 1 2 5 6 7 4\n"
        "7 8 11 3 5 16 12 18\n"
        "8 3 11 7 16 18 12 5\n"
        "255\n"
        "255\n" 
        );
    run( is );
}
于 2010-02-17T14:56:22.933 に答える