簡體   English   中英

檢查2D數組中是否存在元素C ++

[英]Check to see if an element exists in a 2D array C++

我試圖檢查字符元素是否在我的輸出數組中。 數組獲取字符串中字符的頻率。 所以我想說如果當前字符在數組中,然后將1添加到頻率,否則將字符添加到頻率為1的數組。另外,我希望該表按順序顯示前5個最高頻率。

表的EX應該是這樣的:

  character: a b c d
  freqency:  1 2 3 4


string input = GetInputString(inputFileName);
char ** output; 

for (int i = 0; i < sizeof(output); i++)
{
      if (input [count] == output[i][]) // this is where my issue is
      {

            //.......
      }

}

您可以使用std::vector<std::pair<char,int>>來存儲字符及其計數。

string input("1212345678999");

std::vector<std::pair<char, int>> sp;
for(auto c : input)
{
  auto it = std::find_if(sp.begin(), sp.end(), 
                         [=](const pair<int, char>& p) {return p.first == c; });
  if (it != sp.end())
  {
    it->second++;  // if char is found, increase count
  }
  else
  {
    sp.push_back(std::make_pair(c, 1)); // new char, add an entry and initialize count to 1
  }
}

要按順序顯示排名前5位的最高頻率,您可以按count順序進行適當排序:

std::sort(sp.begin(), sp.end(), 
                      [](const pair<int, char>& p1, const pair<int, char>& p2)
                      {
                         return p1.second > p2.second; 
                      });

假設您的示例表示“ a”為0,0,“ b”為0,2,1為1,0等,這意味着該字符始終位於第一行,您只需要遍歷每一個字符輸入0 [x]。

// you should declare your array as an array
char output[2][26] = {0}; // {0} initialises all elements;
// ... assign values to output.

// I assume there's a count loop here, that checks for the upper bounds of input.
// ...
// You have to determine how many columns there are somehow, 
// I just made a static array of 2,26
const int columnsize = 26; 
for (int i = 0; i < columnsize;   i++)
{
  if ( input[count] == output[0][i] )
  {
        // found the character
  }
}

這是為了使您的實施工作正常進行,但是有更好或更簡單的方法可以做到這一點。 例如,如果在編譯時數組大小不是固定的,則可以使用向量的向量。 或者,如果您只想跟蹤字符的出現,則可以使用stl字符映射到頻率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM