C++如何打印在2数组中重复多少个元素
c++ how print how many element are repeated in 2 array?
我有两个数组,我想计算两个数组之间有多少元素是相同的。我尝试了很多次,但输出不正确。正确的应该是6
次但输出在代码中是 4
次。
注意:如果s1
"ss"
并且s2
"ss"
,则结果2
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int flag=0;
for(int i=0, j=0; i < sizeof(s1) && j < sizeof(s2); ) {
if(s1[i] == s2[j]) {
flag++;
i++;
j++;
} else if(s1[i] < s2[j]) {
i++;
} else {
j++;
}
}
cout << flag;
}
s1 的所有元素都存在于两个字符串中,因此输出将等于 s1 的长度。这是正确的代码
#include <iostream>
using namespace std;
int main() {
char s1[] = "FOOBART";
char s2[] = "BFORATO";
int count=0;
for (int i=0; i<sizeof(s1)-1; i++) {
for (int j=0; j<sizeof(s2)-1; j++) {
if (s1[i]==s2[j]) {
count++;
break;
}
}
}
cout<<count<<endl;
}
希望这对你有帮助
使用 STL 算法的解决方案:
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
const std::string s1 = "FOOBART";
std::string s2 = "BFORATO";
int count = 0;
auto beg = begin(s2);
for(auto& elm : s1)
{
auto x = find(beg, end(s2), elm);
if(x != end(s2))
{
*x = *beg;//get rid of elment and reduce the range of search.
++beg;
++count;
}
}
std::cout << count;
return 0;
}
相关文章:
- C++,数组有多少个地址?
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 在 C++ AMP 数组中复制数据多少次?
- C++ 检查结果数组中有多少次数字
- 将数组的元素插入映射的时间复杂度是多少?
- 当我们不使用空字符显式初始化字符数组时,字符串的长度是多少?
- 我怎么知道数组包含多少个元素C++?
- 数组由其类自己的指针指向的大小是多少?
- c++ 中堆上数组的默认值是多少?
- 如何知道我想在数组中存储多少索引
- 我们可以在 C++ 编程中使用的二维数组的最大大小是多少?
- 指针数组中将有多少内存分配
- C++如何打印在2数组中重复多少个元素
- 找出数组中有多少不同的浮点值
- 在计算使用了多少个数组索引的同时,如何填充一个来自用户输入的字符的数组?(使用cin.get)
- 如果我自己不分配数组元素,数组元素的值是多少
- 遍历二维数组的时间复杂度是多少
- 我的数组的长度是多少