声明结构的C元素的向量,和具有元件的数量是I(int类型的输入)

StackOverflow https://stackoverflow.com/questions/574060

  •  05-09-2019
  •  | 
  •  

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

我也试过其他方法,但在所有这些我接收到错误(不能转换℃至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 
有帮助吗?

解决方案

让我们尝试用一个解释:)

cin >> array[i];

这试图从cin提取到结构C.井的目的,因此它需要操作者>>实际执行这项工作:

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;
}

有关接下来的时间,请格式化文本(正确缩进它)。这是我很难步骤通过它:)

其他提示

没你的代码产生哪些错误?

我也不能确定你的代码是应该做的。 在main(),您可以创建C的载体,但C还含有INT的向量。是意图?

我真不明白你想要做的事。

不过,我已经可以看到一个潜在的错误在我们的代码:

在LerVector,你来与一个向量的参考当前不具有在它的任何项目,并且因此具有大小为0。

什么你想要做的是,只要我比尺寸更小,您更新的数组中。但是,当你开始的大小为0,所以我不认为你甚至可以进入输入回路。

现在,即使你这样做,因为向量不与任何尺寸初始化,你可能会认为你要出界的一个错误。你必须调整rray。

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

// 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
}

其中std::vector<T>构造将初始大小的,并且如果该次数之后声明是知道可以将其传递给构造。

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

或者可以使用大小调整方法来改变矢量的大小。

或者可以使用该加载方法来扩展向量(没有明确地给出的尺寸)。

但总体而言,它可能更容易给予帮助的代码和一个完整版本的代码的作用尝试做更多的细节。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top