首页 > 解决方案 > uint8_t 值与向量有关的问题

问题描述

我正在尝试使用 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 这只是我想要达到的一个例子

标签: c++

解决方案


在您正在打印的循环中n/grid_resolution。打印22的时候,其实是21.99999809265,但是因为iostream的默认精度是6,所以四舍五入到22。另一方面,赋值给的时候int,又舍入到21,所以其实是把255存入了grid[18][21]


推荐阅读