I have a std::vector<t_Mont> v, t_Mont have {float val, int i and int j}
I want to do make_heap(v.begin(), v.end()) and pop_head(v.begin(), v.end()) but I get a lot of errors on console. I think this is because I'm passing a vector of type t_mont.
I want to make_heap on the value of the variable val of v.
What I have to do to compile me? I have to overload make_heap and pop_head? How I do it?
Thanks.
My code:
std::vector<t_Mont> v;
for (int i = 0; i < nCellsHeight; i++) {
for (int j = 0; j < nCellsWidth; j++) {
t_Mont aux;
aux.i = i;
aux.j = j;
aux.val = cellValues[i][j];
v.push_back(aux);
}
}
std::make_heap(v.begin(), v.end());
while (v.begin() != v.end()) {
std::cout << "Best of v = " << v[0].val << std::endl;
std::pop_heap(v.begin(), v.end());
v.pop_back();
std::make_heap(v.begin(), v.end());
}
make_heap and related functions will, by default, compare values using <. You need to either provide an overload of that operator for your type:
bool operator<(t_Mont const & lhs, t_Mont const & rhs) {
return lhs.val < rhs.val;
}
or provide a custom comparator when you call the functions:
auto comp = [](t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;};
std::make_heap(v.begin(), v.end(), comp);
If you're stuck with an ancient pre-lambda compiler, define a function type in full:
struct Comp {
bool operator()(t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;}
};
std::make_heap(v.begin(), v.end(), Comp());
t_Mont has to be comparable with operator< for this to work, or you have to use the other form of std::make_heap and pass a comparison functor alongside the iterators (if, for some reason, you don't want t_Mont to be generally sortable).
That is to say, you have to define
bool operator<(t_Mont const &lhs, t_Mont &rhs) {
// return true if lhs is less than rhs, false otherwise.
}
so that you get a total order (i.e., a < b means !(b < a), a < b and b < c mean a < c, and !(a < a)), or
struct t_Mont_compare {
bool operator()(t_Mont const &lhs, t_Mont &rhs) const{
// return true if lhs is less than rhs, false otherwise.
}
}
with the same conditions.
You have to define a function object for making comparisons between two t_Monts. The declaration of make_heap looks like this :
template <class RandomAccessIterator, class Compare>
void make_heap (RandomAccessIterator first, RandomAccessIterator last, Compare comp );
Or just create a function like this :
bool comp_tmonts(const t_Mont& a, const t_Mont& b)
{
/* Insert your comparison criteria for less than here.
Return a boolean value corresponding to whether a is less than b */
}
Then pass this to your make_heap function as the third argument :
make_heap(v1.begin(), v1.end(), comp_tmonts);
Related
vector<vector<int>> reconstructQueue(vector<vector<int>> &people) {
auto cmp = [](const vector<int> &a, const vector<int> &b) {
return a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]);
};
sort(people.begin(), people.end(), cmp);
Hey guys can someone explain me the auto cmp... part and how to use it in a sort function any help will be highly appreciated :)
This part of the code is a lambda. In other words, a small function defined locally.
You can make a search for this term for more info.
IN the case of the sort algorithm, you are expected to pass a function taking two arguments and returning true if the first argument is less than the second.
To make it simple, you give an alternative comparison function to use instead of the standard operator< a.k.a. std::less.
Any object having an operator() can be used.
The comparator can be implemented in multiple ways, for eg. a lambda (as in your example) or a callable struct/class.
Just to give you an example for sorting say a vector of std::pair by the second element:
struct Comparator
{
bool operator()(const std::pair<int,int>& lhs, const std::pair<int,int>& rhs)
{
return lhs.second < rhs.second;
}
}
void foo(std::vector<std::pair<int,int> > &v)
{
std::sort(v.begin(), v.end(), Comparator);
}
Alternatively, instead of using a callable struct, you can write foo using lambda as:
void foo(std::vector<std::pair<int,int> > &v)
{
std::sort(v.begin(), v.end(),
[](const pair<int, int>& lhs, const pair<int, int>& rhs)
{
return lhs.second < rhs.second;
} );
}
You can write more advanced comparisons by say capturing some other data and using that for comparisons. Try reading about lambdas.
Given a list of objects, what is the cleanest way to create a functor object to act as a comparator, such that the comparator respects the ordering of the objects in the list. It is guaranteed that the objects in the list are unique, and the list contains the entire space of possible objects.
For example, suppose we have:
const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};
Now we want a function to act as a comparator, say for a map:
using Comparator = std::function<bool(const std::string&, const std::string&>;
using MyMap = std::map<std::string, int, Comparator>;
I have a solution, but it's not what I'd call pretty:
const auto cmp = [&ordering] (const auto& lhs, const auto& rhs)
{
const std::array<std::reference_wrapper<const std::decay_t<decltype(lhs)>, 2> values {lhs, rhs};
return *std::find_first_of(std::cbegin(ordering), std::cend(ordering),
std::cbegin(values), std::cend(values),
[] (const auto& lhs, const auto& rhs) {
return lhs == rhs.get();
}) == lhs;
};
Is there something a little less verbose?
You can use:
const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};
struct cmp
{
bool operator()(const std::string& lhs, const std::string& rhs)
{
return (std::find(ordering.begin(), ordering.end(), lhs) <
std::find(ordering.begin(), ordering.end(), rhs));
}
};
using MyMap = std::map<std::string, int, cmp>;
See it working at http://ideone.com/JzTNwt.
Just skip the algorithms and write a for-loop:
auto cmp = [&ordering](auto const& lhs, auto const& rhs) {
for (auto const& elem : ordering) {
// check rhs first in case the two are equal
if (elem == rhs) {
return false;
}
else if (elem == lhs) {
return true;
}
}
return false;
};
It might technically be longer than your solution, but I find it way easier to read.
Alternatively, depending on the size of the ordering, could throw both into a map:
std::unordered_map<std::string, int> as_map(std::vector<std::string> const& ordering)
{
std::unordered_map<std::string, int> m;
for (auto const& elem : ordering) {
m.emplace(elem, m.size());
}
return m;
}
auto cmp = [ordering_map = as_map(ordering)](auto const& lhs, auto const& rhs){
auto left = ordering_map.find(lhs);
auto right = ordering_map.find(rhs);
return left != ordering_map.end() && right != ordering_map.end() &&
left->second < right->second;
};
KISS. Build up your solution from reusable primitives with clear semantics.
order_by takes a projection A->B and returns an ordering on A using the ordering on B. It optionally takes an ordering on B (not used here):
template<class F, class Next=std::less<>>
auto order_by(F&& f, Next&& next = {}) {
return [f=std::forward<F>(f), next=std::forward<Next>(next)]
(auto&& lhs, auto&& rhs)->bool
{
return next(f(lhs), f(rhs));
};
}
index_in takes a container c and returns a function that takes an element, and determines its index in c:
template<class C>
auto index_in( C&& c ) {
return [c=std::forward<C>(c)](auto&& x){
using std::begin; using std::end;
return std::find( begin(c), end(c), x ) - begin(c);
};
}
template<class T>
auto index_in( std::initializer_list<T> il ) {
return [il](auto&& x){
using std::begin; using std::end;
return std::find( begin(il), end(il), x ) - begin(il);
};
}
We then compose them:
auto cmp = order_by( index_in(std::move(ordering) ) );
Each component can be independently tested and validated, and the composition "obviously" works. We can also rewrite index_in to use a faster lookup than linear, say a map from key to index, and we'd have two implementations that can unit test against each other.
I find order_by very often useful. index_in I've never had to use before.
This trick makes constructing the resulting map on one line, instead of storing cmp, practical, as the final description is short and clear.
template<class T>
using Comparator = std::function<bool(T const&, T const&>;
using MyMap = std::map<std::string, int, Comparator<std::string>>;
MyMap m = order_by( index_in({"dog", "cat", "mouse", "elephant"}) );
is also really pretty looking.
Here is a second approach.
We can move some of the work outside of the lambda.
template<class T0, class...Ts>
std::array< std::reference_wrapper<T0>, sizeof...(Ts)+1 >
make_ref_array( T0& t0, Ts&... ts ) {
return {std::ref(t0), std::ref(ts)...};
}
Then we can write the lambda from first principles instead of algorithms:
Comparator cmp = [&ordering] (const auto& lhs, const auto& rhs)
{
if (lhs==rhs) return false; // x is never less than x.
for (auto&& e:ordering)
for (auto&& z:make_ref_array(lhs, rhs))
if (e==z.get())
return std::addressof(z.get())==std::addressof(lhs);
return false;
};
The resulting lambda is a bit less verbose.
If you had ranged based algorithms it might also help.
In both my solutions, all elements not in the list are greater than any element in the list, and are equal to each other.
I suggest you make the key a structure type containing the key (std::string in this case) and the index in the array.
Something like
struct Key
{
std::string str;
size_t index;
};
using MyMap = std::map<Key, int, Comparator>;
struct Comparator
{
bool operator()(const Key &a, const Key &b) const
{
return a.index < b.index;
}
};
This is basically the same as R. Sahu's answer. But since I'd already typed it up... The primary thing I'm advocating here is keeping ordering internal to cmp, presuming that you don't need it externally.
const auto cmp = [ordering = vector<string>{ "dog", "cat", "mouse", "elephant" }](const auto& lhs, const auto& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); };
Live Example
Encapsulating the ordering within cmp makes the scope that a reader has to look at when he changes ordering much smaller. (Personally I wouldn't construct cmp as an Rvalue, I'd just dump it directly into the constructor for the same reason... Though it is becoming a bit of a redonculous one-liner:
map<string, int, function<bool(const string&, const string&)>> myMap([ordering = vector<string>{ "dog", "cat", "mouse", "elephant" }](const auto& lhs, const auto& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); });
Live Example
Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)
For example:
const vector<int> first = {13};
const vector<int> second = {42};
const vector<int> concatenation = first + second;
I know that vector doesn't have an addition operator like string, but that's the behavior that I want. Such that concatenation would contain: 13 and 42.
I know that I can initialize concatenation like this, but it prevents me from making concatenation const:
vector<int> concatenation = first;
first.insert(concatenation.end(), second.cbegin(), second.cend());
No, it's not possible if you require that
no helper function is defined, and
the resulting vector can be declared const.
template<typename T>
std::vector<T> operator+(const std::vector<T>& v1, const std::vector<T>& v2){
std::vector<T> vr(std::begin(v1), std::end(v1));
vr.insert(std::end(vr), std::begin(v2), std::end(v2));
return vr;
}
This does require a helper "function", but at least it allows you to use it as
const vector<int> concatenation = first + second;
I think you have to write a help function. I'd write it as:
std::vector<int> concatenate(const std::vector<int>& lhs, const std::vector<int>& rhs)
{
auto result = lhs;
std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
return result;
}
The call it as:
const auto concatenation = concatenate(first, second);
If the vectors are likely to be very large (or contain elements that are expensive to copy), then you might need to do a reserve first to save reallocations:
std::vector<int> concatenate(const std::vector<int>& lhs, const std::vector<int>& rhs)
{
std::vector<int> result;
result.reserve( lhs.size() + rhs.size() );
std::copy( lhs.begin(), lhs.end(), std::back_inserter(result) );
std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
return result;
}
(Personally, I would only bother if there was evidence it was a bottleneck).
class Vector : public vector<int>
{
public:
Vector operator+(const Vector& vec);
};
Vector Vector::operator+(const Vector& vec)
{
for (int i = 0; i < vec.size(); i++)
{
this->push_back(vec[i]);
}
return *this;
}
Let me preface this by saying this is a hack, and will not give an answer to how to do this using a vector. Instead we'll depend on sizeof(int) == sizeof(char32_t) and use a u32string to contain our data.
This answer makes it exceedingly clear that only primitives can be used in a basic_string, and that any primitive larger than 32-bits would require writing a custom char_traits, but for an int we can just use u32string.
The qualification for this can be validated by doing:
static_assert(sizeof(int) == sizeof(char32_t));
Once size equality has been established, and with the knowledge that things like non-const data, and emplace or emplace_back cannot be used, u32string can be used like a vector<int>, with the notable inclusion of an addition opperator:
const vector<int> first = {13};
const vector<int> second = {42};
const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());
[Live Example]
I came across this question looking for the same thing, and hoping there was an easier way than the one I came up with... seems like there isn't.
So, some iterator trickery should do it if you don't mind a helper template class:
#include <vector>
#include <iostream>
template<class T>
class concat
{
public:
using value_type = typename std::vector<T>::const_iterator::value_type;
using difference_type = typename std::vector<T>::const_iterator::difference_type;
using reference = typename std::vector<T>::const_iterator::reference;
using pointer = typename std::vector<T>::const_iterator::pointer;
using iterator_category = std::forward_iterator_tag;
concat(
const std::vector<T>& first,
const std::vector<T>& last,
const typename std::vector<T>::const_iterator& iterator) :
mFirst{first},
mLast{last},
mIterator{iterator}{}
bool operator!= ( const concat& i ) const
{
return mIterator != i.mIterator;
}
concat& operator++()
{
++mIterator;
if(mIterator==mFirst.end())
{
mIterator = mLast.begin();
}
return *this;
}
reference operator*() const
{
return *mIterator;
}
private:
const std::vector<T>& mFirst;
const std::vector<T>& mLast;
typename std::vector<T>::const_iterator mIterator;
};
int main()
{
const std::vector<int> first{0,1,2,3,4};
const std::vector<int> last{5,6,7,8,9};
const std::vector<int> concatenated(
concat<int>(first,last,first.begin()),
concat<int>(first,last,last.end()));
for(auto i: concatenated)
{
std::cout << i << std::endl;
}
return 0;
}
You may have to implement operator++(int) or operator== depending on how your STL implements the InputIterator constructor, this is the minimal iterator code example I could come up with for MingW GCC.
Have Fun! :)
I need to iterate over a vector strictly in the order the elements were pushed back into it. For my particular case it's better use iterators than iterating though the for-each loop as follows:
std::vector<int> vector;
for(int i = 0; i < vector.size(); i++)
//not good, but works
My question is if it's realiably to iterate over the vector through iterator like that:
std::vector<int> v;
for(typename std::vector<int>::iterator i = v.iterator(); i != v.end(); i++)
//good, but I'm not strictly sure about the iterating order.
So, can I use iterators safely with my requirements? Is it standartized?
If you have access to C++11 you can use range-based for loops
for (auto i : v)
Otherwise you should use begin() and end()
for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i)
You can also use std::begin and std::end (these require C++11 as well)
for (std::vector<int>::iterator i = std::begin(v); i != std::end(v); ++i)
begin will return an iterator to the first element in your vector. end will return an iterator to one element past the end of your vector. So the order in which you get the elements iterating this way is both safe and defined.
if you want to use iterators, your approach is fine
for(auto it = v.begin(); it != v.end(); ++it)
the iteration order depends in fact on the container and the actual used iterator.
for a std::vector this code iterates always over the elements in their order in the vector. if you'd use v.rbegin() or v.rend() instead, the order would be reversed.
for another container the order is different, for a std::set the very same code would iterate the elements in ascending order of their sorting criterion.
This is an overly complex solution.
First, we start with an index type. It can store anything that models iterator and/or integral (basically, supports + scalar, delta to scalar, copy, destruction and equality):
template<class T,
class Category=std::random_access_iterator_tag,
class Delta=decltype(std::declval<T>()-std::declval<T>())
>
struct index:
std::iterator<Category, T, Delta, T*, T>
{
T t;
T operator*()const{ return t; }
index& operator++(){++t; return *this;}
index operator++(int){index tmp = *this; ++t; return tmp;}
index& operator--(){--t; return *this;}
index operator--(int){index tmp = *this; --t; return tmp;}
T operator[](size_t i)const{return t+i;}
friend bool operator<(index const& lhs, index const& rhs) {
return rhs.t-lhs.t>0;
}
friend bool operator>(index const& lhs, index const& rhs) {
return rhs<lhs;
}
friend bool operator<=(index const& lhs, index const& rhs) {
return !(lhs>rhs);
}
friend bool operator>=(index const& lhs, index const& rhs) {
return !(lhs<rhs);
}
friend bool operator==(index const& lhs, index const& rhs) {
return lhs.t==rhs.t;
}
friend bool operator!=(index const& lhs, index const& rhs) {
return lhs.t!=rhs.t;
}
friend Delta operator-(index const& lhs, index const& rhs) {
return lhs.t-rhs.t;
}
friend index& operator+=(index& lhs, Delta rhs) {
lhs.t+=rhs;
return lhs;
}
friend index& operator-=(index& lhs, Delta rhs) {
lhs.t-=rhs;
return lhs;
}
friend index operator+(index idx, Delta scalar) {
idx+=scalar;
return idx;
}
friend index operator+(Delta scalar, index idx) {
idx+=scalar;
return idx;
}
friend index operator-(index idx, Delta scalar) {
idx-=scalar;
return idx;
}
};
most of which isn't needed, but I wanted to be complete. Note that this claims to be a random access iterator by default, but it lies, as its reference type is not a reference. I consider the lie worthwhile.
With index we can both create an iterator-over-integrals, and an iterator-over-iterators. Here is how we create an iterator-over-iterators:
using it_category=typename std::iterator_traits<It>::iterator_category;
template<class It, class Category=it_category<It>>
index<It, Category> meta_iterator( It it ) { return {it}; }
Next, we want to be able to take some iterators, and iterate over the range. This means we want a range type:
template<class It>
struct range {
It b, e;
range(It s, It f):b(s),e(f){}
range():b(),e(){}
It begin()const{return b;}
It end()const{return e;}
bool empty()const{return begin()==end();}
template<class R>
range(R&& r):range(std::begin(r),std::end(r)){}
};
This is a trait that takes an iterable range (not only a range, but also any container) and gets the iterator type out. Note that a superior ADL-enabled one would be a good idea:
template<class R>
using iterator=decltype(std::begin(std::declval<R&>()));
Random helpers:
template<class R,class It=iterator<R>>
range<It> make_range(R&&r){ return {std::forward<R>(r)}; }
template<class It
range<It> make_range(It s, It f){return {s,f};}
Here is a useful helper that solves our problem:
template<class R>
range<meta_iterator<iterator<R>> iterators_into( R&& r ){
return {meta_iterator(std::begin(r)), meta_iterator(std::end(r))};
}
and we are done:
std::vector<int> v;
for(auto it: iterators_into(v)) {
}
returns an iterator for each element of v.
For industrial quality, you'd want to ADL-improve things. Also, dealing with rvalue storage of input ranges lets you chain range-adaptors better in for(:) loops.
I have vector of structures:
vector<Custom> myvec;
Custom is a structure:
struct Custom
{
double key[3];
};
How to sort myvec by key[0]. key[1] or key[2] using STL sort algorithm?
Write a custom comparator:
template <int i> struct CustomComp
{
bool operator()( const Custom& lhs, const Custom& rhs) const
{
return lhs.key[i]<rhs.key[i];
}
};
and then sort e.g. by using std::sort(myvec.begin(),myvec.end(),CustomComp<0>()); (this sorts by the first key entry)
Or with a more recent compiler (with c++0x lambda support):
std::sort(myvec.begin(), myvec.end(),
[]( const Custom& lhs, const Custom& rhs) {return lhs.key[0] < rhs.key[0];}
);
By using a a custom comparator.
struct CustomLess {
size_t idx;
CustomLess(size_t i) : idx(i) {}
bool operator()(Custom const& a, Custom const& b) const {
return a.key[idx] < b.key[idx];
}
};
then
std::sort(myvec.begin(), myvec.end(), CustomLess(1)); // for 1
Note: I did not use a template because, while using a template enables the compiler to optimize for that specific index, it prevents you from selecting the index at runtime, e.g. based on userinput, so it's less flexible/can't do as much as the nontemplated version. And as we all know, premature optimization is evil :)
I'm not sure why so many of the answers posted are focusing on functors. There is no need for a functor with the OP's stated requirement. Here are 2 non-functor solutions:
1: Overload operator< in the Custom class
bool Custom::operator< (const Custom& rhs)
{
return key[0] < rhs.key[0];
}
// can call sort(myvec.begin(), myvec.end());
2: Create a custom comparison function
template<int i> bool CustomLess(const Custom& lhs, const Custom& rhs)
{
return lhs.key[i] < rhs.key[i];
}
// can call sort(myvec.begin(), myvec.end(), CustomLess<0>);
bool CompareCustoms(const Custom& lhs, const Custom& rhs)
{
// Compare criteria here
return (lhs.key[0] < rhs.key[0]);
}
sort(myvec.begin(), myvec.end(), CompareCustoms);