簡體   English   中英

如何在C ++中比較兩個數組並返回不匹配的值

[英]How to compare two arrays and return non matching values in C++

我想解析兩個字符串向量,找到彼此匹配的字符串,以及不匹配的字符串。

我想要得到的例子:
輸入向量1看起來像:[string1,string2,string3]
輸入向量2看起來像:[string2,string3,string4]

理想輸出:
字符串1:不匹配
string2:匹配
string3:匹配
string4:不匹配

目前,我使用以下代碼:

vector<string> function(vector<string> sequences, vector<string> second_sequences){

 for(vector<string>::size_type i = 0; i != sequences.size(); i++) {
  for(vector<string>::size_type j = 0; j != second_sequences.size(); j++){
   if (sequences[i] == second_sequences[j]){
     cout << "Match: " << sequences[i];
    }else{
     cout << "No Match: " << sequences[i];
     cout << "No Match: " << second_sequences[j];
   }
  }
 }  
}

它對匹配的對象非常有用,但是會迭代很多遍,
不匹配的將被打印很多次。

我該如何改善?

最好的代碼是您不必編寫的代碼。

如果您使用(STL)映射容器,它將為您整理和存儲遇到的不同字符串的麻煩。

因此,讓容器為我們工作。

我建議快速編寫一個小的代碼。 您需要使用此語法來至少啟用編譯器的C ++ 2011選項(例如,在gcc上為-std = c ++ 11)。 在C ++ 11之前應該使用的語法更加冗長(但是應該從學者的角度了解)。

您只有一個循環。 這只是對您的提示(我的代碼沒有考慮到第二個向量string4中可能出現多次,但是我讓您根據自己的實際需要進行安排)

#include <iostream>
#include <vector>
#include <string>
#include <map>


using namespace std;


vector<string> v1 { "string1","string2","string3"};
vector<string> v2 { "string2","string3","string4"};

//ordered map will take care of "alphabetical" ordering
//The key are the strings
//the value is a counter ( or could be any object of your own
//containing more information )
map<string,int> my_map;

int main()
{
    cout << "Hello world!" << endl;

    //The first vector feeds the map before comparison with
    //The second vector
    for ( const auto & cstr_ref:v1)
        my_map[cstr_ref] = 0;

    //We will look into the second vector ( it could also be the third,
    //the fourth... )
    for ( const auto & cstr_ref:v2)
    {
        auto iterpair = my_map.equal_range(cstr_ref);

        if ( my_map.end() != iterpair.first )
        {
            //if the element already exist we increment the counter
            iterpair.first->second += 1;
        }
        else
        {
            //otherwise we put the string inside the map
            my_map[cstr_ref] = 0;
        }

    }

    for ( const auto & map_iter: my_map)
    {
        if ( 0 < map_iter.second )
        {
            cout  << "Match    :";
        }
        else
        {
            cout  << "No Match :" ;
        }

        cout << map_iter.first << endl;
    }


    return 0;
}

輸出:

No Match :string1
Match    :string2
Match    :string3
No Match :string4
std::sort(std::begin(v1), std::end(v1));
std::sort(std::begin(v2), std::end(v2));

std::vector<std::string> common_elements;
std::set_intersection(std::begin(v1), std::end(v1)
                    , std::begin(v2), std::end(v2)
                    , std::back_inserter(common_elements));

for(auto const& s : common_elements)
{
    std::cout<<s<<std::endl;
}

暫無
暫無

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

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