2014-12-28 80 views
-2
0 1 2 
- - - - - 
0| 1 2 3 
1| 4 5 6 
2| 7 8 9 

如何确定此二维数组中的任意数字的坐标?在2D阵列中查找值

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

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

+0

我不知道我米看,什么二维数组? –

+0

@VladfromMoscow现在是。删除我以前的评论,因为它与问题的新主体无关。 –

回答

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"; 
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) << "]."; 
    } 
} 
1

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

#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