C++中返回值为vector的函数
作者:野牛程序员:2023-07-11 08:15:08 C++阅读 3832
在C++中,可以通过以下方式定义和实现返回值为向量的函数:
#include <vector>
std::vector<int> createVector()
{
std::vector<int> myVector = {1, 2, 3, 4, 5};
return myVector;
}
int main()
{
std::vector<int> result = createVector();
// 使用返回的向量进行其他操作
return 0;
}在上述示例中,createVector 函数返回一个 std::vector<int> 类型的向量。在函数内部,定义了一个名为 myVector 的向量,并将其初始化为 {1, 2, 3, 4, 5}。然后,使用 return 语句将该向量返回给调用方。
在 main 函数中,声明了一个名为 result 的向量,它接收 createVector 函数的返回值。可以在这里使用 result 向量进行其他操作,如遍历、修改等。
请注意,C++ 中的向量是动态数组,因此可以在函数内部创建并返回。此外,可以根据需要将向量的类型更改为其他数据类型,而不仅仅局限于 int。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:arduino控制伺服驱动器
- 下一篇:C++中vector和数组的区别
