从不使用的 2 个向量(或列表)<algorithm>中删除相似元素
Remove similar elements from 2 vectors (or list) not using <algorithm>
我想从2个向量(或列表)中删除类似的元素。我在这里发现了一个类似的问题,他用<algorimth>
来解决这个问题。我的问题是有没有其他不使用<algorimth>
的方法?
我的是我创建一个向量来保存公共元素的索引,然后删除具有"标记"索引的元素。疯狂的想法,但这不是工作。
示例:
Vector A={1,2,3,4,5};
Vector B={2,3,4,6};
Vector result={1,5};
这是一个已经注意排序和唯一输入的列表的解决方案。
//
#include "stdafx.h"
#include <list>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int A_arrey[] = { 1, 2, 4, 5, 7, 8 };
int B_arrey[] = { 1, 2, 3, 5, 6, 8, 9 };
list<int> A_list(A_arrey, A_arrey + 6);
list<int> B_list(B_arrey, B_arrey + 7);
A_list.sort();
A_list.unique();
B_list.sort();
B_list.unique();
for (int i = 0; i < sizeof(A_arrey) / sizeof(A_arrey[0]); i++)
B_list.remove(A_arrey[i]);
for (int i = 0; i < sizeof(B_arrey) / sizeof(B_arrey[0]); i++)
A_list.remove(B_arrey[i]);
A_list.merge(B_list);
cout << "My list contains:";
for (list<int>::iterator it = A_list.begin(); it != A_list.end(); it++)
std::cout << ' ' << *it;
cout << 'n';
}
在所有值都是唯一且已排序的情况下,可以使用以下操作:
#include <iostream>
#include <vector>
using namespace std;
vector<int> A={1,2,3,4,5};
vector<int> B={2,3,4,6};
vector<int> result;
int main()
{
int a = 0;
int b = 0;
while(a < A.size() && b < B.size())
{
/* Same value - skip to next on both sides */
if (A[a] == B[b])
{
a++;
b++;
}
else
/* Smaller value is unique, so push back that */
if (A[a] < B[b])
{
result.push_back(A[a]);
a++;
}
else
{
result.push_back(B[b]);
b++;
}
}
while (a < A.size())
{
result.push_back(A[a]);
a++;
}
while (b < B.size())
{
result.push_back(B[b]);
b++;
}
for(auto r : result)
{
cout << r << ", ";
}
cout << endl;
return 0;
}
还有许多其他方法。如果值不是很大,可以使用数组在遇到A中的值时向上计数,然后在遇到B时向下计数,然后在完成时遍历计数器数组以给出唯一值列表。
编辑:更新了完整的"工作"代码。
我想你需要这样的东西:
vector<T> v(SIZE);
T tmp=v[0];
// ... Fill your vector here
for(int i=0;i<SIZE;++i)
v[i]==tmp?v.erase(i):tmp=v[i];
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- C++ <algorithm> 使用对象作为比较定义的 sort()
- TicTacToe with MiniMax algorithm 4x4
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- is_permutation方法从 #include<algorithm> 显示错误的输出
- 设置::查找和查找之间的性能差异<algorithm>
- 如何显式调用运算符<<
- Stringholics algorithm
- Next_Permutation algorithm
- 模板操作员&lt;未打电话
- C / CUDA中的模板方法是3个角括号(&lt;&lt;&lt;)
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- 我不使用<algorithm>标题,但 sort() 可用
- std::max在包含<algorithm>后无法解析
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个