[英]how to assign values into a 2D vector like a 2D array
Is there anyway to do it? 反正有做吗? Currently I use like this:
目前,我这样使用:
for( i=0;i<PU_number;i++)
{
for( j=0;j<=time_slots;j++)
myMatrix.tempVec.push_back(0.0);
myMatrix.value.push_back(myMatrix.tempVec);
myMatrix.tempVec.clear();
}
However, it is not useful for me. 但是,这对我没有用。 Sometimes I need to change a particular adress in this vector.
有时我需要更改此向量中的特定地址。 like
myMatrix.tempVec[1][4]
. 就像
myMatrix.tempVec[1][4]
。 When I do it like this: 当我这样做时:
myMatrix.value[i][j]=value;
it corrupts memory, I get SIGABRT
, SIGSESV
and lots of thing like them. 它破坏了内存,我得到了
SIGABRT
, SIGSESV
以及SIGSESV
许多东西。 Also valgrind gets crazy when I do that. 当我这样做时,valgrind也会发疯。 But I need an appropriate way to do it.
但是我需要一种适当的方法来做到这一点。
EDIT: I did what you guys said: 编辑:我做了你们说的:
myMatrix.value.resize(PU_number);
for( i=0;i<PU_number;i++)
myMatrix.value[i].resize(time_slots);
and then: 接着:
for( i=0;i<PU_number;i++)
{
for( j=0;j<time_slots;j++)
{
for( k=0;k<number_of_packets;k++)
{
double r=((double) rand() / (RAND_MAX));
for( x=myMatrix.mat[i][k];x<=myMatrix.mat[i][k]+myMatrix.len[i][k];x++)
myMatrix.value[i][x]=r;
}
}
}
And I got "Invalid write of size 8" again in valgrind. 而且我在valgrind中再次得到“大小为8的无效写入”。
There's the std::vector::resize()
function, that can be used to set the dimensions of your matrix properly, before you access any values by indexing. 有
std::vector::resize()
函数,在通过索引访问任何值之前,该函数可用于正确设置矩阵的尺寸。
Here's a small sample 这是一个小样本
myMatrix.resize(PU_number);
for( i=0;i<PU_number;i++) {
myMatrix[i].resize(time_slots);
for( j=0;j<=time_slots;j++)
myMatrix[i][j] = 0.0;
}
You can use a std::vector > like here : 您可以在此处使用std :: vector>:
#include <vector>
#include <iostream>
int main()
{
std::vector<std::vector<int> > vec;
vec.resize(10);
for (unsigned int i = 0 ; i < vec.size(); ++i)
{
vec[i].resize(10);
}
vec[1][4] = 3;
vec[1].push_back(5)
std::cout << "vec[1][4] = " << vec[1][4] << std::endl;
std::cout << "vec[1][10] = " << vec[1][10] << std::endl;
return (0);
}
I create a vector of size 10 which contain others vector of size 10; 我创建了一个大小为10的向量,其中包含其他大小为10的向量; note that you have to use resize to get the size with a std::vector > but after if you want to add a size you can use vec[i].push_back(5);
请注意,您必须使用resize来获取带有std :: vector>的大小,但是如果要添加大小,则可以使用vec [i] .push_back(5);。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.