How to pass a vector class vector as a function parameter?

Asked

Viewed 1,281 times

0

The contents of my vector are the data I wish to place in the matrix:

int main()
{
    vector<int> dados;
    int valores[4];
    string val;
    ifstream arq ("matriz.txt");
    if(arq.is_open())
    {
        while(! arq.eof())
        {
            getline(arq, val);
            int num;
            stringstream ss(val);
            while(ss >> num)
            {
                dados.push_back(num);
            }
        }
    // mais codigos aqui
    }
    }

In C++:

void Matrix::IniMatrix(int *vetor)
{
    for(int i=0; i<getLinha(); i++)
    {
        for(int j=0; j<getColuna(); j++)
        {
            elem[i][j] = vetor[1]; // int **elem (este é o tipo que esta declarado elem)
        }
    }
}
  • How does the first code relate to the second ? is trying to pass a native vector, int [] or a class vector vector, one vector<int> ?

2 answers

0

It’s an old question and the answer seems pretty simple, unless I’m missing something...

// void Matrix::IniMatrix(int *vetor)
void Matrix::IniMatrix(vector<int>& vetor)
{
  for (int i = 0; i < getLinha(); i++)
    for (int j = 0; j < getColuna(); j++)
      if (i < vetor.size()) // verifica se o indice e' valido no vetor
        elem[i][j] = vetor[i]; // int **elem (este é o tipo que esta declarado elem)
}

-1

The syntax of an array as a parameter in C is:

método(tipo_do_vetor nomedovetor[]){
//comandos aqui
}

Example:

int somadedois(int x[]){
    return (x[0]+x[1]);
}

In your case, the method would look like this:

void Matrix::IniMatrix(int vetor[])
{
   for(int i=0; i<getLinha(); i++)
   {
       for(int j=0; j<getColuna(); j++)
       {
           elem[i][j] = vetor[1]; // int **elem (este é o tipo que esta declarado elem)
       }

   }
}
  • this answer adds nothing, since "int somadedois(int x[])" is the same thing as "int somadedois(int? x)" as is already being used in the question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.