【发布时间】:2021-10-27 00:32:51
【问题描述】:
我正在尝试使用 uint8_t 值创建一个 10 x 10 的网格。使用一些坐标我试图在这些索引上放置 255 个值。当我在这些坐标处替换 255 时,它可以正常工作,但是当我尝试打印出这些索引处的值时,它似乎不是我想要的值。
float grid_width = 10;
float grid_height = 10;
float grid_resolution = 0.05;
float rows = grid_width/grid_resolution;
float cols = grid_height/grid_resolution;
std::vector<std::vector<float>> landmarks = {{2,2},{8,8},{2,8},{8,2},{3,2},{3.5,2.1},{4.0,3.5},{4.5,2.0},{5.0,3.0}};
std::vector<std::vector<uint8_t>> grid(rows, std::vector<uint8_t>(cols, 0));
for(auto i: landmarks)
{
for(auto m = i[0]-(grid_resolution*2) ; m <= i[0] +(grid_resolution*2) ; m=m+grid_resolution )
{
for(auto n = i[1]-(grid_resolution*2); n <= i[1]+(grid_resolution*2); n=n+grid_resolution)
{
int m_co = m/grid_resolution;
int n_co = n/grid_resolution;
grid[m_co][n_co] = 255;
cout<<"m_co: "<< m_co <<" n_co:" << n_co <<endl;
cout<<"grid[m_co][n_co]: "<< unsigned(grid[m_co][n_co]) <<endl; //check the printout over here for index values of 18,22 you will see 255 but when you try it outside the for loops those values are rest to 0
}
}
}
// for(auto m: grid)
// {
// for(auto n: m)
// {
// cout<<unsigned(n)<<" ";
// }
// cout<<endl;
// }
cout<<unsigned(grid[18][18])<<endl; //expected 255 got 255
cout<<unsigned(grid[18][22])<<endl; //expected 255 got 0
cout<<unsigned(grid[22][22])<<endl; //expected 255 got 0
cout<<unsigned(grid[22][18])<<endl; //expected 255 got 0
cout<<unsigned(grid[17][17])<<endl; //expected 255 got 0
cout<<unsigned(grid[20][18])<<endl; //expected 255 got 255
所以我正在使用地标向量获取索引,并尝试将网格向量中的 0 替换为地标索引上的 255,但我也想在该索引周围的索引上替换 0。 如果 2,2 是我的坐标,我想将 1,1 和 1,2 和 1,3 和 2,1 和 2,2,以及 2,3 和 3,1 和 3,2 和 3,3 替换为 255但我没有得到 1,3 和 2,3 和 3,3 255 我得到 0 这只是我想要达到的一个例子
【问题讨论】:
-
为什么要使用浮点变量来分配向量的大小?
-
你能把它变成minimal reproducible example 并解释你看到的不受欢迎的行为,也许有一个正确和错误的例子吗?考虑转换为
unsigned int而不仅仅是unsigned。 -
我在上面用 cmets 编辑了我收到的预期内容。
-
你也可以自己模拟。
-
@QuickSilver 我们可以,如果您创建了一个可以复制/粘贴和编译/运行的minimal reproducible example。您是否使用过调试器来单步执行和验证事情?如果你要打印出来,你应该直接打印
m_co和n_co而不要再做数学。
标签: c++