vector version of slow multiset - c++

I want to sort my objects according to some criteria (according to how big the items are)
My funcSort in multiset slows down calculations and makes the solution does not scale. How can I make it faster?
To avoid it I tried to use vector, sort it (should go quicker?) and change it into multiset. My solution however does not work, I am not sure what I do wrong?
Function arguments:
void deliver(const std::set<MyItem::Ptr> items, MyItem::Ptr item)
(Typedef of shared_ptr):
typedef boost::shared_ptr<MyItem> Ptr;
sort function:
auto funcSort = [item](MyItem::Ptr lhs, MyItem::Ptr rhs){
return lhs->howFar(item->howBig()) < rhs->howFar(item->howBig());
};
Original with multiset (SLOW when using funcSort):
std::multiset<MyItem::Ptr, decltype(funcSort)> sortedItems(funcSort);
for (MyItem::Ptr item : items){
sortedItems.insert(item);
}
My vector attempt (Error message):
std::vector<MyItem::Ptr> sortedItems;
for (MyItem::Ptr item : items)
{
sortedItems.push_back(item);
}
std::sort(sortedItems.begin(), sortedItems.end(), funcSort());
std::multiset<MyItem::Ptr> ms(sortedItems.begin(), sortedItems.end());
Error message:
__lambda1
auto funcSort = [item](MyItem::Ptr lhs, MyItem::Ptr rhs)
candidate expects 2 arguments, 0 provided

You got the sort call wrong. You just want to pass the funcSort, not call it.
Try it like this:
std::sort(sortedItems.begin(), sortedItems.end(), funcSort);

Related

How to neatly write two functions - one for checking if a solution exists, and another one for getting all solutions?

The obvious way is to just write two functions, but then they are almost identical. What I'm doing now is a function template with the return type (either bool or vector<something>) as the argument
template<typename ReturnType>
ReturnType foo(...){
constexpr bool return_bool = std::is_same<ReturnType, bool>::value;
ResultType results; //hopefully, the compiler takes it out in the bool case
And the plan is to use if constexpr(return_bool) when needed. But then I get this reoccurring piece of code
ReturnType result = foo<ResultType>(...);
if constexpr(return_bool){
if(result) return true;
}else std::copy(result.begin(), result.end(), std::back_inserter(results));
The return statement makes it hard to use standard anti-repetition techniques. I could use macros but then perhaps the repetition is better. Getting either all solutions or just the information whether one exists seems like a fairly general problem, is there a better way to do it?
I should've added that the function is performance-critical in the "does a solution exist?" case. That's why I want to have another version there and also why I don't want any costly abstractions.
You want two opposite features :
Reusing one solution in the other to avoid replication
Having an optimized version for solutionExists() to avoid a full result search
You didn't specify what is the solution your function returns, so I will explain why you can't have both using a simple example : your function is returning the number of ocurences of 0 in a vector of integers.
The function returning all solutions would look like this :
int GetNumberOfOccurencesOf0(const vector<int>& data)
{
int occurences = 0;
for (int i : data)
{
if (i == 0)
++occurences;
}
return occurences;
}
If you are not concerned about performance, your function for returning if there is a solution can be :
bool AreThereOccurencesOf0(const vector<int>& data)
{
return (GetNumberOfOccurencesOf0(data) > 0);
}
Note that there is no code duplication but the solution is not optimal : the data vector is iterated entirely. If you want an optimized solution, it would look like this :
bool AreThereOccurencesOf0(const vector<int>& data)
{
for (int i : data)
{
if (i == 0)
return true;
}
return false;
}
If your problem requires an optimized version of solutionExists(), you should write it and it should not need to reuse code from the getAllSolutions() function.

C++ CppCheck algorithm suggestion (std::find_if instead of raw loop) pertinence

CppCheck suggest me to replace one of my code by a STL algorithm, I'm not against it, but I don't know how to replace it. I'm pretty sure this is a bad suggestion (There is warning about experimental functionalities in CppCheck).
Here is the code :
/* Cutted beginning of the function ... */
for ( const auto & program : m_programs )
{
if ( program->compare(vertexShader, tesselationControlShader, tesselationEvaluationShader, geometryShader, fragmentShader) )
{
TraceInfo(Classname, "A program has been found matching every shaders.");
return program;
}
}
return nullptr;
} /* End of the function */
And near the if condition I got : "Consider using std::find_if algorithm instead of a raw loop."
I tried to use it, but I can't get the return working anymore... Should I ignore this suggestion ?
I suppose you may need to use that finding function not once. So, according to DRY, you need to separate the block where you invoke an std::find_if algorithm to a distinct wrapper function.
{
// ... function beginning
auto found = std::find_if(m_programs.cbegin(), m_programs.cend(),
[&](const auto& prog)
{
bool b = prog->compare(...);
if (b)
TraceInfo(...);
return b;
});
if (found == m_programs.cend())
return nullptr;
return *found;
}
The suggestion is good. An STL algorithm migth be able to choose an appropriate
approach based on your container type.
Furthermore, I suggest you to use a self-balancing container like an std::set.
// I don't know what kind of a pointer you use.
using pProgType = std::shared_pointer<ProgType>;
bool compare_progs(const pProgType &a, const pProgType &b)
{
return std::less(*a, *b);
}
std::set<std::shared_pointer<prog_type>,
std::integral_constant<decltype(&compare_progs), &compare_progs>> progs.
This is a sorted container, so you will spend less time for searching a program by a value, given you implement a compare operator (which is invoked by std::less).
If you can use an stl function, use it. This way you will not have to remember what you invented, because stl is properly documented and safe to use.

Sort a vector of struct based on a specific field

Currently I am trying to sort a vector of structs based on a specific field. I have set up a custom comparison function for the use of the sort function. However, i am getting some errors with it.
Code:
struct Play{
int min, down, yard, locat;
string Description, offname, defname;
double relevance;
};
bool customCompare(const Play &x, const Play &y)
{
return (x.relevance < y.relevance);
}
void printResults()
{
sort(vecData.begin(),vecData.end(), customCompare);
}`
Errors:
error C3867: 'List::customCompare': function call missing argument list; use '&List::customCompare' to create a pointer to member
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
a) Use sort function with lambda notation as below( if you are using c++11)
sort(vecData.begin(),vecData.end(), [](const Play &x, const Play &y){ return (x.relevance < y.relevance);});
Working code:
http://ideone.com/bDOrBV
b) Make comparator function as static
http://ideone.com/0HsaaH
Although this is an old question, I would like to note for the benefit of the future readers the possibility of directly sorting according to a specific field with the help of projections in the upcoming Ranges library in C++20:
ranges::sort(vecData, ranges::less, &Play::relevance);
This avoids the need of specifying two iterators or writing a custom comparison function or lambda.
static bool customCompare(const Play &x, const Play &y)

removing duplicates from a c++ list

I have been looking for an effective solution to remove duplicates from a C++ list.
The list consists of pointers to a class object which has an attribute ID. I want to remove duplicates based on that ID.
for my purpose, the unique method of the STL list will work in which we can pass a BinaryPredicate. i.e.
void unique( BinPred pr );
I searched on the internet about how to use this method, n got an example in which we can declare a function returning boolean and use the "name" of that function as Binary Predicate.
But it's not working.
What actually is this binary predicate and how do i use it ? ...
Any help will be appreciated.
Here is the code snippet:
class SP_MDI_View {
..
..
bool removeDupli(SP_DS_Node*, SP_DS_Node*);
bool DoReductionGSPN(SP_DS_Node*, SP_ListNode*, SP_DS_Node*);
..
..
}
SP_MDI_View::DoReduction( ... ) {
SP_ListNode setZ; // typedef list<SP_DS_Node*> SP_ListNode, where SP_DS_Node is some other class
setZ.clear();
setZ.merge(tempsubset);
setZ.merge(setX);
setZ.push_back(*cs_iter);
setZ.unique(removeDupli); //Error here
}
bool SP_MDI_View::removeDupli(SP_DS_Node* first, SP_DS_Node* second) {
return ( (first->GetId())==(second->GetId()) );
}
You could write a function like:
bool foo (int first, int second)
{ return (first)==(second) ); }
Also, you might need to declare the function as static if your using it in class.
You have to use unique on an ordered list. So the first thing that you must do is sort the list.

Easy way to check if item is in list?

I'm writing a search algorithm in C++, and one of the things I need to do is have a few if statements that check cells above, below, left of, and right of.
Each time a cell is found to be open and added to the stack, I want it added to a list of cells already checked.
I want to be able to say in the if statement if(thisCell is not in checkedCells).
Any simple ideas?
For this purpose it's better to use the std::set container, because it provides you with the ability to search for items faster than a list. Then you can write:
std::set<itemType> myset;
...
if (myset.find(item) != myset.end()) {
// item is found
}
A larger example can be found by googling. For example, here.
If the number of items are in the hundreds, you can use simple, sequential search. This algorithm is built-into C++ as the find() function:
#include <algorithm> // for find()
typedef std::vector<Cell> CellList;
CellList checked_cells;
// .....
Cell cellToSearch;
if (is_in_checked_cells (cellToSearch, cells))
{
// .....
}
// Makes a sequential search using find().
static bool
is_in_checked_cells (const Cell &cell, const CellList &cells)
{
CellList::const_iterator end = cells.end ();
CellList::const_iterator item = std::find (cells.begin (), end, cell);
return (item != end);
}
Make sure Cell has operator< overridden.
If the list is very large, you may want to use binary search, which also comes bundled with C++:
#include <algorithm> // for sort() and binary_search()
CellList checked_cells;
// Make sure the cells are sorted.
checked_cells.sort (checked_cells.begin (), checked_cells.end ());
Cell cellToSearch;
if (is_in_checked_cells (cellToSearch, cells))
{
// .....
}
// Searches using binary_search().
static bool
is_in_checked_cells (const Cell &cell, const CellList &cells)
{
return std::binary_search (cells.begin (), cells.end (), cell);
}