I learned an interesting (and very easy) way to remove duplicate entries as well as to sort them. Basically, in C++ it is achieved by creating a new set and initialize with values from the vector. We shift all the hardwork to the std library to do this.
#include <iostream>
#include <vector>
#include <set>
void print(std::vector<int> &v)
{
std::cout << "[";
for(std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it << ",";
}
std::cout << "]" << std::endl;
}
void print(std::set<int> &v)
{
std::cout << "{";
for(std::set<int>::iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it << ",";
}
std::cout << "}" << std::endl;
}
int main()
{
int inits[] = {1,10,3,2,2,4,4,5,6,7,8,8,9};
std::vector<int> vec(inits, inits + sizeof(inits)/sizeof(inits[0]));
print(vec);
std::set<int> ves(vec.begin(), vec.end()); // both sorted & unique already
print(ves);
}
#include <iostream>
#include <vector>
#include <set>
void print(std::vector<int> &v)
{
std::cout << "[";
for(std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it << ",";
}
std::cout << "]" << std::endl;
}
void print(std::set<int> &v)
{
std::cout << "{";
for(std::set<int>::iterator it = v.begin(); it != v.end(); ++it)
{
std::cout << *it << ",";
}
std::cout << "}" << std::endl;
}
int main()
{
int inits[] = {1,10,3,2,2,4,4,5,6,7,8,8,9};
std::vector<int> vec(inits, inits + sizeof(inits)/sizeof(inits[0]));
print(vec);
std::set<int> ves(vec.begin(), vec.end()); // both sorted & unique already
print(ves);
}
No comments:
Post a Comment