如何在C++中比较两个数组并返回不匹配的值
How to compare two arrays and return non matching values in C++
我想解析两个字符串向量,找到彼此匹配的字符串和不匹配的字符串。
我想要得到的示例:
输入向量1看起来像:[string1,string2,string3]
输入向量2看起来像:[string2,string3,string4]
理想输出:
字符串1:不匹配
字符串2:匹配
字符串3:匹配
字符串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];
}
}
}
}
它适用于匹配的对象,但会对所有对象进行多次迭代,
并且不匹配的会被大量打印
我该如何改进
最好的代码是不必编写的代码。
如果你使用一个(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
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;
}
相关文章:
- 如何在C++中比较两个char数组
- 在c++中获取两个大int,并将它们存储在数组中
- 如何以优化的方式同时迭代两个间距不相等的数组
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 可以将两个相同类型的连续数组视为一个数组吗?
- C++递归来决定数组中的两个值
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 给定一个大小为 N 的数组 S,检查是否可以将序列拆分为两个序列
- 在 char* 数组中添加两个索引
- 使用嵌套函数数组是个好主意吗?
- 链表数组(5 个队列)
- 是否有可能通过溢出 C 中的第一个元素来写入数组第二个元素
- 动态分配一维结构数组:两种方法
- 指向数组第一个元素的指针的地址
- 用 std::valarray 替换 POD C 样式数组是个坏主意吗?
- OpenGL:两个顶点数组 + 两个索引数组
- c++多维数组多个数据类型
- 使用C++AMP处理大型数组(65536+个元素)
- 在c++中使用MKL函数初始化数组是个好主意吗?