I have a set inside a class, and I'd like to define a new order for that set, but the order depends on an attribute of the class. How should I implement it?
I tried something like this
class myclass{
int c;
set<int,cmp> myset;
struct cmp{
bool operator()(const unsint a, const unsint b)
const {
return (depends on c) ;
}
};
}
but it didn't work. Any help is appreciated, thanks.
EDIT: The problem is that i don't know c a priori. It's a value i get in input, and then it will be always the same.
return (depends on c) ;
I think it's not good idea to make comapare function depend on c, because your set object is already built tree and no rebuild is supported by std::set.
Additionally, note that std::set requires Comparator which meet strict weak ordering rule.
You could read more at 'Compare' documentation and wikipedia
As for your problem, you could create another set with another compare function, and then copy contents here.
typedef std::set<int, cmp2> anotherSet;
std::copy(std::begin(firstSet), std::end(firstSet), std::inserter(anotherSet));
However, it looks like you actually don't need std::set if you have to reorder it depending on some parameter. Consider using another data structure like vector or list. Additionally, if you need ~O(log N) access complexity, you can organize data to heap within your vector.
Related
I have a class from Gtk Library that represents a color(GdkColor)....i have written my own interval tree around it...
Basically, it associates different colors to different intervals...
Now,in my test case, once i do a query for interval,
i want to compare the output with the expected value.
typedef struct
{
GdkColor color;
}intervalMetaData;
struct intervalInfo
{
signed int low;
signed int high;
intervalMetaData _data;
};
metaData = _intervalTree.performQuery(BWInterval);
GdkColor red;
//red==metaData.color //throws an error
I cannot overload == for gdkColor since it is from gdk library.
Is there any other way i can get around this??
IF, and only if, you have all the information you need to determine the equality, it is no problem to define the function yourself:
//not sure what GdkColor contains, but if it is large pass by const &
bool operator==(GdkColor a, GdkColor b) {
//check equality here
return result;
}
operator== does not have to be a member function.
If you have no way of comparing two GdkColor instances, you cannot find out if they are equal. Dead simple. If the framework provides no method which allows you to determine equality it probably does so for a good reason. This would usually be something, where neither <,>,<=, >=, !=, == nor anything comparable are provided and access to the members which would define the equality relation is not possible at all. I can't remember wanting to implement an operator==, where this was the case. However, if you have to force the API to its limit to implement an equality-comparison, you should investigate why that is so.
The typical case where you would have no access would be a C library, which uses a typedef to make a struct opaque. However, if it was intended for you to manipulate the contents of the struct or compare them, the framework would provide either something like
xxx getInformationXXX(struct S) or a method int compare(struct S*, struct S*)
I am not familiar with GdkColor, but I assume, there is some publicly available information that allows you to determine if two instances are equal. You should consider putting this function into a namespace, just in case GdkColor ever implements operator== itself to help avoid disambiguation.
operator== should not be the member of the class (and, probably, does not need an access to private/protected part of it), so it can be overloaded.
You can create the derived class and overload just anything you want inside it.
The simplest thing is just a helper function, kind of isEqualTo(), without any overloading at all.
class C
{
struct S
{
T a;
T2 b;
.
.
.
T z;
};
int compute(S s[]);
}
So I need this compute() method to work on the structure S in on of two ways (runtime selectable).
One case is to estimate something on base of a, b and the other contents of structure S, excluding z.
Other times I need the exact same computations, but taking z instead (and in place of) a. They both are the same type and have the same meaning.
The structure S is exposed in the API and thus need to be stored in exactly this layout.
What would be an efficient (compute() is being called rather often) end elegant solution? bool parameter? enum parameter? Template parameter (if so, how to implement it)?
NOTES:
compute() is quite a long function, with selecting a or z happening exactly once
I'd use an enum. It's no more or less efficient than bool, but it may be more clear at the call site:
compute(s, UseAB);
compute(s, UseZB);
Instead of:
compute(s, false);
compute(s, true);
The template option is possible but probably not better; you should try the regular run-time way first. If you care a lot about performance, consider making compute() inline if it is short and simple.
I would just use bool parameter if these are the only two cases. Keep it simple. And document it properly.
Or you can have two methods computeA(S s) and computeZ(S s). In this case it is really about what you are comfortable with.
Suppose there is a class with several (e.g. 2) containers as private members. Would that be good to have different kinds of begin() (or at()) member functions to access iterator (or element) of the corresponding container?
Here is the small example:
class Example
{
private:
std::vector<double> A;
std::vector<double> B;
public:
double& A(std::size_t index) { return A.at(index); }
double& B(std::size_t index) { return B.at(index); }
};
I need to have such kind of access because there is one class that asks for the values in container A and there is also another class asking for the contents of B. In general class Example might have more than two containers.
Is that a good idea or there is better solution?
Thanks
EDIT
Here is some additional information: container A Holds always some parameters that will be passed to different functions, container B holds the values return from the function that has been passed container A as an argument. And the rest of possible containers will hold different constraints on the values that can be stored in A
Does anything outside of the class care about the contents of these vectors? If not, create a member function to take a function pointer and use it with the vectors. Then you don't need to expose the vectors. Fully exposing internal objects with get functions defeats the point of making them private.
If there might be more, it seems like you actually have some kind of "list" of containers. Almost like your naming scheme A, B, ... is just enumerating them, which is always a sign you should be using some sort of container. Then maybe you actually want a container of std::vectors? If it's a fixed amount, something like:
std::array<std::vector<double>, N> containers;
If it's not fixed, then:
std::vector<std::vector<double>> containers;
Then you could have a single function that asks for the index of the container and then an index within that container:
double& get(std::size_t container, std::size_t element) {
return containers[container][element];
}
It sounds like you need such accessors. You might consider putting const keyword on the returned value if elements doesn't have to be modified
const double& getA(std::size_t index) { return A.at(index); }
Hii ,
I was writing a generic function for sorting when i came across this idea . Usually we give the data and call the function sort which is written in a generic manner. I was wondering if we could accept the data-type of the input dynamically at run-time using generics .
Like , if we want to sort some data and we do not know the type of input that is given before hand . So , we need to take the data-type of input dynamically and perform the sort .
Is it possible .. ???
Yeah, if only somebody had though of that before...
Sort algorithms in libraries are generally pretty generic. You just need to tell them how to compare your objects.
I was wondering if we could accept the data-type of the input dynamically at run-time using generics...
....we want to sort some data and we do not know the type of input that is given before hand...
No, you can't do that with C++ templates (I assumed you meant templates when you said generics).
C++ templates are a language feature that allows for types in code to be unspecified until the code that uses them is compiled. That is, C++ templates are a compile-time feature.
If all the types involved are known by the time the code is compiled, then you can use C++ templates. In your sorting example, if you know the exact types of the data to be sorted, then something like the std::sort() function can be used.
If you can't determine the exact types of objects until runtime (which is apparently the situation you're describing), then polymorphism via virtual functions should be used. Using your sorting example, you may have a base class like this:
class SortableInput
{
public:
virtual bool IsLessThan(SortableInput& rhs) = 0;
};
Then your different types can derive from it:
class SortableItemA : public SortableInput
{
public:
virtual bool IsLessThan(SortableInput& rhs) { /* */ }
};
class SortableItemB : public SortableInput
{
public:
virtual bool IsLessThan(SortableInput& rhs) { /* */ }
};
// ...
Then your sort function would only have to know about SortableInput. Of course, this only really makes sense if a SortableItemA can actually be compared against a SortableItemB.
I'm currently building a set of common functions (Search algorithm implementations), and think I'm doing the grouping wrong. At the moment, I have a class, Sorting, that is declared in a file called Sorting.h (it's nowhere near finished yet, btw) like so:
#ifndef SORTING_H
#define SORTING_H
#include <vector>
class Sorting {
private:
Sorting();
Sorting(const Sorting& orig);
virtual ~Sorting();
public:
static void bubbleSort(std::vector<int>& A);
// etc
};
#endif /* SORTING_H */
Now, because the constructor is private, a user cannot instantiate my class - it effectively is just a holder for static functions that the user can call. However, from what I have read of C++ so far - and from looking at the STL libraries etc- I think I'm doing this wrong. Should I instead have a namespace called 'Sorting' or something of the sort? If so, what does my header file (the one the user would include) look like? And would I have to change the structure of the rest of the files? At the moment each set of algorithms is in it's own cpp file (i.e. BubbleSort.cpp, CocktailSort.cpp, etc).
Apologies for what may be a duplicate question - I did search for C++ and namespace, but I got very general questions about namespaces back and none seemed to be this specific problem.
Use a namespace. The callers of the code won't need to care. Also, you need to template on any sortable type- a sort that can only sort a vector of integers is rather bad. Stick to the definition provided by std::sort.
namespace Sorting {
template<typename Iterator> void cocktail_sort(Iterator a, Iterator b) {
// implement cocktail sort
}
template<typename Iterator> void bubble_sort(Iterator a, Iterator b) {
// implement bubble sort
}
};
The caller won't care whether you're statically in a class, but the simple fact is that you waste semantics and time having it in a class, and it doesn't accurately represent the intention. It's not wrong, per se, but it is kinda bad. Using a namespace also allows callers to use the using namespace Sorting; semantics.
It doesn't matter, a free function in a namespace achieves the same. The syntax for calling it is identical.
I'll recomend using a namespace if the class is not to be instantiated.