Passing a string vector to a function

You need to move vector<string> from one function to another function and work with it there.

I was able to do this with data like int, but it doesn't work with string.

std::string fun(std::string);

int main()
{
    std::vector<std::string> arr(3);
    fun(arr);
    std::cout << "Сумма: " << fun(arr);
    system("pause");
}

std::string fun(std::string arr) {
        for (int i = 0; i < 3; i++) {
            std::cout << "[" << i + 1 << "] ";
            std::cin >> arr[i];
        }
    return arr;
}

P.S. I know that I have an error in my code, I just want to understand the essence of how to pass the contents of a vector to a function.

Author: αλεχολυτ, 2016-10-02

3 answers

It is best to transmit by reference. Imagine what happens when passing by value - each row is copied, and a heap of memory is allocated (a very slow operation)... And then - whatever you do with this vector of strings in the function-it will not affect the original. Sometimes it's not the right thing to do. So I recommend

std::string fun(std::vector<std::string>& arr)

If you need to somehow change this vector and strings, or

std::string fun(const std::vector<std::string>& arr);

If arr, if you don't need to change it.

In your particular case - the first call in general completely loses everything entered, the second returns the same vector - i.e. the next copy of everything when returning! (I'm not saying yet that std::cout << "Сумма: " << fun(arr); doesn't compile due to the lack of an output operator for the string vector). After that, you have a vector returned by the function fun(arr), and a vector arr that has nothing to do with this returned vector .

In short, in this code of yours, passing the argument only as a non-const reference.

 4
Author: Harry, 2016-10-02 05:14:10

Here is an example with a link transfer. In my opinion, the return of the string for this function is not needed.

#include <iostream>
#include <string>
#include <vector>

using namespace std;

ostream& operator<<(ostream &os, const vector<string> &v)
{
    for(auto const& s: v)  os << s << " ";
    return os;
}

void fun(vector<string>& arr)
{
    for (int i = 0; i < 3; i++) {
        cout << "[" << i + 1 << "] ";
        cin >> arr[i];
    }
}

int main()
{
    vector<string> arr(3);
    fun(arr);
    cout << "result=" << arr << endl;
    return 0;
}

It will give you:

[1] 123
[2] 456
[3] 789
result=123 456 789
 3
Author: 0xdb, 2016-10-02 12:48:44

std::string fun(std::string arr) //функция принимает строку

std::string fun(std::vector<std::string> arr) //функция принимает вектор строк

 -2
Author: strangeqargo, 2016-10-02 01:27:57