比较C++字符串向量的向量

Compare vectors of vectors of strings in C++

本文关键字:向量 字符串 C++ 比较      更新时间:2023-10-16

我是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 samen";
  }