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

时间:2013-11-13 17:54:38

标签: c++ vector

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

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’。复制多维向量的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

同意 - 适合我(g ++ 4.6.1 on linux)

#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

答案 1 :(得分:0)

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

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