在2D数组中查找值

时间:2014-12-28 19:56:48

标签: c++ visual-c++

   0 1 2
- - - - -
0| 1 2 3
1| 4 5 6
2| 7 8 9

如何确定此二维数组中任何数字的坐标?

例如,如果我想知道数字9的坐标,它将是[2][2]

我怎么能通过C ++程序上的代码来做到这一点?

3 个答案:

答案 0 :(得分:2)

这是两种方法。第一个使用标准算法,第二个使用普通循环。

#include <iostream>
#include <algorithm>
#include <iterator>

int main() 
{
    const size_t N = 3;
    int a[N][N] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    int value = 9;

    auto it = std::find( reinterpret_cast<int *>( a ),
                         reinterpret_cast<int *>( a ) + N * N,
                         value );

    if ( it != reinterpret_cast<int *>( a ) + N * N )
    {
        size_t n = std::distance( reinterpret_cast<int *>( a ), 
                                  it );
        std::cout << "Row = " << n / N << ", Column = " << n % N << std::endl;
    }

    size_t row = 0;
    size_t col = 0;

    for ( ; row < N; row++ )
    {
        col = 0;
        while ( col < N && a[row][col] != value ) col++;
        if ( col != N ) break;
    }

    if ( row != N )
    {
        std::cout << "Row = " << row << ", Column = " << col << std::endl;
    }

    return 0;
}

输出

Row = 2, Column = 2
Row = 2, Column = 2

或者您可以通过以下方式编写函数

#include <iostream>
#include <utility>

const size_t N = 3;

std::pair<size_t, size_t> find_position( const int ( &a )[N][N], int value )
{
    size_t row = 0;
    size_t col = 0;

    for ( ; row < N; row++ )
    {
        col = 0;
        while ( col < N && a[row][col] != value ) col++;
        if ( col != N ) break;
    }

    return { row, col };
}

int main() 
{
    int a[N][N] =
    {
        { 1, 2, 3 },
        { 4, 5, 6 },
        { 7, 8, 9 }
    };

    int value = 9;

    auto position = find_position( a, value );

    if ( position.first != N )
    {
        std::cout << "Row = " << position.first 
                  << ", Column = " << position.second << std::endl;
    }

    return 0;
}

输出

Row = 2, Column = 2

答案 1 :(得分:1)

基本上你需要搜索数组来检查每个单元格的内容。

   int a[3][3]={{1,2,3},{4,5,6},{7,8,9});
   for(int x=0;x<3;++x)
        for(int y=0;y<3;++y)
            if(a[x][y] == 9)
                 cout << "9 found at ["<<x<<"]["<<y<<"]\n";

答案 2 :(得分:1)

如果你可以使用std::vector<std::vector<int>>,那就是:

std::vector<std::vector<int>> vec = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < vec.size(); i++)
{
    auto it = std::find(vec[i].begin(), vec[i].end(), 9);
    if (it != vec[i].end())
    {
        std::cout << "Number 9 found at vec[" << i << "][" << std::distance(vec[i].begin(), it) << "].";
    }
}