比较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 samen";
}
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>