表示向量引用向量的最方便的方法
most convenient way to represent a vector of vector references
我有以下代码:
#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()" 很烦人。
有没有人对 "vector of pointers/references" 应该如何在 C++ 中表示提出建议?
非常感谢。
如果您只想修改传递给函数的向量,则不需要指针。只需通过引用传递矢量。
#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;
}
我有以下代码:
#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()" 很烦人。
有没有人对 "vector of pointers/references" 应该如何在 C++ 中表示提出建议?
非常感谢。
如果您只想修改传递给函数的向量,则不需要指针。只需通过引用传递矢量。
#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;
}