C ++: Vector in a function

1

I'm doing a project where I use many vector-type vectors. But 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 did I do wrong?

Note: I am a beginner, so if you have an easier method, please tell me.

    
asked by anonymous 24.04.2017 / 03:47

1 answer

1

First of all, you can not 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 your function:

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

Or you will have to use std :: array.

You can not pass an array in this way, you need to specify its size in your 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;
}
    
24.04.2017 / 04:40