我来帮你说清楚吧,对于如下代码
while (i <= n)
{
cin >> d >> w;
t.push_back(task(i, d,w));
++i;
}
需要这样输入
d0 w0
d1 w1
d2 w2
……
dn wn
现在我想改为这么输入
d0 d1 d2 …… dn
w0 w1 w2 …… nw
怎么办?
----------------------------------------------------------------
一种办法是先将输入的数据保存起来
程序代码:
struct task
{
int inumber;
int deadline;
int weight;
task( int inumber=0, int deadline=0, int weight=0 )
: inumber(inumber), deadline(deadline), weight(weight)
{
}
};
#include <vector>
#include <iostream>
int main( void )
{
const size_t n = 10;
std::vector<std::pair<int,int>> buf;
buf.resize( n );
for( size_t i=0; i!=n; ++i )
std::cin >> buf[i].first >> buf[i].second;
std::vector<task> tasks;
tasks.reserve( n );
for( size_t i=0; i!=buf.size(); ++i )
tasks.push_back( task(static_cast<int>(i+1),buf[i].first,buf[i].second) );
}
或者是只初始化一半
程序代码:
int main( void )
{
const size_t n = 10;
std::vector<task> tasks;
tasks.reserve( n );
for( size_t i=0; i!=n; ++i )
{
int deadline;
std::cin >> deadline;
tasks.push_back( task(static_cast<int>(i+1),deadline) );
}
for( size_t i=0; i!=tasks.size(); ++i )
std::cin >> tasks[i].weight;
}