C++: Vector in a function

Asked

Viewed 104 times

1

I’m doing a project where I use many vector vectors. Only working with array vectors is easier, so I did the following function:

// add.cpp
vector <string> sAdd (string In[])
{
   vector <string> Out;
   Out.resize (sizeof(In));

   for (int i = 0; i < sizeof(In); i++)
      Out[i] = In[i];

   return Out;
}

// add.h
vector <string> sAdd (string In[]);

// main.cpp
#include "add.h"

int main (void)
{
   vector<string> op;
   op = sAdd (string temp[3] = {
      "Opcao1",
      "Opcao2",
      "Opcao3"
});

But the following error occurs in main.cpp: "Some argument was expected in Sadd." What I did wrong?

Note: I’m a beginner, so if you have an easier way, please tell me.

1 answer

1


First of all, you cannot use "sizeof" to check the amount of string in a standard array, because the string class uses pointers and dynamic allocation internally. You will have to pass the size of the array in its function:

vector<string> sAdd(string In[3], int size)

Or else you’ll have to use Std::array.

You cannot pass an array this way, you need to specify its size in its function, or use a pointer:

#include <iostream>
#include <string>
#include <vector>
using namespace std;


vector<string> sAdd(string* In, int size)
{
    vector <string> Out;
    Out.resize(size);

    for (int i = 0; i < size; i++)
        Out[i] = In[i];

    return Out;
}


int main()
{
    vector<string> op;
    string arr[] = { "Opcao1", "Opcao2", "Opcao3" };
    op = sAdd(arr, 3);

    return 0;
}
  • Thanks man. You know some simple way to make the variable arr[] exist only for the function. Because if not I would have to use delete [] arr, which for some reason, whenever I use my program closes alone.

  • No, dude, you only need to use 'delete' if you instantiated the array with 'new'. The pointer is only used to reference the array in main without having to specify the amount of items. And not understood, here compiled normal. Your program displays nothing, just copies the common array elements to a vector.

  • This time it worked. Other times, whenever I recreated the normal vector, it kept the size of the first one, but it doesn’t happen here. Thank you very much.

Browser other questions tagged

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