-2

请看这段代码(并原谅缺乏知识)。它输出我无法解决的错误。我需要声明结构 C 的元素向量,但我需要元素的数量为 i(int 类型的输入)。

我也尝试了其他方法,但在所有这些方法中我都收到了一个错误(无法将 C 转换为 int 等)。我怎样才能做到这一点?

# include < iostream >
using std::cout;
using std::cin;
using std::endl;

# include < vector >
using std::vector;

struct C{
    int cor;
    vector<int>cores;

    };

    void LerVector( vector< C> &array ) ;

int main ()
{
     int n;
    bool done=false;
        bool don=false;
    vector<C>cidade;
    int i;


    while(!done){
    cout<<"Entre o número de cidades "<<endl;
    cin>>n;
    if(n>500)
    {
        cout<<endl;
        cout<<"O número máximo é 500"<<endl;
}
else
done=true;
}
n--;
while(!don){
cout<<"Entre o número de confederações"<<endl;
cin>>i;
if(i>100){
cout<<endl;
cout<<"Número máximo de 100 cidades"<<endl;

}
else {

 LerVector(  cidade) ;

don=true;
}
}


    cin.get();
    return 0;
}
//resolve...
 void LerVector( vector< C> &array ) 
  { 
    for ( size_t i = 0; i < array.size(); i++ ) 
      cin>>array[i];

  } // end function inputVector 
4

5 回答 5

3

让我们尝试解释一下:)

cin >> array[i];

它试图从cinstruct C 的对象中提取出来。嗯,所以它需要一个 operator>> 来实际工作:

istream & operator>>(istream &is, C &c) {
    is >> c.cor; // or into whatever member 
    return is;
}

此外,正如另一个提到的,您必须首先将元素实际添加到向量中:

while(!don){
    cout<<"Entre o número de confederações"<<endl;
    ....
} else {
    cidade.resize(i); // resize to i elements
    LerVector(cidade);
    don = true;
}

下次请格式化文本(正确缩进)。我很难通过它:)

于 2009-02-22T01:07:09.300 回答
1

您的代码产生了哪些错误?

我也不确定你的代码应该做什么。在 main() 中,您创建了一个 C 向量。但 C 还包含一个 int 向量。这是故意的吗?

于 2009-02-22T01:02:06.163 回答
1

我不太清楚你想做什么。

但是,我已经可以在我们的代码中看到一个潜在的错误:

在 LerVector 中,您输入的是对当前没有任何项目的向量的引用,因此其大小为 0。

您要做的是,只要 i 小于大小,您就会更新数组中的该项目。但是,当您开始时大小为 0,所以我认为您甚至不会进入输入循环。

现在,即使你这样做了,由于向量没有用任何大小初始化,你可能会得到一个错误,你会越界。您必须调整阵列的大小。

于 2009-02-22T01:02:06.443 回答
0

如果我猜你想做什么,应该是这样的:

// First create an empty vector of C's
vector<C> cidade;

// cidade has zero elements now
// Read i from user
cin >> i;

// Resize vector to contain i elements
cidade.resize(i);

// Then go on and fill them.
int n;
for (n = 0; n < i; i++) {
  cin >> cores;
  cidade[n].cores.resize(cores);
  // now cidade[n].cores has 'cores' elements, but they are uninitialized
}
于 2009-02-22T01:01:10.860 回答
0

其中一个std::vector<T>构造函数将采用初始大小,如果在该数字之后声明,则可以将其传递给构造函数。

cin >> n;
std::vector<C> cidade(n);

或者您可以使用 resize 方法来更改矢量的大小。

或者您可以使用 add 方法来扩展向量(无需明确给出大小)。

但总的来说,使用完整版本的代码和更多关于代码试图做什么的细节提供帮助可能会更容易。

于 2009-02-22T01:03:07.347 回答