This is the way that came to mind, but the first vector (iv) is for some reason empty.

#include <string> #include <vector> typedef std::vector<std::string> stringVector; typedef std::vector<int> intVector; intVector & StringVectorToIntVector(const stringVector strv){ intVector iv; for (int i = 0; i < strv.size(); i++) iv.push_back(atoi(strv[i].c_str())); return iv; } #include <iostream> using namespace std; int main(){ stringVector v; intVector iv; v.push_back("10"); v.push_back("15"); v.push_back("20"); iv = StringVectorToIntVector(v); return 0; } 
  • and how else to return a vector from a function, through a parameter? - perfect
  • I tried the test function wrote. She gave me 10 int & func () {int a = 10; return a; } - perfect
  • @VladD thanks. All normal documentation is in English, and I am German. Therefore, I master all languages ​​by the method of experiments. Or Russian manuals. I don't know much about stack and data storage. - perfect

1 answer 1

You have created a vector on the stack, and return a link to it. So it is impossible, the object will die after the end of the function.

This is compiled, but incorrect, and is according to the standard undefined behavior. Something random happens. (With C ++, you should not rely on experiment, only on documentation.)

Return by value, or pass a vector reference to a function.

In general, you should use std::transform like this or even like this .

Update

@perfect : Well, you have to figure out about the stack if you are programming in a low-level language like C ++. In short: local variables of a function die when the function ends. Only the return value is copied out. The link does not prolong the life of variables (except for a few cases, as usual in C ++). So the returned link points to the "corpse".

  • Updated the answer - VladD
  • Thank you very much, good man. Memorized. - perfect