【问题标题】:Using functions on vectors in C++在 C++ 中对向量使用函数
【发布时间】:2015-04-30 11:25:21
【问题描述】:

我正在尝试通过使用函数来更改向量元素内的数据。碰巧元素在函数内部发生了变化。如何将更改保留在函数之外?我必须使用指针吗?

代码:

#include <iostream>
#include <vector>

using namespace std;

void populate( int size_, vector<int> pop)
{
    //Set the vector's size and populate the vector
    pop.resize(size_);
    for(int i = 0; i<3 ; i++)
    {
        pop[i] = i;
    }
}

int main()
{
    vector<int> vec;
    int size = 3;
    populate(size, vec);

    for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << *it << endl;
    }   
}

cout 的输出应该是:0 1 2 但它是空的。

【问题讨论】:

  • 你的函数看起来应该是构建并返回一个向量,而不是把一个向量作为参数。
  • 最近我试图解释一些与朋友有关的事情,我编造了this example。当你运行它时,你可以看到你传递的对象是如何被复制到一个局部变量中的,并且一旦函数返回,这个局部变量就会被删除。

标签: c++ function pointers vector


【解决方案1】:

您正在尝试使用标准库设施轻松且惯用地完成:

int size = 3;
std::vector<int> vec(size);
std::iota(vec.begin(), vec.end(), 0);  // include algorithm for this

【讨论】:

  • 我会 +1 以促进 std 算法的使用(因为不久前我很难习惯它)但我认为实际的问题是他不知道引用传递的概念
  • @tobi303 对,但其他用户负责解释。
【解决方案2】:

你需要通过引用来获取向量

void populate( int size_, vector<int>& pop)

否则,您将传入向量的副本,填充它,然后返回,但原始向量未修改。

或者正如@juanchopanza 推荐的那样,因为这个函数的唯一目的是为你制作这个向量,它可能是

vector<int> populate( int size_ )
{
    vector<int> temp(size_);
    for(int i = 0; i < size_ ; i++)
    {
        pop[i] = i;
    }
    return temp;
}

然后

int main()
{
    int size = 3;
    vector<int> vec = populate(size, vec);
    for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
    {
        cout << *it << endl;
    }   
}

【讨论】:

  • 感谢您的帮助。我真的需要知道如何通过引用传递向量的值。
【解决方案3】:

您正在将向量发送到populate按值。这会创建一个副本,因此popvec 的副本。您所做的更改只会影响pop

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2011-10-15
    • 1970-01-01
    • 2016-04-26
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多