2014-09-20 195 views
1

我想解析兩個字符串向量並找出匹配的字符串和不匹配的字符串。如何在C++中比較兩個數組並返回不匹配的值

什麼,我希望得到例子:
輸入向量1會是什麼樣子:字符串1,字符串,STRING3]
輸入向量2會是什麼樣子:[字符串2,STRING3,串,4]

理想的輸出:
字符串1:不匹配
字符串2:比賽
STRING3:比賽
串,4:不匹配

目前我使用此代碼:

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]; 
    } 
    } 
} 
} 

它匹配的那些偉大工程,但在一切迭代這麼多次,
不匹配得到印有大量的人的時代。

我該如何改進?

+3

我想'I = I + +'應該只是'++ i'(同樣以'j' obvs)。 – Galik 2014-09-20 04:37:21

+1

也排序第一個數組,並進行二進制搜索與第二個數組作爲輸入應該會改善您的結果 – 2014-09-20 04:46:58

+4

這可以通過排序和使用set_intersection和set_symmetric_difference來完成。看到這裏:http://ideone.com/y0o5St – PaulMcKenzie 2014-09-20 05:26:05

回答

1

最好的代碼是你沒有寫的代碼。

如果你拿一個(STL)地圖容器,它會照顧你整理和記住你遇到的不同的字符串。

讓容器爲我們工作。

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

您只有一個循環。 這是隻爲你一個提示(我的代碼並沒有考慮到的是,在第二矢量串,4可能存在不止一次,但我讓你把它安排到您的具體需求)

#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 
+0

感謝您的幫助! – reklaw 2014-09-20 14:35:34

0
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; 
} 
相關問題