如果我有一个浮点矢量为{1.2,1.2,1.2,1.3,1.4}并且我必须找出唯一元素的数量,我该怎么办呢?
我是C ++的新手,我真的不知道如何使用迭代器。谢谢!
编辑: 我做了这样的事情:
sort(arra.begin(),arra.end());
vector <float>::iterator it = arra.begin();
while ( it != arra.end() )
{
temp1 = *it;
cout<<temp1<<"\n";
it++;
while (*it == temp1)
{
it++;
cout<<*it<<"\n";
}
count++;
}
但是这给了WA。
答案 0 :(得分:6)
方法之一是以下
#include <iostream>
#include <vector>
#include <set>
int main()
{
std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };
std::cout << "Number of unique elements is "
<< std::set<double>( v.begin(), v.end() ).size()
<< std::endl;
return 0;
}
输出
Number of unique elements is 3
如果向量已经排序而不是空,则可以使用以下方法
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <functional>
int main()
{
std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };
auto n = 1 + std::inner_product( std::next( v.begin() ), v.end(),
v.begin(), size_t( 0 ),
std::plus<size_t>(),
std::not_equal_to<double>() );
std::cout << "Number of unique elements is " << n << std::endl;
return 0;
}
或直截了当的方法
#include <iostream>
#include <vector>
int main()
{
std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 };
size_t n = 0;
if ( v.begin() != v.end() )
{
++n;
for ( auto current = v.begin(), prev = v.begin();
++current != v.end(); ++prev )
{
if ( !( *prev < *current ) && !( *current < *prev ) ) ++n;
}
}
std::cout << "Number of unique elements is " << n << std::endl;
return 0;
}
答案 1 :(得分:3)
如果可以修改矢量(或者你可以复制它):
std::sort(v.begin(), v.end());
auto uniqCnt = std::unique(v.begin(), v.end()) - v.begin();
请注意,这可能不适用于花车,因为它们不能完全代表数字(但是你必须澄清你的意思&#34;独特的元素&#34;关于花车)
答案 2 :(得分:0)
这样的事情会起作用。
std::vector< float > vec = { 1.2f, 1.2f, 1.2f, 1.3f, 1.4f };
int unique_elements = 0;
{
std::vector< float > used;
for ( std::vector< float >::const_iterator it = vec.cbegin(); it != vec.cend(); ++it )
{
if ( std::find( used.cbegin(), used.cend(), *it ) == used.cend() )
{
used.push_back( *it );
++unique_elements;
}
}
}
答案 3 :(得分:0)
而是使用vector
使用set
。它总是保留其中的独特元素。
阅读此example,了解如何找到向量中的唯一元素。
答案 4 :(得分:0)
以下作品:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<double> doublevector;
int main()
{
doublevector v = { 1.2, 1.2, 1.2, 1.3, 1.4 };
sort(v.begin(), v.end()); //not needed if you know vector is sorted
int nbrUnique = 0;
if (v.size() == 1) nbrUnique = 1;
else{
nbrUnique = 1;
for (doublevector::iterator it = v.begin(); it < v.end() - 1; ++it){
if ((*it) != *(it + 1)) nbrUnique++;
}
}
cout << nbrUnique << endl;
return 0;
}