I have a set of user defined dataType and using that set variable in a structure. I want to compare the values of set. How will I do that - c++11

using setIp = set<ipv4address>;
struct Test {
setIp IP1;
setIp IP2;
}
IP1 and IP2 can have more than 1 ipaddress.
I want to use find function on setIp and for that need operator <. How would I overload it.

You can do this:
bool operator<(const ipv4address& left, const ipv4address& right) {
return left.TODO < right.TODO;
}
The TODO is there because I don't know what the members of your ipv4address are, but I'm sure you can figure that part out. If your comparison needs to consider multiple members (for example if you store ipv4address as four separate octets), use std::tie:
bool operator<(const ipv4address& left, const ipv4address& right) {
return std::tie(left.o1, left.o2, left.o3, left.o4)
< std::tie(right.o1, right.o2, right.o3, right.o4);
}
That means "if left.o1 is less than right.o1, left is less than right" and so on.
Either way, the operator needs to be declared before you declare your std::set<ipv4address>.

Related

Boost Ptree Custom Sort

I want to use this Function and make a custom sorting function, but I don't know how the Compare Function works or with a lambda.
Could someone be so kind to give me a working example for using it.
/* Sorts the direct children of this node according to the predicate.
The predicate is passed the whole pair of key and child. */
template <class Compare> void sort (Compare comp);
The predicate is passed the whole pair of key and child.
Is this a pair of key/ptree? I don't know how what the datatype is.
Im searching something like a lambda function equal for lists
unorderedGenList.sort([](const boost::property_tree::ptree & treeA, const boost::property_tree::ptree & treeB)
{
if(std::stod(treeA.get<std::string>("sortA","0")) < std::stod(treeB.get<std::string>("sortA","0"))
|| (std::stod(treeA.get<std::string>("sortA","0")) == std::stod(treeB.get<std::string>("sortA","0")) && std::stod(treeA.get<std::string>("sortB","0")) < std::stod(treeB.get<std::string>("sortB","0")))
)
return true;
return false;
});
I think i got the Solution
typedef std::pair< const Key, self_type > value_type;
unorderedPtree.sort([](const boost::property_tree::value_type& treeA, const boost::property_tree::value_type & treeB){
treeA.second.get<std::string>("sortB","0")) ...
}

Store the enum constants in variable

This code actually works fine, the question I have with my code is how do you store the enum constant in any variable, and why do we use enum? and what does the statement mean HouseType houseType;? Thank you so much in advance.
import java.util.Scanner;
public class HomeBuying {
public enum HouseType{UNKNOWN,SINGLEFAMILY,TOWNHOUSE,CONDOMINIUM};
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the type of house you want to purchase"); //1.Single Family/n" " 2. Townhouse/n" " 3. Condominium/n");
int choice = input.nextInt();
HouseType houseType;
switch(choice) {
case 1:
houseType = HouseType.SINGLEFAMILY;
break;
case 2:
houseType = HouseType.TOWNHOUSE;
break;
case 3:
houseType = HouseType.CONDOMINIUM;
break;
default:
houseType = HouseType.UNKNOWN;
break;
}
System.out.println(houseType);
}
The code snippet you provided already stores an Enum value in a variable.
HouseType houseType; //declaration of variable of type HouseType (means it can store values of the HouseType enum)
houseType = HouseType.UNKNOWN; //put value into the houseType variable
We use enums whenever we need to represent values from some known and finite set. For example if you want your program to keep track of whether it is day or night, you could just make up some rule for yourself and use integers, say 1 represents day and 0 represents night. But then what the other numbers mean? Or you could just use boolean for that (again, with some arbitrary meaning attached to false and true).
enum TimePeriod{
DAY,
NIGHT
}
Enums represent a better alternative by letting you to be explicit about what values mean. This is not just a convenience - being explicit in your intentions is what makes your program readable by others.

C++ routine returning function

I have the following code which work fine. I am trying to understand the syntax. The return statement has std::plus<double>(). The double over here has the return value data type. But the function definition has the return type as std::function<double(double, double)> which indicates two double parameters. How do these two relate to each other?
#include <functional>
#include <iostream>
using namespace std;
std::function<double(double, double)> GetFunction()
{
return std::plus<double>();
}
int main()
{
auto operation = GetFunction();
int a = operation(1, 4);
std::cout << std::plus<>{}(1, 4) << '\n';
return 0;
}
There is an implicit conversion from std::plus<double> to std::function<double(double,double)>, because the former has a member call operator double operator()(double, double). See the documentation for std::function constructors.
In std::function<double(double, double)>:
The first double is the return type of the function. You can remember that by realizing that it's on the left, just like in a normal function definition.
The doubles in parentheses are the parameter types of the function, just like in a normal function definition; minus the parameter names. There are 2 since the plus function takes 2 doubles.
This makes sense if you think about it. The plus function/operator is a binary operator, meaning it takes 2 parameters of a type, and returns a single value of the same type. This is why you only need to specify a single type when you write std::plus<double>; the parameters and the return type must be the same type. It would be error prone and useless to force the caller to specify the same type 3 times.
If your question is, why there is only one double in the template parameter of std::plus but three in std::function, then the answer is this:
For std::plus, both parameters and the returntype always have to be the same, so you only have to specify it once.
std::function on the other hand can hold any function like object with any combination of parameters and returntypes, so you have to basically state each of those types individually.

How to check if value is number in Varnish?

Cookie String Example:
session=9urt2jipvkq77brfrf; MyId=124 ; PageId=134
I'm using Varnish version 4.1. In the following code, I extract the value of MyId (124) and PageId (134) from the cookie string and then check if the values are the same. If it is, return pass and don't serve cache content. The problem is that anonymous visitors will not have these two cookies in place unless they sign up, and it will accidentally pass the condition and not cache because both values will return the same value session=9urt2jipvkq77brfrf with the regsub function. I want to make sure that both values are entirely number. Is there any function handy for that?
Code:
if(req.http.Cookie){
set req.http.MyId = regsub(req.http.Cookie,".*MyId=(\d+).*","\1");
set req.http.PageId = regsub(req.http.Cookie,".*PageId=(\d+).*","\1");
if(req.http.MyId == req.http.PageId){
return (pass);
}
}
There isn't a handy function like "is_integer" or similar. But you can check it with regular expressions.
This will match any sequence of numbers:
req.http.MyId ~ "[0-9]+"
Or you can match only 3 numbers:
req.http.MyId ~ "[0-9][0-9][0-9]"
You can do it in a vmod or inline C. Here is an inline C example testing a header value:
sub vcl_backend_response
{
// Check some value from your backend server response
if (beresp.http.X-MyCustom-Header)
{
C{
syslog(LOG_ERR, "Received a X-MyCustom-Header");
char *val_to_test;
const struct gethdr_s hdr = { HDR_BERESP, "\022X-MyCustom-Header:" };
val_to_test = VRT_GetHdr(ctx, &hdr);
int val_int = atoi(val_to_test); // or whatever C functions
syslog(LOG_ERR, "My int value was: %d", val_int);
}C
}
...
}
Normally you would package all of that inline C into a vmod and make your life easier but it can be useful for testing before moving to a vmod.

boost::shared_* with copy constructor and assignment operator

I have a class that contains a boost::shared_array member. The other members are not dynamic - just a bunch of ints, no pointers. I would expect that the default copy constructor for such a class would be fine.
This is my assumption:
Let's say I have an instance of this class, orig.
orig's shared_array member has a reference count of 1.
Now I create a copy of orig:
copy = orig;
I now expect both copy and orig to have shared_arrays that point to the same underlying memory, each with a reference count of 2.
Is the above correct?
I'm intimidated by various people who warn against the default copy constructor when there is a boost::shared_* member - but I can never find an explanation why the default would/could be bad. For example, here's a comment by someone who says an explicit copy/assignment should be defined, but no explanation why:
https://stackoverflow.com/a/716112/629530
Can someone clarify when a copy constructor and assignment operator need to be defined for a class that contains boost::shared_* (shared_array and shared_ptr) members?
The following class uses the Pimpl Idiom in combination with a shared_ptr:
class location
{
struct impl
{
double _latitude;
double _longitude;
};
std::shared_ptr<impl> _impl;
public:
location(double latitude, double longitude)
: _impl{new impl{latitude, longitude}}
{ }
void move_to(double latitude, double longitude)
{
_impl->_latitude = latitude;
_impl->_longitude = longitude;
}
// ...
};
The code compiles and works. However, there is a strange behaviour:
location london{51.51, 0.12};
location paris = london;
paris.move_to(48.86, 2.35);
std::cout << "London: " << london << '\n'; // prints 48.86/2.35
Changing the copy of an object also affected the original object. In this case, it is better to use std::unique_ptr instead of std::shared_ptr, because we would have been forced to write our own copy constructor.
There are also cases in which the behaviour of std::shared_ptr is desired. Let's add a member variable metric that will be used to calculate the distance between two locations (because there might be different strategies for calculating distances):
std::shared_ptr<metric> _metric;
double operator-(const location& rhs) const
{
return _metric->distance(*_impl, *rhs->_impl);
}
In this case a std::shared_ptr works perfectly, because the metric is not part of the perceived state of the location, and there is no way to change the metric.

Resources