Cpp function return vector

How to return a vector in C++

In this tutorial, we will discuss how to return a vector in C++. There are 2 ways to return a vector in C++ i.e. by value and by reference. We will see which one is more efficient and why.

Return by Value

This is the preferred method in C++ 11, because we have an optimization in C++ 11 Compiler, it’s called Name Return Value Optimization (NRVO). In this method, the compiler optimizes so that function doesn’t get constructed twice. In this method an object is not copied for returning a vector, it will point the pointer to the new vector which will be returned not causing extra time and space.

Code

#include using namespace std; vector divVecByVal(vector &v) < vectorres(v.size()); for(int i=0; i int main() < vectorv = ; cout << "Original Vector: "; for(auto a:v) cout << a << " "; cout << endl; vectorv2 = divVecByVal(v); cout

Output

Original Vector: 10 20 30 40 50 Vector after calling function: 1 2 3 4 5

Return by Reference

In this method, we just return the reference of the vector. And one more thing we must remember is to not return the reference of local variable declared in the function, if one tries to do then he will have a dangling reference (a reference to a deleted object).

Читайте также:  Наточите свой карандаш изучаем java ответы

Code

#include using namespace std; vector &divVecByRef(vector &v) < for(int i=0; iint main() < vectorv = ; cout << "Original Vector: "; for(auto a:v) cout << a << " "; cout << endl; vectorv2 = divVecByRef(v); cout

Output

Original Vector: 10 20 30 40 50 Vector after calling function: 1 2 3 4 5

Note: If you try to return the local variable, you will end up with the below error, so never return the local variable.

Output

warning: reference to stack memory associated with local variable 'res' returned [-Wreturn-stack-address] zsh: segmentation fault ./a.out

Источник

Function Returning a Vector in C++

Can a function return a vector in C++? The reason why this question is asked, is because a function cannot return an array (that is similar to a vector) in C++. The answer is simple. Yes, a function can return a vector in C++ and in different ways. This article explains the different ways in which a C++ function can return a vector.

In order to code a vector in C++, the vector library has to be included in the program. The vector library has the vector class from which vector objects can be instantiated (created).

The program in which all the code samples of this article are, begins with:

A vector of strings is used.

Article Content

Returning Vector by Normal Vector Name

Let the vector of interest be:

The vector is a list of items in a small grocery store. The name, store of this vector, is to be sent as an argument to a function, whose parameter is a vector, but with the name, vtr. The function of interest can be:

Notice the return type of the function definition. The name of the vector is store. This is the argument for the function call. The parameter for the function corresponding to the vector is:

Note that the argument for the function and the parameter name are different (they can still be the same). As soon as the function starts executing, the following statement is made:

This statement is equivalent to the following two statements:

And so, vtr is a copy of the vector, store. At this point, there are two vectors with the same content in memory for the program. An appropriate C++ main function for the code can be:

Notice that the word store, is the argument of the function call. When the function is called, two copies of the same vector content occur in memory. The function (call) returns a vector, which is received by another vector, v. By the time the program finishes, there are three vectors of the same copy in memory. These three copies of the same content can be reduced to one copy by using a reference vector, or pointer vector.

Here is the full code for this program:

vector < string >store = { «bread» , «meat» , «rice» , «Tomato sauce» , «Cheese» } ;

vector < string >fn ( vector < string >vtr ) {
return vtr ;
}

The output for the above program is:

Returning a Vector Literal

Today (in 2022), a vector literal is the same as an array literal. This literal is called an initializer_list, today in C++. So, returning a vector literal by a function, is the same as returning an initializer_list. Let the initlializer_list be:

Let the function definition to return the initializer_list be,

return { «bread» , «meat» , «rice» , «tomato sauce» , «Cheese» } ;
}

The initializer_list is composed on the spot in the return statement, and returned. The function definition has no parameter, but has the same return type as its counterpart in the previous section. Let the main C++ function be:

The function call, this time, has no argument, but the return value is received by the same vector and type of the previous section.

By the time the program is completing, would there be two copies of the same vector in memory? No. There would be only one copy, which is v. The initializer_list is a kind of expression, called a rvalue. When this kind of expression is no longer needed in memory, can it be erased by C++ in order to have more memory space? It is not important whether it remains in memory after it has been used while the program continues to run. It would be erased if its space is needed. The program output is:

The full code for the program is here:

return { «bread» , «meat» , «rice» , «tomato sauce» , «Cheese» } ;
}

Источник

Return a Vector From a Function in C++

Return a Vector From a Function in C++

  1. Use the vector func() Notation to Return Vector From a Function
  2. Use the vector &func() Notation to Return Vector From a Function

This article will introduce how to return a vector from a function efficiently in C++.

Use the vector func() Notation to Return Vector From a Function

The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics. It means that returning a vector does not copy the object, thus avoiding wasting extra speed/space. Under the hood, it points the pointer to the returned vector object, thus providing faster program execution time than copying the whole structure or class would have taken.

#include #include #include  using std::cout; using std::endl; using std::vector;  vectorint> multiplyByFour(vectorint> &arr)   vectorint> mult;  mult.reserve(arr.size());   for (const auto &i : arr)   mult.push_back(i * 4);  >  return mult; >  int main()   vectorint> arr = 1,2,3,4,5,6,7,8,9,10>;  vectorint> arrby4;   arrby4 = multiplyByFour(arr);   cout  <"arr - | ";  copy(arr.begin(), arr.end(),  std::ostream_iteratorint>(cout," | "));  cout    cout  <"arrby4 - | ";  copy(arrby4.begin(), arrby4.end(),  std::ostream_iteratorint>(cout," | "));  cout     return EXIT_SUCCESS; > 
arr - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | arrby4 - | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 | 

Use the vector &func() Notation to Return Vector From a Function

This method uses the return by reference notation, which is best suited for returning large structs and classes. Note that do not return the reference of the local variable declared in the function itself because it leads to a dangling reference. In the following example, we pass the arr vector by reference and return it also as a reference.

#include #include #include  using std::cout; using std::endl; using std::vector;  vectorint> &multiplyByFive(vectorint> &arr)   for (auto &i : arr)   i *= 5;  >  return arr; >  int main()   vectorint> arr = 1,2,3,4,5,6,7,8,9,10>;  vectorint> arrby5;   cout  <"arr - | ";  copy(arr.begin(), arr.end(),  std::ostream_iteratorint>(cout," | "));  cout     arrby5 = multiplyByFive(arr);   cout  <"arrby5 - | ";  copy(arrby5.begin(), arrby5.end(),  std::ostream_iteratorint>(cout," | "));  cout     return EXIT_SUCCESS; > 
arr - | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | arrby5 - | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article — C++ Vector

Источник

Функция, возвращающая вектор в C++

bestprogrammer.ru

Двумерный вектор в C++

Программирование и разработка

Может ли функция возвращать вектор в С++? Причина, по которой задается этот вопрос, заключается в том, что функция не может возвращать массив (аналогичный вектору) в C++. Ответ прост. Да, функция может возвращать вектор в C++ и по-разному. В этой статье объясняются различные способы, которыми функция C++ может возвращать вектор.

Чтобы закодировать вектор на C++, в программу должна быть включена библиотека векторов. В векторной библиотеке есть векторный класс, из которого можно инстанцировать (создавать) векторные объекты.

Программа, в которой находятся все примеры кода этой статьи, начинается с:

#include

#include

#include

using namespace std ;

Используется вектор строк.

Возврат вектора по нормальному имени вектора

Пусть интересующий вектор:

Вектор представляет собой список товаров в небольшом продуктовом магазине. Имя store этого вектора должно быть передано в качестве аргумента функции, параметром которой является вектор, но с именем vtr. Функция интереса может быть:

Обратите внимание на возвращаемый тип определения функции. Имя вектора store. Это аргумент для вызова функции. Параметр функции, соответствующей вектору:

Обратите внимание, что аргумент функции и имя параметра отличаются (могут быть одинаковыми). Как только функция начинает выполняться, делается следующий оператор:

Это утверждение эквивалентно следующим двум утверждениям:

Итак, vtr — это копия вектора, store. На данный момент в памяти программы есть два вектора с одинаковым содержимым. Подходящей основной функцией C++ для кода может быть:

Обратите внимание, что хранилище слов является аргументом вызова функции. При вызове функции в памяти появляются две копии одного и того же векторного содержимого. Функция (вызов) возвращает вектор, который получен другим вектором v. К моменту завершения программы в памяти имеется три вектора одной копии. Эти три копии одного и того же контента могут быть уменьшены до одной копии с помощью вектора ссылки или вектора указателя. Вывод для вышеуказанной программы:

bread, meat, rice, tomato sauce, Cheese.

Возврат векторного литерала

Сегодня (в 2022 году) векторный литерал — это то же самое, что и литерал массива. Этот литерал называется initializer_list сегодня в C++. Таким образом, возврат функции векторного литерала аналогичен возврату списка initializer_list. Пусть initlializer_list будет:

Пусть определение функции для возврата initializer_list будет следующим:

Initializer_list составляется на месте в операторе return и возвращается. Определение функции не имеет параметров, но имеет тот же тип возвращаемого значения, что и его аналог в предыдущем разделе. Пусть основной функцией C++ будет:

Вызов функции на этот раз не имеет аргумента, но возвращаемое значение принимается тем же вектором и типом, что и в предыдущем разделе.

К моменту завершения программы будут ли в памяти две копии одного и того же вектора? Нет. Будет только одна копия — v. Initializer_list — это своего рода выражение, называемое rvalue. Когда такое выражение больше не требуется в памяти, может ли C++ стереть его, чтобы освободить место в памяти? Неважно, остается ли он в памяти после того, как был использован, пока программа продолжает работать. Он будет стерт, если его пространство необходимо. Вывод программы:

bread, meat, rice, tomato sauce, Cheese.

Возврат ссылки на вектор

Программа здесь будет делать то же, что и первая программа выше, но только с одной копией того же вектора. Однако у одного и того же вектора будет три разных имени. Пусть интересующий вектор:

Сигнатура определения функции и оператор вызова функции:

Источник

Оцените статью