复制通过引用传递给函数的多维向量

copying a multidimensional vector passed by reference to a function

本文关键字:函数 向量 引用 复制      更新时间:2023-10-16

要复制通过引用传递给成员变量的向量,我们可以使用以下代码:

struct B
{
  std::vector<double> c;
  void cpyV(const std::vector<double> &v)
  {
    c = v;
    return;
  }
};

但是,要复制 2D 向量,类似的代码不起作用:

struct B
{
  std::vector<std::vector<double> > c;
  void cpyV(const std::vector<std::vector<double> > &v)
  {
    c = v;
    return;
  }
};

我收到错误error: no match for ‘operator=’ in ‘((B*)this)->B::c = v’.复制多维向量的正确方法是什么?

同意 - 对我有用(Linux 上的 g++ 4.6.1)

#include <stdlib.h>
#include <iostream>
#include <vector>
using namespace std;
struct B
{
  std::vector<std::vector<double> > c;
  void cpyV(const std::vector<std::vector<double> > &v)
  {
    c = v;
    return;
  }
} A;
int main(void)
{
 vector<vector<double> > a, b;
 vector<double> x;
 x.push_back(1.0);
 x.push_back(2.0);
 x.push_back(3.0);
 a.push_back(x);
 a.push_back(x);
 a.push_back(x);
 b = a;
 cout << "a:n";
 for(unsigned i=0; i<a.size(); i++)
    {
     for(unsigned j=0; j<a[i].size(); j++)
        cout << a[i][j] << "t";
     cout << "n";
    }
 cout << "nb:n";
 for(unsigned i=0; i<b.size(); i++)
    {
     for(unsigned j=0; j<b[i].size(); j++)
        cout << b[i][j] << "t";
     cout << "n";
    }
 A.cpyV(a);
 cout << "nA.c:n";
 for(unsigned i=0; i<A.c.size(); i++)
    {
     for(unsigned j=0; j<A.c[i].size(); j++)
        cout << A.c[i][j] << "t";
     cout << "n";
    }

 return 0;
}

生成以下内容:

a:
1       2       3
1       2       3
1       2       3
b:
1       2       3
1       2       3
1       2       3
A.c:
1       2       3
1       2       3
1       2       3

它看起来像编译器的库错误。您也可以尝试以下代码

c.assign( v.begin(), v.end() );