簡體   English   中英

比較C ++中字符串向量的向量

[英]Compare vectors of vectors of strings in C++

我是C ++的新手(來自Python),我試圖找出一種比較兩個大小不同的向量的好方法,每個向量都包含字符串向量,以在它們之間找到匹配的向量。 我試過==,但這顯然只是比較迭代器而不是它們的內容。

因此,您想比較內部向量嗎? 像這樣的東西應該可以工作(使用gcc 4.7):

typedef vector< vector<string> > VectorOfVector;
VectorOfVector v1 = { {"ab", "cd"}, { "ab" } }, v2 = { {"xy"}, {"ab"}};

for(vector<string> & v1item : v1) { 
  for(vector<string> & v2item : v2) { 
    if (v1item == v2item) cout << "found match!" << endl;
  }
}
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    vector<vector<string>> v1 = { {"abc", "012"}, {"xyz", "9810"}};
    vector<vector<string>> v2 = { {"pqr", "456"}, {"abc", "012"}, {"xyz", "9810"}};

    vector<pair<size_t, size_t>> matches;

    for (auto it1 = v1.cbegin(); it1 != v1.cend(); ++it1)
    {
        auto it2 = find(v2.cbegin(), v2.cend(), *it1);
        if (it2 != v2.cend())
        {
            matches.push_back(make_pair(it1 - v1.cbegin(), it2 - v2.cbegin()));
        }
    }

    for_each(matches.cbegin(), matches.cend(), [](const pair<size_t, size_t> &p)
    {
        cout << p.first << "\t" << p.second << endl;
    });
}

這將兩個向量中所有匹配的索引值成對打印。 您可以使用相應向量的[]運算符讀取匹配向量的內容。

查找公共子向量:

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

int main()
{
    std::vector<std::vector<std::string> > data1; // init here
    std::vector<std::vector<std::string> > data2; // init here

    std::vector<std::vector<std::string> > results;

    // common sub vectors put in result
    std::set_union(data1.begin(),data1.end(), data2.begin(), data2.end(),
                   std::back_inserter(results));
}

但這可能無法回答您的基本問題:

字里行間的閱讀:
您正在使用迭代器在兩個向量之間進行迭代:

  std::vector<std::vector<std::string> >::const_iterator loop1 = /* Get some part of data1 */;
  std::vector<std::vector<std::string> >::const_iterator loop2 = /* Get some part of data2 */;

  // loop1/loop2 are iterators in-to your vec/vec/string
  // Thus de-referencing them will give you a (const) reference to vec/string
  // Thus you should be able to compare them with `==`

  if ((*loop1) == (*loop2))
  {
      std::cout << "They are the same\n";
  }

暫無
暫無

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

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