将元素插入2D向量 [英] Inserting elements into 2D vector

查看:196
本文介绍了将元素插入2D向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我创建一个实现邻接表的类。目前在我的类定义中我初始化了两个向量:

  vector< vector< int> adjList; 
vector< int>邻居

并且我声明了两个函数,我计划使用它们:

  bool constructAdjList(); 
bool insertIntoAdjList(int,int);

很难将我的头围绕在2D向量。我理解它本质上是一个向量的向量,但我很困惑如何插入一个新的值到一个子向量。例如,我可以通过以下循环在createAdjList中创建一个空的列表:

  for(int i = 0; i  neighbors.push_back(0); 
adjList.push_back(neighbors);
neighbor.clear();
}

但是我怎么说,push_back值5到adjList ,这将在我的insertIntoAdjList函数中表示为

  insertIntoAdjList(4,5); 



我知道我可以通过说adjList [4] [1]访问2D向量中的特定值。 ,但我该如何推一个呢?



谢谢!

解决方案

要推动作为另一个向量的元素的向量,只需这样做

  adjList [x] .push_back ); 


so I'm creating a class that implements an adjacency list. Currently in my class definition I initialized two vectors:

vector<vector<int>> adjList;
vector<int> neighbors;

and I declared two functions that I plan to use to make it:

bool constructAdjList();
bool insertIntoAdjList(int, int);

It's getting difficult wrapping my head around 2D vectors. I understand that it is essentially a vector of vectors, but I'm confused about how to insert a new value into one of the "subvectors". For example, I am able to create an adjacency list in createAdjList that is empty with the following loop:

for (int i = 0; i < numOfValues; i++){
    neighbors.push_back(0);
    adjList.push_back(neighbors);
    neighbors.clear();
}

But how can I say, push_back the value 5 to the 4th vector in adjList, which would be represented in my insertIntoAdjList function as

insertIntoAdjList(4, 5);

I know I can access a specific value in a 2D vector by saying adjList[4][1], but how can I push one onto it?

Thanks!

解决方案

To push on the vector that is an element of another vector, you simply do this

adjList[x].push_back();

这篇关于将元素插入2D向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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