C++ 向量中的数字运算
我试图使用循环打印类似的数字,但我不知道如何检查向量中的所有重复字符,如何解决这个问题C++ 向量中的数字运算,c++,C++,我试图使用循环打印类似的数字,但我不知道如何检查向量中的所有重复字符,如何解决这个问题 int main() { vector <double> n0, similar; cout << "Enter numbers: "; for(double temp; cin >> temp;) n0.push_back(temp); // stop using ctrl+d... const double small
int main() {
vector <double> n0, similar;
cout << "Enter numbers: ";
for(double temp; cin >> temp;)
n0.push_back(temp); // stop using ctrl+d...
const double smallest = *min_element(n0.begin(),n0.end());
const double biggest = *max_element(n0.begin(),n0.end());
cout << "\nVector: ";
for(double x = 0; x < n0.size(); ++x){
cout << n0[x] << " ";
for(double z = -1; z < n0.size(); ++z){
if (n0[z] == n0[x]){
similar.push_back(n0[z]);
}
}
}
cout << "\nSimilar: ";
for(double v = 0; v < similar.size(); ++v){
cout << similar[v] << " ";
}
cout << '\n' << "Smallest: " << smallest
<< '\n' << "Biggest: " << biggest << '\n';
}
intmain(){
向量n0,相似;
cout>temp;)
n0.向后推(temp);//停止使用ctrl+d。。。
const double ministen=*最小元素(n0.begin(),n0.end());
常量double max=*max_元素(n0.begin(),n0.end());
cout首先,似乎你真的想计算int
s,而不是double
s。使用double
s作为循环索引也很奇怪。基于这些,我猜有人建议你对所有类型的数字都使用double
s。那个人错了
现在来回答您的问题-您似乎希望循环读取输入中的数字,然后在最后打印出任何多次出现的数字,同时还打印最小和最大输入。对于跟踪元素的存在,基于哈希的关联容器是一个不错的选择,因为它们支持fast(平均情况下为摊销常量)基于键的插入和查找,具有非常方便的界面
使用此类容器有多种方法,这只是一种方法:
#include <algorithm>
#include <iostream>
#include <limits>
#include <unordered_map>
int main()
{
std::unordered_map<int, int> occurrences; // map inputs to the number of times they occurred
int min = std::numeric_limits<int>::max();
int max = 0;
int inp;
while (std::cin >> inp) { // read and immediately check stream state for success
// first update min and max
min = std::min(min, inp);
max = std::max(max, inp);
// update count
// note that the first time we see a particular input, the map will create a default value of 0
++occurrences[inp];
}
std::cout << "min: " << min << ", max: " << max << '\n';
std::cout << "duplicates:\n";
for (auto const& p : occurrences) { // the map gives you pairs of (int, int)
if (p.second > 1) {
std::cout << p.first << '\n';
}
}
}
请注意,它会打印重复条目,但不会以任何保证的顺序打印。如果您需要以特定(可能是升序)顺序打印副本,则需要执行不同的操作。可能的操作包括将副本放入另一个容器并对其排序,或者首先使用(尽管它有不同的、通常更糟糕的性能特征)
你可能还想考虑使用<代码>未签名的int 遍历,因为看起来你不想允许负数。
你能提供一个示例输入,输出你所期望的和你实际得到的输出吗?这会使你真正想要达到的目标更加清晰。但是我不知道如何检查所有的副本。在向量中添加字符——使用std::unordered\u set
@BoBTFish我正在尝试输入随机数:1 2 4 1 4 7 4 1 4 5并打印:1 4 5可能重复的@YesThatIsMyName好的,谢谢。
$ echo "1 2 4 1 4 5 7 4 1 4 5" | ./SO
min: 1, max: 7
duplicates:
5
4
1