C ++复制多维向量 [英] C++ copying multidimensional vector

查看:119
本文介绍了C ++复制多维向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在复制多维矢量时遇到问题,我已经尝试了很多事情,但这是最后一件事:

I'm having problems copying a multidimensional vector, I've tried many things but this is the last one:

vector < vector < int > > a;
vector < vector < int > > b;
a.resize(10);
b.resize(10);
a[0][0] = 123;
copy( a.begin(), a.end(), back_inserter(b) );
cout << b[0][0];

我正在尝试做一个递归循环,计算10步之内网格中所有可能的路线。我正在尝试创建一个名为 current_path 的向量,当 current_path 具有时,该向量将保存每次递归的当前路径。 10个动作,它将数据从 current_path 复制到 all_paths

I'm trying to do a recursive loop that counts all possible routes in a grid within 10 moves. I'm trying to create a vector called current_path which would hold the current path for each recursion, when the current_path has 10 moves, It will copy the data from current_path to all_paths.

网格如下:

0  1  2 3
4  5  6 7
8  9  10 11
12 13 14 15

您只能移动到触摸的正方形因此从0开始,您可以移至1、4和5。从1至3、4、5、6等。

You can only move to a square you touch so from 0 you can move to 1, 4 and 5. And from 1 to 3, 4, 5, 6 etc.

主要思想是复制 current_path 到下一个函数调用(递归),因此它将保持 curren_path 到该点,直到完成为止( 10个步骤)。从 current_path 复制到 all_paths 后,我想我必须删除 current_path

The main idea is to copy the current_path to the next function call (recursive) so it would hold the curren_path up to that point, doing that until it's full (10 steps). After it's copied from current_path to all_paths I suppose I have to delete the current_path?

我知道如何有效地计算所有步骤,但是在复制 current_path 时遇到了麻烦适当地,当我走10步时如何将 current_path 添加到 all_paths

I know how to efficiently calculate all steps but I'm having trouble copying the current_path and propably and how do I add the current_path to all_paths when I'm at 10 steps?

推荐答案

您的代码有一些问题。在第4行的末尾,您有两个向量,每个向量包含10个空向量。您可以这样看待它:

There are a few problems with your code. By the end of line 4, you have two vectors that each contain 10 empty vectors. You could visualize it like this:

a = {{}, {}, {}, {}, {}, {}, {}, {}, {}, {}}
b = {{}, {}, {}, {}, {}, {}, {}, {}, {}, {}}

那些内部向量仍然没有任何元素,因此当您尝试设置时a [0] [0] 123 ,您正在访问的元素不存在,从而调用了未定义的行为。

Those inner vectors still do not have any elements so when you try and set a[0][0] to 123, you're accessing an element that doesn't exist, invoking undefined behaviour.

如果可行,使用 std :: copy 只会复制中的每个向量a 并将其推到 b 的后面。由于 b 已经具有10个元素,因此现在将具有20个元素。

If that had worked, your use of std::copy would simply copy each of the vectors from a and pushed it to the back of b. Since b already has 10 elements, it would now have 20 elements.

然后尝试输出 b [0] [0] 并不像 a [0] [0] 一样不存在

Then you try to output b[0][0] which doesn't exist just as much as a[0][0] didn't either.

这里的解决方案是简单地使用 std :: vector

The solution here is to simply use the copy assignment operator defined by std::vector:

vector<vector<int>> a = {{1, 2, 3}, {4, 5}};
vector<vector<int>> b;
b = a;

这篇关于C ++复制多维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆