【问题标题】:most convenient way to represent a vector of vector references表示向量引用向量的最方便方法
【发布时间】:2016-10-16 23:01:05
【问题描述】:

我有以下代码:

#include <iostream>
#include <vector>


using namespace std;

using float_vec = vector<float>;

float foo( vector<float_vec*> vec )
{
  // ...

  return (*vec[0])[0] = 1;
}


int main()
{
  std::vector<float> i_1(1,0);
  // ...
  std::vector<float> i_n(1,0);

  std::cout << i_1[ 0 ] << std::endl;

  foo( {&i_1, /* ..., */ &i_n} );

  std::cout << i_1[ 0 ] << std::endl;

  return 0;
}

正如您在上面看到的,我将浮点向量的向量传递给函数 foo,在这里,foo 对其输入有副作用。为此,我使用了一个指针向量;不幸的是,这使代码有点不可读->“(*vec [0])[0]”和“&i_1”,...,“&i_n”。有没有更优雅的方式来表示 C++ 中的指针向量?

我尝试如下使用 std::refrence_wrappers

#include <iostream>
#include <vector>


using namespace std;

using float_vec = std::reference_wrapper< vector<float> >;

float foo( vector<float_vec> vec )
{
  // ...

  return vec[0].get()[0] = 1;
}


int main()
{
  std::vector<float> i_1(1,0);
  // ...
  std::vector<float> i_n(1,0);

  std::cout << i_1[ 0 ] << std::endl;

  foo( {i_1, /* ..., */ i_n} );

  std::cout << i_1[ 0 ] << std::endl;

  return 0;
}

然而,这里的“get()”很烦人。

有没有人建议如何在 C++ 中表示“指针/引用向量”?

非常感谢。

【问题讨论】:

    标签: c++ reference stdvector


    【解决方案1】:

    如果您只想修改传递给函数的向量,则不需要指针。只需通过引用传递向量即可。

    #include <iostream>
    #include <vector>
    
    
    using namespace std;
    
    using float_vec = vector<float>;
    
    float foo( vector<float_vec>& vec )
    {
      // anything you do to vec here will change the vector you pass to the function
    
      return 1;
    }
    

    【讨论】:

    • 谢谢。您能否提供一个代码示例来演示如何将向量“i_1”、...、“i_n”(我的示例)插入(您的示例的向量)“float_vec”?
    • @abraham_hilbert 现在不行。但是,这很简单。只需使用您的对象(向量)作为参数调用它,然后您在该函数中所做的任何修改都将在原始向量中完成。
    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2013-08-11
    • 2017-04-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多