why my code which includes hashfunction and unordered_set uncompilable? - hash

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
struct hashfunction{
size_t operator()(pair<string,int> x){
size_t ret=5381;
for(int i=0;i<x.first.length();i++){
ret=(ret<<5)+(ret)+x.first[i];
}
ret+=x.second;
return ret;
}
};
unordered_set<pair<string,int>,hashfunction> myset;
int main(void)
{
string a="123";
int b= 4;
myset.insert({a,b});
}
I am studying unordered_set and hashfunction. But the code above is not compilable. why not? Anyone can explain why it is not compilable and how to solve this problem?

const is needed after operator()(pair<string,int> x).

Related

Thrust Device Vector iterator location

i am trying to find the index/location of an iterator, i use the thrust::distance(). however, it returns weird value.
the vector size is 10. and when i use this method it returns value of "131" .
here is a fully working example.
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, ""));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(y.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
The iterator it is established with respect to the vector x:
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
^ ^
But you are asking for the distance from this iterator to the beginning of the vector y:
int newsize=thrust::distance(y.begin(),it);
^
That doesn't make sense. There is no defined relationship between it and the vector y.
If you ask for the distance to the beginning of vector x instead, you'll get more sensible results:
$ cat t1244.cu
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/reduce.h>
#include <thrust/extrema.h>
#include <iostream>
#include <iomanip>
#include <thrust/sort.h>
#include <thrust/copy.h>
#include <thrust/random.h>
#include <thrust/unique.h>
#include <thrust/reduce.h>
#include <thrust/iterator/constant_iterator.h>
using namespace std;
template <typename Vector>
void print_vector(const std::string& name, const Vector& v)
{
typedef typename Vector::value_type T;
std::cout << " " << std::setw(20) << name << " ";
thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
}
int main()
{
thrust::device_vector<int> x;
x.push_back(1);
x.push_back(10);
x.push_back(1);
x.push_back(11);
x.push_back(1);
x.push_back(11);
thrust::device_vector<int> y(10);
print_vector("Original",x);
thrust::sort(x.begin(),x.end());
print_vector("sort",x);
thrust::device_vector<int>::iterator it=thrust::unique(x.begin(),x.end());
std::cout<<*it<<std::endl;
//int newsize=it-y.begin();
int newsize=thrust::distance(x.begin(),it);
cout<<"nsz:"<<newsize<<endl;
return 0;
}
$ nvcc -o t1244 t1244.cu
$ ./t1244
Original 1 10 1 11 1 11
sort 1 1 1 10 11 11
10
nsz:3
$

Why does destructor cause segmentation fault?

All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
All I do is construct a BNode object. The debugger says that the constructor is causing a segmentation fault. Does anyone know what the problem is here?
#ifndef BTree_H
#define BTree_H
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
template <typename T>
class BNode
{
public:
BNode();
BNode(int M);
~BNode();
int keyCount;
BNode *pointers;
T *keys;
};
template<typename T>
BNode<T>::BNode()
{
}
template<typename T>
BNode<T>::BNode(int M)
{
pointers = new BNode<T>[M];
keys = new T[M - 1];
}
template<typename T>
BNode<T>::~BNode()
{
delete[] pointers;
delete[] keys;
}
#endif
int main()
{
BNode<int> obj(5);
return 0;
}
You are deleting an array of pointers and keys, whereas you never defined these to be arrays.
Both of these are pointers.
You need to be freeing memory from the pointers, not arrays.
Try this:-
delete myPointer;
myPointer = NULL;
NOTE: If you're using C++, read about smart pointers. They'll come in handy!

smart pointer to manage socket file descriptor

A smart pointer clears the memory if the pointer gets out of scope. I wanted to adapt this to a file descriptor, like a socket. There you need a user defined deleter, because close() is the function to free the file descriptor (fd) resources.
I found this useful page, unfortunately, most approaches did not work for me. Below is a working solution I found up to now, which is a little nasty. Because uniqu_ptr expects a pointer I created int *fd to store the fd value, therefore, I had to close(*fd) and delete fd in my custom deleter.
(1) Is there a better way?
Options A and B, which are based on the hints provided by the mentioned web page, are much nicer but causing odd compiler errors.
(2) Does anyone know how to correctly use these alternatives?
I'm using Qt Creator 3.0.1 with CONFIG += c++11 option and gcc version 4.8.2
#include "ccommhandler.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <qdebug.h>
//for Option A and B
struct CloseHandleDeleter {
typedef int pointer;
void operator()(int handle) const
{
}
};
//custom deleter, working
class MyComplexDeleter
{
public:
MyComplexDeleter() {}
void operator()(int* ptr) const
{
qDebug() << "Deleting ";
close(*ptr);
delete ptr;
}
};
CCommHandler::CCommHandler()
{
//Option A doesn't work
//std::unique_ptr<int, CloseHandleDeleter> file( socket(AF_INET, SOCK_STREAM, 0) );
//Option B doesn't work
//std::unique_ptr<int, int()(int)> filePtr( socket(AF_INET, SOCK_STREAM, 0) , close);
MyComplexDeleter deleter;
int *fd = new int;
*fd = socket(AF_INET, SOCK_STREAM, 0);
std::unique_ptr<int, MyComplexDeleter> p( fd , deleter);
}
Edit:
The posted answer by Nevin is right, it solves my initial problem.
The comment of learnvst caused to rethink my problem, and I have to say I may made it much more complex than needed, because the following simple class should also solve my problem of auto-free the memory of a resource or as in my case, to close the file descriptor:
class SocketHandler
{
int _fd;
public:
SocketHandler(int FD):_fd(FD){}
~SocketHandler() { if(_fd!=-1) close(_fd); }
operator int() const { return _fd; }
};
Because fd isn't a pointer, I wouldn't try to pigeonhole it into unique_ptr. Instead, create a custom class whose interface is based on unique_ptr, as in (caution: totally untested):
class unique_fd
{
public:
constexpr unique_fd() noexcept = default;
explicit unique_fd(int fd) noexcept : fd_(fd) {}
unique_fd(unique_fd&& u) noexcept : fd_(u.fd_) { u.fd_ = -1; }
~unique_fd() { if (-1 != fd_) ::close(fd_); }
unique_fd& operator=(unique_fd&& u) noexcept { reset(u.release()); return *this; }
int get() const noexcept { return fd_; }
operator int() const noexcept { return fd_; }
int release() noexcept { int fd = fd_; fd_ = -1; return fd; }
void reset(int fd = -1) noexcept { unique_fd(fd).swap(*this); }
void swap(unique_fd& u) noexcept { std::swap(fd_, u.fd_); }
unique_fd(const unique_fd&) = delete;
unique_fd& operator=(const unique_fd&) = delete;
// in the global namespace to override ::close(int)
friend int close(unique_fd& u) noexcept { int closed = ::close(u.fd_); u.fd_ = -1; return closed; }
private:
int fd_ = -1;
};

Compile error with boost bind in std::find_if

Consider this snippet:
#include <vector>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
template<typename PODType>
class SomeClass
{
public:
SomeClass() : m_pred(boost::bind(&SomeClass<PODType>::someMethodA, this, _1))
{
}
bool someMethodA(const PODType& elem)
{
return false;
}
bool someMethodB(const std::vector<PODType>& vec)
{
return (std::find_if(vec.begin(), vec.end(), m_pred(_1)) != vec.end());
}
private:
boost::function<bool(PODType)> m_pred;
};
int main(int argc, char* argv[])
{
SomeClass<int> obj;
std::vector<int> v;
obj.someMethodB(v);
return 0;
}
The compiler gives
error: no match for call to '(boost::function<bool(int)>) (boost::arg<1>&)'
note: no known conversion for argument 1 from 'boost::arg<1>' to 'int'
for the line return (std::find_if(vec.begin(), vec.end(), m_pred(_1)));
I'm trying to call someMethodA within the member predicate for the find_if calls.
Just pass m_pred, no need for m_pred(_1).

how to call a function of c++ file in .m file?

I have a header file test.h
#ifndef __visibilty_test__test__
#define __visibilty_test__test__
#include <iostream>
using namespace std;
class test{
public:
void print(string s);
};
#endif
and test.mm
#include "test.h"
using namespace std;
void test:: print(string s){
cout << s << endl;
}
now I want to call print function in my AppDelegate.m file in an iOS Application. Can anyone help me?
Thanks in advance
Rename AppDelegate.m to AppDelegate.mm.
Call the method as you would in C++:
test t;
t.print("Hello");
Your object:
#include <iostream>
using namespace std;
class test
{
public:
void print(string s)
{
cout << s << endl;
}
};
call from mm file
test *t = new test;
t->print("hello");