0

私はC ++(Pythonから来ました)が初めてで、それぞれが文字列のベクトルを含む異なるサイズの2つのベクトルを比較して、それらの間で一致するベクトルを見つける良い方法を見つけようとしています。== を試しましたが、これは明らかにイテレータを比較するだけであり、その内容は比較しません。

4

3 に答える 3

1

共通のサブベクトルを見つけます。

#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";
  }
于 2013-01-31T19:14:59.490 に答える
1
#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;
    });
}

これにより、両方のベクトルで一致するすべてのインデックス値がペアとして出力されます。それぞれのベクトルの [ ] 演算子を使用して、一致したベクトルの内容を読み取ることができます。

于 2013-01-31T19:05:21.863 に答える
1

内部ベクトルを比較しますか? このようなものは動作するはずです (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;
  }
}
于 2013-01-31T19:02:49.480 に答える