使用 std::vector 的 c++ 矩阵初始化

标签 c++ matrix c++14

<分区>

我正在尝试初始化一个矩阵,该矩阵实现为 double vector 的 vector 。即,

std::vector<std::vector<double>> A {std::vector<double> {}}; 
std::vector<std::vector<double>>::iterator it = A.begin();

我的想法是使用一个指向每个“行”的指针,通过这个指针访问“push_back”来填充我的行。要创建新行,我只需使用:

A.push_back(std::vector<double> {});

然后让我的指针简单地指向下一行:

it++;

然后填写我的下一行。 代码符合要求(我使用的是 C++14 标准)。但是当我运行它时,我得到了这个:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted (core dumped)

请考虑以下代码:

#include <iostream>
#include <vector>

void print(std::vector<std::vector<double>> matrix)
{
  typedef std::vector<std::vector<double>> row;
  typedef std::vector<double> col;
  for(row::iterator it = matrix.begin();it!=matrix.end();it++)
  {
    for(col::iterator ti = it->begin();ti!=it->end();ti++)
    {
      std::cout << *ti << ' ';
    }
    std::cout  << '\n';
  }
}

int main()
{
  std::vector<std::vector<double>> A {std::vector<double> {}};
  std::vector<std::vector<double>>::iterator it = A.begin();
  it->push_back(1);
  it->push_back(2);
  it->push_back(3);
  A.push_back(std::vector<double> {});
  it++;
  it->push_back(4);
  it->push_back(5);
  it->push_back(6);
  print(A);
  return 0;
}

(您可能理所当然地认为打印函数在编译或运行期间按预期工作而没有错误)。

任何输入都会有所帮助。 干杯

最佳答案

你的 vector<>调用 push_back() 可能会使迭代器无效.

A.push_back(std::vector<double> {});
//it may be invalid at this point because of new allocation in the vector
it++;

当您调用 push_back() 时, vector可能必须重新分配内存以容纳新数据。这将导致之前的迭代器不再指向内存中的正确位置,进一步使用它们将导致未定义的行为。

如果您调用 A.begin()push_back()之后为了重新分配您的迭代器然后进行增量,然后代码按我的预期工作。如:

A.push_back(std::vector<double> {});
it = A.begin();
it++;

编辑

如果您想部分避免将迭代器重新分配到开头,您可以使用:

it++;
it = A.insert(it,std::vector<double>{});

这将添加一个新的 vector<double>就在it之前指向(在本例中,就在当前 vector 结束之前)。这将返回存储在 it 中的迭代器。这将指向 vector您刚刚插入,因此您可以按原样使用代码的结果。

关于使用 std::vector 的 c++ 矩阵初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257630/

相关文章:

javascript - 给定 rotateX、rotateY 和 rotateZ,如何计算 matrix3d?

javascript - 如何优化二维矩阵读取速度?

c++ - 为什么在 CentOS 7 上选择了错误的 GCC 7.2 libstdc++ ABI?

C++:int *x[5] 和 int (*x)[5] 有什么区别?

c++ - 为什么 Crypto++ 和 Ruby 生成的 SHA-1 哈希略有不同?

java - 使用 ejml 进行 LU 分解

C++ 将 std::tuple<A, A, A...> 转换为 std::vector 或 std::deque

c++ - 传递线程构造函数的引用以将其绑定(bind)到函数失败?

c++ - 如何使用 QLineEdit 将 QString 添加到 QListView

C++ 数组和指针