c++ - 无重复运行功能
问题描述
我想知道是否有可能使函数运行而没有重复?
如果它通过带有数字的数组循环,1,2,2,3,4
我希望 2 只运行一次而不是两次。喜欢1,2,3,4
。如何检查是否tab[i]
已经插入?我需要在 c++ 98 中执行此操作。
std::vector<int> noDup(n);
for(int k=0; k < n; k++) {
bool exists = false;
for(int c= 0; c < noDup.size(); c++) {
if(tab[k] == tab[c]) {
exists = true;
break;
}
if(exists == false) {
noDup.push_back(tab[k]);
}
}
}
for(auto c : noDup) {
cout << c << " ";
}
当我在选项卡数组 4 中插入元素数量时,我输入2,2,3,4
我得到了输出0 0 0 0 3 3 4 4 4
解决方案
你做了
if(exists == false) {
noDup.push_back(tab[k]);
}
在错误的地方。它必须在检查所有元素之后。
此外,向量std::vector<int> noDup(n);
已经有n
元素,push_back()
并将在初始元素之后添加n
元素。似乎您想预先分配而不通过添加元素reserve()
。
条件tab[k] == tab[c]
也是错误的。应该是tab[k] == noDup[c]
。
另一个错误是for(auto c : noDup)
(range-based for and auto
) 的使用,它在 C++11 中可用,在 C++98 中不可用。
固定代码:
std::vector<int> noDup;
noDup.reserve(n);
for(int k=0; k < n; k++) {
bool exists = false;
for(int c= 0; c < noDup.size(); c++) {
if(tab[k] == noDup[c]) {
exists = true;
break;
}
}
if(exists == false) {
noDup.push_back(tab[k]);
}
}
for(std::vector<int>::iterator it = noDup.begin(); it != noDup.end(); it++) {
cout << *it << " ";
}
更好的选择是使用std::set
.
std::set<int> seen;
std::vector<int> noDup;
noDup.reserve(n);
for(int k=0; k < n; k++) {
if (seen.find(tab[k]) == seen.end()) {
seen.insert(tab[k]);
noDup.push_back(tab[k]);
}
}
for(std::vector<int>::iterator it = noDup.begin(); it != noDup.end(); it++) {
cout << *it << " ";
}
推荐阅读
- angular - 如何保存搜索查询并将其显示在新组件上?
- javascript - TypeScript 等效于 Array.from()
- python - Pyside2:如何使用 QFileDialog 保存具有特定扩展名的文件?
- list - 合并列表
并列出 进入列表 > - python - python 3.8如何将txt转换为带有2个或更多空格分隔符的csv
- python - Django Celery worker 收到任务但不执行任务
- python - 使用 arima for python 预测具有分钟间隔的时间序列
- user-interface - 如何将内容添加到可见对话框
- c++ - С++:如何将 long double 转换为 char[12]?
- css - Django ClearableFileInput 未正确呈现