I have a priority_queue that contains a vector with some objects.
std::priority_queue<std::shared_ptr<Foo>, std::vector<std::shared_ptr<Foo>>, foo_less> foo_queue;
It has a foo_queue function that will order the priority_queue.
Now, from outside of the priority_queue, I want to change some object value that must influenciate the ordering of the priority_queue.
My question is:
How can I set some kind of "refresh" that will trigger the priority_queue to run the foo_queue() in order to keep it orderes all the time?
Make your own priority queue using the standard heap algorithms and a
vector. When you want to change a key, find and remove that value from
the underlying vector and call make_heap on the vector. Alter the key and then
push it back onto the heap. So the cost is a linear search of the vector
to find the value and a call to make_heap (which I think is also linear).
#include <iostream>
#include <vector>
#include <algorithm>
template <class T, class Container = std::vector<T>,
class Compare = std::less<T> >
class my_priority_queue {
protected:
Container c;
Compare comp;
public:
explicit my_priority_queue(const Container& c_ = Container(),
const Compare& comp_ = Compare())
: c(c_), comp(comp_)
{
std::make_heap(c.begin(), c.end(), comp);
}
bool empty() const { return c.empty(); }
std::size_t size() const { return c.size(); }
const T& top() const { return c.front(); }
void push(const T& x)
{
c.push_back(x);
std::push_heap(c.begin(), c.end(), comp);
}
void pop()
{
std::pop_heap(c.begin(), c.end(), comp);
c.pop_back();
}
void remove(const T& x)
{
auto it = std::find(c.begin(), c.end(), x);
if (it != c.end()) {
c.erase(it);
std::make_heap(c.begin(), c.end(), comp);
}
}
};
class Foo {
int x_;
public:
Foo(int x) : x_(x) {}
bool operator<(const Foo& f) const { return x_ < f.x_; }
bool operator==(const Foo& f) const { return x_ == f.x_; }
int get() const { return x_; }
void set(int x) { x_ = x; }
};
int main() {
my_priority_queue<Foo> q;
for (auto x: {7, 1, 9, 5}) q.push(Foo(x));
while (!q.empty()) {
std::cout << q.top().get() << '\n';
q.pop();
}
std::cout << '\n';
for (auto x: {7, 1, 9, 5}) q.push(Foo(x));
Foo x = Foo(5);
q.remove(x);
x.set(8);
q.push(x);
while (!q.empty()) {
std::cout << q.top().get() << '\n';
q.pop();
}
}
Related
I can't figure out why in this code example the std::set container is not ordering the Entities as I expect on the basis of the compare class I defined. Anyone can help me please? Thanks
#include <iostream>
#include <set>
class Entity {
public:
int num;
Entity(int num):num(num){}
bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
};
struct my_cmp {
bool operator() (const Entity* lhs, const Entity* rhs) const { return (lhs < rhs); }
};
class EntityManager {
private:
std::set<Entity*, my_cmp> entities;
public:
void AddEntity(int num) { entities.insert(new Entity(num)); }
void ListAllEntities() const {
unsigned int i = 0;
for (auto& entity: entities) {
std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
i++;
}
}
};
int main(void) {
EntityManager manager;
manager.AddEntity(2);
manager.AddEntity(1);
manager.AddEntity(4);
manager.AddEntity(3);
manager.ListAllEntities();
return 0;
}
Output:
Entity[0]: num:2
Entity[1]: num:1
Entity[2]: num:4
Entity[3]: num:3
I would expect the following output instead:
Entity[1]: num:1
Entity[0]: num:2
Entity[3]: num:3
Entity[2]: num:4
You need to dereference your pointers *lhs < *rhs. You're just comparing the value of the pointers currently, so your order is dependent on their location in memory.
#include <iostream>
#include <set>
class Entity {
public:
int num;
Entity(int num):num(num){}
bool operator< (const Entity& _entity) const { return (this->num < _entity.num); }
};
struct my_cmp {
bool operator() (const Entity* lhs, const Entity* rhs) const { return (*lhs < *rhs); }
};
class EntityManager {
private:
std::set<Entity*, my_cmp> entities;
public:
void AddEntity(int num) { entities.insert(new Entity(num)); }
void ListAllEntities() const {
unsigned int i = 0;
for (auto& entity: entities) {
std::cout << "Entity[" << i << "]: num:" << entity->num << std::endl;
i++;
}
}
};
int main(void) {
EntityManager manager;
manager.AddEntity(2);
manager.AddEntity(1);
manager.AddEntity(4);
manager.AddEntity(3);
manager.ListAllEntities();
return 0;
}
Demo
I have a method that takes an index-able object as a template parameter, something like:
template <typename OBJ>
int foo(int n, OBJ o)
{
int x = 0;
for (int i = 0; i < n; ++i) {
x += o[i];
}
return x;
}
Is there a way I can pass a lambda function in for the o parameter? In other words, having the lambda be call-able via the [] operator rather than the () operator?
template<class F>
struct square_bracket_invoke_t {
F f;
template<class T>
auto operator[](T&& t)const
-> typename std::result_of< F const&(T&&) >::type
{ return f(std::forward<T>(t)); }
};
template<class F>
square_bracket_invoke_t< typename std::decay<F>::type >
make_square_bracket_invoke( F&& f ) {
return {std::forward<F>(f)};
}
Live example.
Code is C++11 and has basically zero overhead.
int main() {
std::cout << foo( 6, make_square_bracket_invoke([](int x){ return x; } ) ) << "\n";
}
result is 0+1+2+3+4+5 aka 15.
Is this a good idea? Maybe. But why stop there?
For max amusement:
const auto idx_is = make_square_bracket_invoke([](auto&&f){return make_square_bracket_invoke(decltype(f)(f));});
int main() {
std::cout << foo( 6, idx_is[[](int x){ return x; }] ) << "\n";
}
You can do that by:
Creating a class template, a functor, that has the operator[] defined.
Implementing the operator[] in terms of the operator() of a std::function.
Storing the lambda in a wrapped std::function as a member variable of the class template.
Here's a demonstrative program.
#include <iostream>
#include <functional>
template <typename OBJ>
int foo(int n, OBJ o)
{
int x = 0;
for (int i = 0; i < n; ++i) {
x += o[i];
}
return x;
}
template <typename> struct Functor;
template <typename R> struct Functor<R(int)>
{
using ftype = std::function<R(int)>;
Functor(ftype f) : f_(f) {}
R operator[](int i) const { return f_(i); }
ftype f_;
};
int main()
{
Functor<int(int)> f = {[](int i) -> int {return i*i;}};
std::cout << foo(10, f) << std::endl;
}
and its output
285
Live demo
PS
Functor is not the appropriate name here. It does not overload the function call operator. I suspect there is a more appropriate name.
Well, if it helps, here's a way to forward a wrapper class's operator[] to your lambda's operator().
template<class F>
struct SubscriptWrapper_t {
F f_;
template<class T> auto operator[](T const& t_) const -> decltype(f_(t_)) {
return f_(t_);
}
};
template<class F>
SubscriptWrapper_t<typename std::decay<F>::type> SubscriptWrapper(F&& f_) {
return{std::forward<F>(f_)};
}
I use wrappers like this a lot. They're convenient, and they don't seem to have any computational overhead, at least when compiled by GCC. You can make one for at or even make one for find.
EDIT: Updated for C++11 (and updated to be able to return a reference)
A sketch of a wrapper type that would do this.
template<typename UnaryFunction>
class index_wrapper
{
public:
index_wrapper(UnaryFunction func) : func(std::move(func)) {}
template<typename T>
std::invoke_result_t<UnaryFunction, T> operator[](T&& t)
{ return func(std::forward<T>(t)); }
private:
UnaryFunction func;
};
With usage
#include <iostream>
template <typename OBJ>
int foo(int n, OBJ o)
{
int x = 0;
for (int i = 0; i < n; ++i) {
x += o[i];
}
return x;
}
int main()
{
index_wrapper f([](int i) -> int { return i*i; });
std::cout << foo(10, f) << std::endl;
}
You might want to restrict it to a single parameter type, so that you can provide member type aliases similar to std::vector::reference et.al.
I am trying to implement Matrix Addition using expression templates. I am facing some trouble. Here is my matrix code:
#include<iostream>
#include<vector>
#include<cassert>
template <typename T>
class MatrixExpression {
public:
double operator[](size_t i) const { return static_cast<T const&>(*this)[i];}
size_t size()const { return static_cast<T const&>(*this).size(); }
};
template<typename T>
class Matrix:public MatrixExpression<Matrix<T>>
{
std::vector<std::vector<T>> mat;
public:
Matrix(std::size_t m, std::size_t n):mat(m,std::vector<T>(n)){}
class Proxy
{
std::vector<T> vec;
public:
Proxy(std::vector<T> vec):vec(vec){ }
T operator[](std::size_t i){ return vec[i];}
//T &operator[](std::size_t i){ return vec[i];}
std::size_t size() const{ return vec.size(); }
};
Proxy operator[](std::size_t i) const { return Proxy(mat[i]); }
//Proxy &operator[](std::size_t i) { return Proxy(mat[i]); }
size_t size() const { return mat.size(); }
Matrix(std::initializer_list<std::initializer_list<T>> lst)
{
int m=0,n=0;
for(auto l:lst )
{
for(auto v:l)
{
n++;
}
m++;
}
int i=0,j=0;
mat(m,std::vector<T>(n));
for(auto l:lst )
{
for(auto v:l)
{
mat[i].push_back(v);
}
i++;
}
}
Matrix(MatrixExpression<T> const& matx):mat(matx.size(),std::vector<T>(matx[0].size))
{
for(int i=0;i<matx.size();i++)
{
for(int j=0;j<matx[0].size();j++)
{
mat[i][j] = matx[i][j];
}
}
}
};
template<typename T, typename X, typename Y>
class MatrixSum:public MatrixExpression<MatrixSum<T,X,Y>>
{
X const& x;
Y const& y;
public:
MatrixSum(X const& x1, Y const& y1):x(x1),y(y1){
assert(x1.size()==y1.size());
assert(x1[0].size()==y1[0].size());
}
class ProxySum
{
std::vector<T> vec1,vec2;
public:
ProxySum(std::vector<T> vec1,std::vector<T> vec2):vec1(vec1),vec2(vec2){ }
T operator[](std::size_t i){ return vec1[i] + vec2[i];}
//T &operator[](std::size_t i){ return vec1[i] + vec2[i];}
std::size_t size() const{ return vec1[0].size(); }
};
ProxySum operator[](std::size_t i) const { return ProxySum(x[i],y[i]); }
//ProxySum &operator[](std::size_t i){ return ProxySum(x[i],y[i]); }
size_t size() const { return x.size(); }
};
template<typename T,typename X,typename Y>
MatrixSum<T,X,Y>
operator+(X const& x, Y const& y)
{
return MatrixSum<T,X,Y>(x,y);
}
I am getting two errors when using the Matrix class. First is the operator+ does not exist for Matrix (I used int from testing) even though I have implemented operator overloading for '+', and another error is in the second constructor for Matrix. It says that the call I have made for the constructor of mat variable is invalid.But vectors do have such constructor
1) The following line is not a valid C++ syntax:
mat(m,std::vector<T>(n));
You should initialize mat member object in the constructor's initialization list, like this (assuming the outermost initializer_list is not empty):
Matrix(std::initializer_list<std::initializer_list<T>> lst) : mat(lst.size(), std::vector<T>(begin(lst)->size()))
2) As for the operator + you provided:
template<typename T,typename X,typename Y>
MatrixSum<T,X,Y>
operator+(X const& x, Y const& y)
{
return MatrixSum<T,X,Y>(x,y);
}
Note that T template parameter is non-deducible, so the compiler cannot figure it out and thus cannot use this operator. The only way to call it would be like this:
matrix1.operator +<some_type>(matrix2);
...which is probably not what you want.
The right way would be to try and compute T at compile-time, based on X and Y types, using some metaprogramming.
I was implementing the ring buffer and have encountered an error. What does it mean to store a reference of outer class(class ring) object(m_ring) in inner class(class iterator) and when I remove the reference(&) the program compiles correctly but crashes. Please explain what is happening.(See the comment in Ring.h) Sorry for bad English.
// Ring.h
#ifndef RING.H
#define RING.H
#include <iostream>
using namespace std;
template<class T>
class ring {
unsigned int m_size;
int m_pos;
T *m_values;
public:
class iterator;
public:
ring(unsigned int size) : m_size(size), m_pos(0)
{
m_values = new T[m_size];
}
~ring()
{
delete[] m_values;
}
void add(const T &val)
{
m_values[m_pos] = val;
m_pos++;
m_pos %= m_size;
}
T& get(int pos)
{
return m_values[pos];
}
iterator begin()
{
return iterator(0, *this);
}
iterator end()
{
return iterator(m_size, *this);
}
};
template<class T>
class ring<T>::iterator {
int m_pos;
ring &m_ring; // Removing & gives garbage output.
public:
iterator(int pos, ring& aRing) : m_pos(pos), m_ring(aRing){}
bool operator!=(const iterator &other) const
{
return other.m_pos != m_pos;
}
iterator &operator++(int)
{
m_pos++;
return *this;
}
iterator &operator++()
{
m_pos++;
return *this;
}
T &operator*()
{
// return m_ring.m_values[m_pos];
return m_ring.get(m_pos);
}
};
#endif // RING
Driver program :
// Ring_Buffer_Class.cpp
#include <iostream>
#include "ring.h"
using namespace std;
int main()
{
ring<string> textring(3);
textring.add("one");
textring.add("two");
textring.add("three");
textring.add("four");
// C++ 98
for(ring<string>::iterator it = textring.begin(); it != textring.end(); it++)
{
cout << *it << endl;
}
cout << endl;
// C++11
for(string value : textring)
{
cout << value << endl;
}
return 0;
}
I also observed that removing ~ring() (Destructor) results into correct output.
Expected output :
four
two
three
four
two
three
The find method of boost::splay_set that require only the key accepts an argument of type KeyValueCompare to compare objects with the key. To be able to use this, we need to supply two methods of the form:
struct KeyValCompare {
inline bool operator() (const std::int64_t key, const MyType& val) const {
//TODO:
}
inline bool operator() (const MyType& val, const std::int64_t key) const {
//TODO:
}
};
However there is no mention in the documentation about how to implement these. Any pointers?
Found a solution here:
http://boost.cowic.de/rc/pdf/intrusive.pdf
they should return true if key (or key from the value) of lhs is less than the key (or key from the value) of rhs.
I don't see why the comparator would be so complicated. The set just stores elements of MyType, so you need to define a strict weak total ordering on them:
struct Comparator {
bool operator()(MyType const& a, MyType const& b) const;
};
Indeed, the default comparer is std::less<MyType>
E.g. to sort
class MyType : public splay_set_base_hook<>
{
int int_;
public:
MyType(int i) : int_(i) {}
int getValue() const { return int_; }
};
By the value, after reversing the digits (e.g. "431" before "322" because 134<223):
struct CompareReversed {
bool operator()(MyType const& a, MyType const& b) const {
return reversed(a.getValue()) < reversed(b.getValue());
}
private:
static int reversed(int i)
{
auto s = std::to_string(i);
std::reverse(s.begin(), s.end());
return boost::lexical_cast<int>(s);
}
};
See it Live On Coliru:
#include <boost/intrusive/splay_set.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <algorithm>
using namespace boost::intrusive;
class MyType : public splay_set_base_hook<>
{
int int_;
public:
MyType(int i) : int_(i)
{}
// default ordering
friend bool operator< (const MyType &a, const MyType &b) { return a.int_ < b.int_; }
friend bool operator> (const MyType &a, const MyType &b) { return a.int_ > b.int_; }
friend bool operator== (const MyType &a, const MyType &b) { return a.int_ == b.int_; }
int getValue() const { return int_; }
};
struct CompareReversed {
bool operator()(MyType const& a, MyType const& b) const {
return reversed(a.getValue()) < reversed(b.getValue());
}
private:
static int reversed(int i)
{
auto s = std::to_string(i);
std::reverse(s.begin(), s.end());
return boost::lexical_cast<int>(s);
}
};
#include <iostream>
int main()
{
//typedef splay_set<MyType, compare<std::less<MyType> > > Set;
typedef splay_set<MyType, compare<CompareReversed> > Set;
std::vector<MyType> v { 24, 42, 123, 321 };
Set set;
set.insert(v[0]);
set.insert(v[1]);
set.insert(v[2]);
set.insert(v[3]);
for (auto& el : set)
{
std::cout << el.getValue() << "\n";
}
std::cout << set.count(24) << "\n"; // 1
std::cout << set.count(25) << "\n"; // 0
std::cout << set.count(42) << "\n"; // 1
}
If you want to suppor mixed type comparisons, just supply the overloads, obviously:
struct CompareReversed {
bool operator()(MyType const& a, MyType const& b) const {
return reversed(a.getValue()) < reversed(b.getValue());
}
bool operator()(MyType const& a, int b) const {
return reversed(a.getValue()) < reversed(b);
}
bool operator()(int a, MyType const& b) const {
return reversed(a) < reversed(b.getValue());
}
// ...
};
Thanks sehe for the support.
That is exactly what I am doing there. But please have a look at following sample code which fails.
#include <boost/intrusive/splay_set.hpp>
#include <algorithm>
using namespace boost::intrusive;
class MyClass {
public:
MyClass(const std::int64_t& k)
: key(k) {
}
std::int64_t key;
splay_set_member_hook<> member_hook_;
friend bool operator <(const MyClass& lhs, const MyClass& rhs) {
return lhs.key < rhs.key;
}
friend bool operator >(const MyClass& lhs, const MyClass& rhs) {
return lhs.key > rhs.key;
}
friend bool operator ==(const MyClass& lhs, const MyClass& rhs) {
return lhs.key == rhs.key;
}
};
struct KeyValCompare {
inline bool operator()(const std::int64_t key, const MyClass& val) const {
return key < val.key;
}
inline bool operator()(const MyClass& val, const std::int64_t key) const {
return val.key < key;
}
};
typedef member_hook<MyClass, splay_set_member_hook<>, &MyClass::member_hook_> MemberOption;
typedef splay_set<MyClass, MemberOption, compare<std::greater<MyClass> > > MyClassObjectsType;
TEST(MyClass, test) {
MyClassObjectsType set;
set.insert(*new MyClass(10));
set.insert(*new MyClass(20));
set.insert(*new MyClass(100));
auto ite = set.find(100, KeyValCompare());
ASSERT_TRUE(ite != set.end()); // Fails here
}
If I use std::less instead of std::greater, it passes.
Figured it out:
The greater than operator must be change from:
friend bool operator >(const MyClass& lhs, const MyClass& rhs) {
return lhs.key > rhs.key;
}
to this:
friend bool operator >(const MyClass& lhs, const MyClass& rhs) {
return lhs.key < rhs.key;
}