mercredi 28 février 2018

Subtraction of iterators for unordered_set does not work

Trying to find the index of an element in unordered set. Found that subtraction (operator '-') of iterators as one way of doing it.

vector<int> twoSum(vector<int>& nums, int target) 
{
    unordered_set<int> comp; 
    vector<int> res;
    for(int i = 0; i<nums.size(); i++)
    {
        //unordered_set<int>::iterator it = comp.find(nums[i]);
        if (comp.find(nums[i])!=comp.end())
        {
            //int pos = distance(comp.begin(), comp.find(nums[i]));
            auto pos = comp.find(nums[i]) - comp.begin();
            res.push_back((int)pos);
            res.push_back(i);
        }
        comp.insert(target-nums[i]);
    }
    return res;
}

But I get compile error on line with auto pos:

no match for 'operator-' (operand types are 'std::unordered_set<int>::iterator {aka std::__detail::_Node_iterator<int, true, false>}' and 'std::unordered_set<int>::iterator {aka std::__detail::_Node_iterator<int, true, false>}')

Have included iostream, iterator and unordered_set. Please advice. Thanks

Visual Studio gdiplus Rendering Images

I am trying to use the gdiplus library in Microsoft Visual Studios 2017 to render an image on the desktop of my Windows 10 computer. I have loaded the image that I want to render into the program with the following lines:

GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

Image* image = Image::FromFile(_T("C:\\whatever\\Image00.png"));

Graphics *pGraphics = new Graphics(image);

pGraphics->Clear(0xffffffff);

Rect sizeR(0, 0, image->GetWidth(), image->GetHeight());

pGraphics->DrawImage(image, sizeR, 0, 0, (int)image->GetWidth(), (int)image->GetHeight(), UnitPixel);

The "DrawImage" function did not render anything to my screen, however. Does anyone know how I can proceed from here? The image needs to be full screen. I do not want to call on Microsoft Paint or Photo Viewer to render this image, I want the program to render the image by itself.

Find number x if given k n of ciphers of x and sum of the number x+x/10+x/100+x/k?

Is there an algorithm that can solve this kind of task? Sum goes up to 10^15. I found formula [9*10^k-1/[10*(10^k-1)]

Visual Studio C++ Rendering Images Library

I am trying to write code that displays a full screen image on the desktop of a Windows computer, and to do this, I want to find a Microsoft equivalent to the library OpenCV. Does there exist some Microsoft built-in library that includes a way to decode and render images on the user's screen? I want the program to decode and render the images itself, rather than call on Paint or Microsoft Photo Viewer to do it for me.

I am using Visual Studio 2017.

C++ class method to stop current thread

I have a thread pool that reads command objects from a queue. Each command object is an implementation of an abstract command class with a single execute() method, i.e. the command pattern.

I want to implement a command that makes the thread stop itself, i.e. the execute() method stops the current thread. Usually I would just return from the thread function, but I need to stop the thread from the execute() method.

What is the best way to do this? I can use detach or destroy, but the main program calls join on all threads and I’m not sure if it will work. Assume everything the thread has access to has been unlocked.

Cmake compile errors. How to linke shared libraries?

I am writing a larger cmake file, where I want to link two shared libraries to a main.

CUDA_ADD_LIBRARY(cudnn_stereo SHARED ${HEADERS} ${SOURCES})
TARGET_LINK_LIBRARIES(cudnn_stereo ${CUDA_LIBRARIES} ${EXTERN_LIBS} cnpy)

cuda_add_library(stereo SHARED ${SRC_STEREO_LIB})
    TARGET_LINK_LIBRARIES(stereo ${IMAGEUTILITIES_LIBRARIES} ${LIBS}
    ${OpenCV_LIBRARIES} ${OpenCV_LIBS} cudnn_stereo ${SLACK_PROP_LIBRARY} ${ITK_LIBRARIES} cnpy png)

cuda_add_executable(stereo_img ${SRC_STEREO_IMG})
TARGET_LINK_LIBRARIES(stereo_img  ${IMAGEUTILITIES_LIBRARIES} ${EXTERN_LIBS} cudnn_stereo  cnpy png)

I created a new folder build. Then, cd build, cmake .. and make -j. I get this errors during compiling:

[ 60%] Linking CXX shared library libstereo.so                                                                                              
[ 80%] Linking CXX executable stereo_img                                                                                                    
[ 80%] Built target stereo                                                                                                                
libcudnn_stereo.so: undefined reference to `error_stream::error_stream(char const*)'                                                                                                                                 
libcudnn_stereo.so: undefined reference to `error_stream::~error_stream()'                                                                     
libcudnn_stereo.so: undefined reference to `typeinfo for error_stream'                                                                      
libcudnn_stereo.so: undefined reference to `error_stream::set_file_line(char const*, int)'                                                                      
libcudnn_stereo.so: undefined reference to `error_stream::error_stream(error_stream const&)'                                                                     
libcudnn_stereo.so: undefined reference to `demangle[abi:cxx11](char const*)'                                                                   
libcudnn_stereo.so: undefined reference to `error_stream::error_stream()'                                                                     
collect2: error: ld returned 1 exit status 

Any ideas, how to get rid of these errors?

Trampolining a non-static C++ member as a registered C callback

I am writing a C++ freeGlut 3.0.0 application. I am having trouble registering a generic callback signature (hopefully a function pointer template argument) with a non static member function that matches the signatures of the declared free-glut callbacks.

To this end, with the help from this answer, I put together a live Coliru working example that demonstrates how to register a C++ non static method as a callback with a C application (in my case the freeGlut library). A more modern C based normally would allow the callback registration to specify an optional void* user parameter which could be bound as a this* to the object with the callback member function as explained here. FreeGlut does not allow this in their callback registration API, so it seems that I will need to use a trampolining technique that I am not very familiar with.

My example uses a hard coded callback type alias callback_t with a specific signature. The place where I need help is to allow a more generic version of the callback type - perhaps the trampolining approach described in this [live coliru demo][5] could be used to modify my example as it takes a more generic approach. I suspect I need to change the callback_t below to somehow allow variadic arguments and a templated return type but I don't know how.

using callback_t = std::add_pointer<int(const char *, int)>::type;
using MyFTWFunction = std::function<void(unsigned char, int, int)>;

template <MyFTWFunction *callback>
class callback_binder {
public:
    static void trampoline(unsigned char key, int x, int y) {
        return (*callback)(key, x, y);
    }
};

// This matches the signature of the callbacks in freeGlut
extern "C" {
    // register the keyboard callback here
    void glutKeyboardFunc(void(*callback)(unsigned char ch, int x, int y)) {
        callback('S', 3, 4);
    }
    // register Reshape callback here
    void glutReshapeFunc(void(*callback)(int, int)) {
        callback(1, 2);
    }
    // register Display callback here
    void glutDisplayFunc(void(*callback)(void)) {
        callback();
    }
}

I need help making it more generic such that I can also register other callbacks.

How can we convert `boost::asio::streambuf` or `boost::asio::array` to int or long?

I see that boost::asio::streambuf can be converted to some stream and converting it to a integer is done by streambuf->stringstream->string->int;

Is there any way to do streambuf->int?

Sequential communication failed with boost::asio::streambuf in binary way?

Using boost::asio, I'm coding network stuff. I tried to build a simple send-and-receive-string protocol. The sender first send the string size to the receiver. Then the sender sends the actual string to the receiver.

In particular, I designed the following two protocols.

  • A sender holding a string sends it to a receiver. Upon receiving it, the receiver shows the string.

  • Execute above protocol sequentially (two times).

I built the above protocols as shown below: If I execute this protocol once, that works fine. However, if i execute this protocol more than once (e.g. two times), the string size that the receiver receives gets wrong.

First time : 1365 bytes.

Second time : 779073 bytes. (just read not 779073 but 7790)

I found that os << data_size is not done in a binary way. "779073" is just sent as 6 bytes string. But the receiver just reads 4bytes of it. How to send a binary data and to receive a binary data using boost::asio and boost::asio::streambuf?

Receiver

// socket is already defined
// ** first step: recv data size
boost::asio::streambuf buf;
boost::asio::read(
   socket,
   buf, 
   boost::asio::transfer_exactly(sizeof(uint32_t))
);
std::istream is(&buf);
uint32_t read_len;
iss >>  read_len;

// ** second step: recv payload based on the data size
boost::asio::streambuf buf2;
read_len = boost::asio::read(socket, buf2, 
boost::asio::transfer_exactly(read_len), error);
cout << "  read "<< read_len << " bytes payload" << endl; 
std::istream is_payload(&buf2);
std::string str;
is_payload >> str;
cout << str << endl; 

Sender

// socket is already defined
string str=...;   // some string to be sent
// ** first step: tell the string size to the reciever
uint32_t data_size = str.size();
boost::asio::streambuf send_buf;
std::ostream os(&send_buf);
os << data_size;
size_t sent_byte = boost::asio::write(socket, send_buf.data());
cout << sent_byte << endl; // debug purpose

// ** second step: send the actual string (payload)
sent_byte = boost::asio::write(socket, boost::asio::buffer(reinterpret_cast<const char*>(&str[0]), data_size));
cout << sent_byte << endl; // debug purpose

Use variable from another C++ source file with a twist

I'm using one source file to create another and then from first file call a bash script to compile the second. Is it possible to access the variables of second file in the first?

// File 1: type.cpp
#include<..>
....
int main () {
  int var;
  // Open another file subtype.cpp via file input-output
  // directly write to another file subtype.cpp
  ...
    ofs << "int main () { \n";
    ofs << "printf(\" Hi \"); \n";
    ofs << "int subvar;"
    ofs << "return 0; \n }"
  ...
  // Call the bash script to compile the subtype.cpp file. 
  system ( bash.sh );  

  // Access the variable "subvar" here !
  var = subvar;
  return 0;
}  

I can see that using extern i can accomplish the task but for that the file header of second has to be included in first but file is only created after running first.

What i have tried:

I can think a direct way (a little ugly) of accessing the value of the variable by writing variables value (subtype.cpp) it into third file [subvar_value.txt] and then read the third file by first file (type.cpp). Is there a direct way i can access the variable subvar from first.

Bad Access Exception when printing linked list using templates

As I have just learned templates in C++, I started to practice it. I am at the beginning of the implementation of a Linked List using templates and I have been having an error on Xcode, where it states: "Thread 1: EXC_BAD_ACCESS(code=1, address=0x9)". In my other compiler, it says it is a segmentation fault, but I cannot find the cause of it. What might be the reason of this error?

#include <iostream>

using namespace std;

template <typename T> struct Node{

    T value;
    Node * ptr;
};

template <typename T> class LinkedList {
public:

    LinkedList(const T & element);
    T & push(const T & element);
    T & pop(const int index);
    int get_size() const { return this->_size; }
    void printll();

private:
    LinkedList(){};
    struct Node<T> * head;
    int _size;
};

template <typename T> LinkedList<T>::LinkedList(const T & element){

    struct Node<T> new_node;           
    new_node.value = element;
    new_node.ptr = nullptr;

    this->head = &new_node;            

    this->_size = 1;                    
}

template <typename T> void LinkedList<T>::printll(){

    if(this->head != nullptr){

        Node<T> * temp = this->head;
        while((*temp).ptr != nullptr){  // Error here.
            cout << (*temp).value << " ";
            temp = temp->ptr;
        }
        cout << (*temp).value << endl;
        cout << endl;

    }else {
        cout << "The list is empty!" << endl;
    }
}

int main(int argc, char** argv){

    LinkedList<int> l1(5);

    l1.printll();

    return 0;
}

Need help in calculating minimum pair

I have a problem like this:-

enter image description here

Description of the problem:- There are M no. of boys and N no. of girls. The boy B1 can match only with that girl who has minimum number of fights with. All boys have fought with all the girls. One boy can match up with one girl only based on minimum number of fights as mentioned before. For example:- if Boy B1 is matched up with girl G2 then no other boy can match up with girl G2 and vice versa. The input will be in matrix form like this:-

std::vector<std::vector<float>> input = {
  {1.0f,0.03f,1.0f},
  {0.04f,1.0f,0.2f},
  {0.05f,0.01f,0.03f},
  {1.0f,0.05f,0.01f}
}; // I know the fight value is in float, but please take this for granted

Output should be the pair containing row and column like this:-

[1,0],[2,1],[3,2]

I need the algorithm to calculate this type of problem. Thank you.

Idiom for CUDA class static member in device code?

So, I've got a C++14 library that I'm porting to CUDA 9. I actually have (I think) a pretty good knowledge of CUDA, but I haven't done any direct work in it since CUDA 6.

Typically, I use a lot of templates and small classes in my code. It's surprised me that one still cannot have a static __device__ class member in CUDA 9, but global variables are fine. Is there a good idiom or workaround for this? What do people typically do?

Why is boolean printed as a number? [duplicate]

This question already has an answer here:

I am a bit curious why my code prints a number instead of bool value.

class fb
{
public:
    bool p;

    void
    func()
    {
        memset(&(p), 4, 1);
    }
};

int
main()
{
    fb f;

    f.func();

    std::cout << f.p << std::endl;

    return 0;
}

My code prints number "4" and I am not really sure why this happens. Can you please explain me what is wrong with my code? I was expecting that result will be "true".

Thank you

for_each not returning (boolean) value

I have a program to verify if Ip address entered as string is an valid IPv4 format. The problem I am facing is that I'm not able to return (exit) function once I detect error. As per cppreference documentation for_each returns UnaryFunction. I tried using any_of and all_of but they require me using an loop (range-based loop) inside my lambda function which I'm trying to avoid. Am I missing something or it is not possible to return value in for_each.

vector<string> ipExplode;
string ip;
bool    inValidIp = false;
cout << "Server IP : ";
cin >> ip;
trim(ip);
ipExplode = explode(ip, '.');
if(not for_each(ipExplode.begin(), ipExplode.end(), [](const string& str) -> bool{
    int32_t ipNum;
    if(regex_search(str, regex("\\D+")))
        return false;
    try
    {
        ipNum = stoi(str);
        if(ipNum < 0 or ipNum > 255)
            return false;
    }
    catch (std::exception& ex)
    {
        return false;
    }
}))
    return false;

C++: Create integer vector of infinities

I'm working on an algorithm and I need to initialize the vector of ints:

std::vector<int> subs(10)

of fixed length with values:

{-inf, +inf, +inf …. }

This is where I read that it is possible to use MAX_INT, but it's not quiete correct because the elements of my vector are supposed to be greater than any possible int value.

I liked overrloading comparison operator method from this answer, but how do you initialize the vector with infinitytype class objects if there are supposed to be an int?

Thank you.

C++ Crash - Memory corruption

I have an c++ application which crash when i use :

_p_event_translator = shared_ptr<EventTranslator>(new EventTranslator(_id, _p_event_queue, dump_events)); 

i get error : * Error in `/opt/oss/bin/hua_m2000_am': malloc(): memory corruption: 0x0000000000d4ac90 *

I debugged with "gdb" as shown below : enter image description here

I m a beginner in C++, i have some difficulties to understand and resolve the problem.

Thanks so much for your helps ^^

(Programming) Automatically Launch Computer?

How can I Launch my computer automatically? and with what's programming language? I have found on the internet. there are some way(code-by c#, c++) to wake up computer from sleep state. But no way to power computer on from shutdown state. does any body have a suggestion?
Many thanks!

How to pass a vector (or similar) into a variadic template

Suppose I have the following code:

template <typename... Args>
void DoSomething(const Args&... args)
{
    for (const auto& arg : {args...})
    {
        // Does something
    }
}

Now let's say I'm calling this from another function, and want to pass in an std::vector (or somehow modify the vector in such a way that it could be used with this)

void DoSomethingElse()
{
    std::vector<int> vec{50, 60, 25};
    DoSomething(??); // <- Ideally I'd pass in "vec" somehow
}

Is there anyway to do this? I've also considered using std::initializer_list instead of variadic templates, but the issue still remains that I have no way to passing in existing data.

Thank you.

mardi 27 février 2018

How do you create a container class that include a stack?

I am designing a container class called Process for a project in one of my classes. Process has a string that is the name of the process and stack ptr that points to a stack of a class called Function. Function is a class that has a string that is its name and a bool related to when it needs to be removed. My problem is that I can add items to the stack when I am using a stack on its own, however, I am having trouble doing so within Process. I can add an item to the stack but it disappears after the function ends even though it isn't included in that function. I think I have some sort of scope problem but I am not sure what it is. I created a smaller program that I have been trying to test the problem in. I attached all of those files here. If you make the program and run it as ./Test it will run.

How to count number of times recursion is called? (Computing number of multiplications for x^n)

I'm having some trouble figuring out how to increment count (mults in my code) in such a way that power2's counter is equivalent to power1's. My program compares the efficiency of computing x^n in different ways. I've looked up solutions on how to count the number of times a recursion calls itself but no matter what method I implement I get the incorrect output. Any help or guidelines would be appreciated!

This is part of my code so far (power1 has the right counter):

template <class T>
T power1(T x, unsigned int n, unsigned int& mults)
{
mults = 0;

if (n == 0)
    return 1;
else if (n == 1)
    return x;
else
{
    T total = 1;

    for (int i = 0; i < n; ++i)
    {
        total = total * x;
        ++mults;
    }
    mults -= 1;

    return total;
}
}


template <class T>
T power2(T x, unsigned int n, unsigned int& mults)
{
++mults;

if (n == 0)
{
    mults = 0;
    return 1;
}
else if (n == 1)
    return x;
else
{
    if (n > 1)
    {
        return (x * power2(x, n - 1, mults));
    }
}

return x;
}

This is part of my output:

Test for integer base:
2^0 = 1: mults1 = 0, mults2 = 0
2^1 = 2: mults1 = 0, mults2 = 1
2^2 = 4: mults1 = 1, mults2 = 3
2^3 = 8: mults1 = 2, mults2 = 6
2^4 = 16: mults1 = 3, mults2 = 10
2^5 = 32: mults1 = 4, mults2 = 15
2^6 = 64: mults1 = 5, mults2 = 21
2^7 = 128: mults1 = 6, mults2 = 28
2^8 = 256: mults1 = 7, mults2 = 36
2^9 = 512: mults1 = 8, mults2 = 45

Incorrect number of template arguments with decltype.

In the below program when compiling it complains that there should be 2 template arguments but there is only 1.

template<typename T, typename U = T, 
    typename = std::enable_if<std::is_convertible<std::decltype(int()), int>::value>::type>
void func(T t, U u){}

However the below code compiles,

template<typename T, typename U = T, 
    typename = std::enable_if<std::is_convertible<int, int>::value>::type>
void func(T t, U u){}

I am wondering what the difference between the two is and how I might make this code compile.

c++ not validating string input

int main() {
    Population town;
    int population;
    int numBirths, numDeaths;
    string city, intTest;
    bool isValid = true;

    do {
        cout << "Enter name of city: ";
        cin >> city;
        getline(cin, city);
        for (int i = 0; i < city.length(); i++) {
            if (!(isalpha(city[i]))) {
                isValid = false;
            }
            else {
                isValid = true;
                break;
            }
        }
    } while(!isValid);

Its not properly checking to see if the input is a string or not. Not sure whats wrong with the code.

C++ dereferncing a instance variable pointer

Hello,

im trying to learn C++ at the moment but i'm struggeling with pointers i wrote a class for a simple list with the instance variables:

LinkedList *next;
int val;

However when i'm trying to dereference and get the value of next i get syntax error. The question is how can i derefernce the pointer correctly? If i don't use the pointer "this".

My try was:

LinkedList i;
i.*next;

and:

i.(*next);

Thank you for your help.

Getting value of member depending on underlying object type

I have two structs - Foo1 and Foo2. Both have the same member called _b, but at different offsets.

struct FooBase { };

struct Foo1 : FooBase
{
    int _a = 2;
    int _b = 1;
};

struct Foo2 : FooBase
{
    int _b = 2;
};

struct Wrap
{
    Wrap(const FooBase& x) : _x(x) { }
    FooBase _x;
    int GetValue() { return /* MISSING */; }
};

I have a wrapper class called Wrap. I am looking for a way to return the value of _b without using virtual functions in the foo classes, since I can't change their size anymore.

Wrap x = Foo1();
int a = x.GetValue(); // should return 1

Wrap y = Foo2();
int b = y.GetValue(); // should return 2

Any ideas? I posted one approach in the comments but curious for a better solution.

C++ Computing block sum for an arbitrary region in an image

I wonder what is the most affective way to solve the following problem: (If there is a name for this problem, I would like to know it as well)

[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 0 1 0 1 1 1;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]

If I have an image where I am interested in the following pixels marked by 1. In an image I want to calculate a sum around this block. A sum of block is easy to calculate from an integral image but I don't want to do it for the whole image, since there is a lot of unnecessary computation.

One option that I can come up with is to search the minimum and maximum in horizontal and vertical directions and then take a rectangular portion of the image enlarged so that it will covered the block portion. For example +2 pixels each directions, if the block size is 5. But this solution still includes unnecessary calculation.

If I had a list of these indices, I could loop through them and calculate the sum for each block but then if there is another pixel close by which has the same pixels in its block, I need to recalculate them and If I save them, I somehow need to look if they are already calculated or not and that takes time as well.

Is there a known solution for this sort of a problem?

C++ Overloading operator- (unary minus) as member function? [duplicate]

This question already has an answer here:

I have implemented a unary minus operator as a non-member function.

template<typename T>
vector3<T> operator-(const vector3<T> &v)
{
    //return vector3<T>(-v._x_, -v._y_, -v._z_);
    return vector3<T>(-v.GetX(), -v.GetY(), -v.GetZ());
}

This implementation looks out of place compared to the other functions I have written as the variables _x_,_y_ and _z_ are private, and therefore I have to use the Get methods to access the member variables.

I could declare this function as a friend. However this does not seem like a particularly good solution.

Is it possible to implement unary minus as a member function, thereby being able to access the members without the Get methods? It seems to me that such a thing would not make sense, becuase as this is a unary operator, what would the argument be? Would it simply have to be empty?

C++ sharing object between two class


Suppose I have two class: FirstContainer and SecondContainer
They hold the same reference (pass in their constructor) to the class ThirdContainer.
FirstContainer and SecondContainer have the following methods:
- addMemberToThirdContainer
- delMemberOfThirdContainer
- getThirdContainerMembers

When the ThirdContainer is modify, I want the two others to update using getThirdContainerMembers.
For this purpose I use the observer/listener pattern.

ThirdContainer has a list of listener and a method: addNewListener. FirstContainer and SecondContainer register by doing: mThirdContainer.addNewListener(this);

I'm not sure this is the good way to do this, I'm new to oriented object.
What are my other possibilities to achieve something like that ?
I'm not attached to anything I stated, it's just here because I have hard time to explain what I want to do. I hope it's clear. Thanks for the help,
Best,

Parse cmd input with fewer lines of code

Can I do (1) and/or (2) better with something from algorithm for example? By better, I mean with more readable code and with fewer lines of code. I really don't like that I need so many lines of code to do this... Thank you.

for (int node = 0; node < numberOfNodes; ++node)
{
    cout << node << ": ";
    // (1)
    string input;
    getline(cin, input);
    istringstream ss(input);

    // (2)
    vector<int> adjacencyList;
    int adjacent;
    while (ss >> adjacent)
    {
        adjacencyList.push_back(adjacent);
    }
    graph[node] = adjacencyList;
}

C++11 activation with

I'm using a Python library, named PyPHS, specialized in physical modeling. To save computation during the simulation, it implements a C++ code generation feature. It uses CMake to generate an executable of a particular simulation.

It is implemented in C++ 11.


Issue

In the CMakeLists.txt file, the C++ 11 feature is activated by the following line:

target_compile_features(<project_name> PUBLIC cxx_std_11)

On my computer (CMake 3.5.1 & Ubuntu 16.04.4 Xenial Xerus), CMake throws an error: this feature is unknown:

-- The CXX compiler identification is GNU 5.4.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMake Error at CMakeLists.txt:31 (target_compile_features):
  target_compile_features specified unknown feature "cxx_std_11" for target
  "dampedosc".
```

-- Configuring incomplete, errors occurred!
See also "/home/victorw/git/vocal-phs/python/output/dampedosc/CMakeFiles/CMakeOutput.log".

This error has not been encountered on other installs (Debian 8, Mac OSX or windows 7)

Fix

I’ve changed the CMakeLists.txt template. Here is the link to the commit, on my own fork of PyPHS.

I’ve replaced the target_compile_features(<project_name> PUBLIC cxx_std_11) by set (CMAKE_CXX_STANDARD 11)


Question

What is the difference between the two commands? What are your insights on this matter? Did I forget to mention some information?

Thank you for your answers!

How to test if an std::function

I am currently writing a template class that takes a Signature template parameter and stores a std::function internally.

template <class Signature>
Impl
{
    std::function<Signature> f;
};

This seems to work quite OK, except when the Signature template parameter is not valid, where the compiler fails with some template instantiation error in std::function.

Now because Impl clients do not need to know the internals of Impl, it would be better to output some human readable message to the fellow developer that will use Impl stating that the Signature parameter is invalid.

Using a is_invocable trait class, something like :

static_assert(is_invocable<Signature>::value, "Template parameter Signature is invalid");

When attempting to write such a trait class, I've come up with this :

template <class Signature>
struct is_invocable : std::false_type
{};

template <class Signature>
struct is_invocable <std::function<Signature>> : std::true_type
{};

This does not seem to work however, because is_invocable does not want to check if Signature is std::function but rather if it is possible to construct a std::function<T> with T being the template parameter Signature.

How would it be possible to write a is_invocable class ?

Note: c++17 is not available.

Calling processing constexpr at runtime. C++

Please see the code below:

#include <iostream>

constexpr int f(int a, int b)
{
    return a<b? a : throw std::out_of_range("out of range");    
}

int main() 
{
    try
    {
        int n = 0;
        f(5, n);
    }
    catch(const std::exception& ex)
    {
        std::cout<<"Exception caught"<<std::endl;
        std::cout<<ex.what()<<std::endl;
    }
}

I know that constexprt functions are processed at compile time. So how it came that I can pass a "runtime" local varialbe to it and use it in try-catch block again in runtime? Maybe I am missing smth regargind constexprt functions?

How to use make_heap to create a min heap in c++

How do I create a a min heap using the make_heap method in <algorithm>

From the documentation it says, we can pass in a third argument Compare comp that is a

Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to be less than the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

So I tried passing in a function object as follows

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>

using namespace std;

struct myComp {

    bool operator() (const pair<int, char>& lhs, const pair<int, char>& rhs) {
        return lhs.first > rhs.first;
    }
};

int main() {
    vector< pair<int, char> > Q;
    Q.push_back( pair<int, char>(10, 'c') );
    Q.push_back( pair<int, char>(123, 'a') );
    Q.push_back( pair<int, char>(2, 'd') );
    Q.push_back( pair<int, char>(9, 'f') );
    Q.push_back( pair<int, char>(81, 'b') );
    Q.push_back( pair<int, char>(4, 'e') );

    make_heap(Q.begin(), Q.end(), myComp);

    pop_heap(Q.begin(), Q.end());

    cout << Q.back().first << ", " << Q.back().second << endl;
    Q.pop_back();

    return 0;
}

and I am getting this following error

jdoodle.cpp: In function 'int main()':
jdoodle.cpp:25:38: error: expected primary-expression before ')' token
  make_heap(Q.begin(), Q.end(), myComp);
                                      ^

I don't really understand what this means, what am I doing wrong?

What are the references for understanding the different ways of initialization in cpp

I went through multiple ways of initializing objects/variables in cpp like using assignment operator, in parenthesis and in curly braces. Is there differences associated with all this mechanism of initialization and what is the reference to understand about the different initialization mechanism.

Should be std::set

I see that map have a const key on value_type but set not work the same way.

If std::map<T>::value_type are std::pair<const Key, T> would std::set<T>::value_type be const Key?

What is lambda functions type? C++

See my code:

#include <iostream>
#include <typeinfo>

int main() {
    auto x = [](int a, int b) -> bool{return a<b;};
    std::cout<<typeid(decltype(x)).name()<<std::endl;
}

And this is printing Z4mainEUliiE_. Can anyone explain whay? And what is the actual type of x??

Accessing pointers after erasing from Map

The sample scenario in my code implementation is as follows

I have a map defined as map<int,map<int,object*>*> . The inner map which is in heap has a object pointer.

The scenario is,

After using(processing) all the elements in the inner map. I will erase the inner map contents using iterator. But the object* will not be deleted. I will use the object pointer further after erasing the key from the map.

My question is will that object* exist even after erasing it's presence in the map. As far as my understanding , yes the object is in heap and it can be used even after the erase in map. But i am facing random crash in the process after few minutes of execution. This makes me to post the question here.

multimap<ULONG, Class*>::iterator it_top3 = InnerMap->begin();
if (InnerMap->size() >= classLimit)
{
    if (it_top3->first <= ClassObj->m_classSize)
    {
        if (it_top3->second != NULL)
        {
            delete it_top3->second;
            it_top3->second = NULL;
        }
        InnerMap->erase(it_top3);
        InnerMap->insert(pair<ULONG, Class*>(ClassObj->m_classSize, ClassObj));
}

Secondly , On analyzing debug diag the line it_top3->second = NULL; points as the crash point with access violation exception. What would be possible reason for the crash here.?

C++ switch in loop goes to default before running again

My first program in C++ is a command line survival game. I have a switch statement in a while loop, but it always goes through once and runs the default choice before getting the users input. Here's the relevant code:

int menu() {
    while (true) {
        char choice = getChoice();
        switch(choice) {
            case 'p':
            {
                system("clear");
                Arena arena(player, difficulty);
                arena.play();
            }
                break;
            case 'u': 
            {
                system("clear");
                player.save();
                player.init();
            }
                break;
            case 'd': 
            {
                system("clear");
                changeDifficulty();
            }
                break;
            case 'q':
            {
                system("clear");
                return 0;  // return menu(); in main()
            }
            default:
            {
                system("clear");
                cout << nInvalid option! Press a key to choose: p, u, s, or q\n\n";
                break;
            }
        }
    }
}

getChoice Function

char getChoice() {

    cout << "      Main Menu\n";
    cout << "---------------------\n";
    cout << "p - play game" << endl;
    cout << "u - change user" << endl;
    cout << "d - change difficulty" << endl;
    cout << "q - quit\n" << endl;

    char choice = getchar();
    return choice;
}

Everything works fine after it goes through once and runs the code from the default option. Here's what I get every time the program re-enters this loop:

Invalid option! Press a key to choose: p, u, s, or q                                                                                                                                               

      Main Menu                                                                                                                                                                                    
---------------------                                                                                                                                                                              
p - play game                                                                                                                                                                                      
u - change user                                                                                                                                                                                    
d - change difficulty                                                                                                                                                                              
q - quit   

Thanks for any help in advance!

lundi 26 février 2018

move semantics with temps allocated with new

I'm just wondering if move semantics are restricted to syntax style B. More specifically, with style B the object is created on the stack and moved. With style A, the object is created on the heap, but it seems can't be moved.

The question very specifically is, can you use move semantics such that the temp is created with NEW? If so, how?

//move c'tor
A(A&& other) : num(other.num), s(other.s){
   other.num = 0;
   other.s = nullptr;     //dyn alloc obj
}

If you do this, it doesn't work (syntax style A).

A a2(new A("blah"));        //error
A a2(move(new A("blah")));  //error

This is ok (syntax style B)

A a2(A("blah"));            //uses c'tor
A a2(move(A("blah")))       //uses move c'tor

compile error with std::reference_wrapper "has no member named" when used with class

So I've found this fancy stuff "std::reference_wrapper" in C++11 which I found could be useful in future program development. I played with it for a bit and I thought it could replace good-old reference in some cases for better usage, until I bumped into the following error:

#include <iostream>
#include <functional>

class testbench {
public:
    int ownerid = 5;
    bool camper = false;
};

class testing {
public:
    testing(testbench &x);
    int quack = 3;
    std::reference_wrapper <testbench> camper;
};

testing::testing(testbench &x):camper(x) {
}

int main() {
    testbench tempo;
    testing test_a (tempo);
    std::cout << test_a.camper.ownerid;
}

this would cause an error in gcc (I'm using Code::Blocks as Editor and gcc as compiler)

'class std::reference_wrapper<testbench>' has no member named 'ownerid'

If the line

    std::reference_wrapper <testbench> camper;

is changed to :

    testbench &camper;

Then everything is worked as I expected.

How do I fix this, or is it just my misunderstanding "std::reference_wrapper" as a general improvement of reference.

C++ strong-typed enums and calling convention

How safe is it to use callbacks, substituting an int parameter for a strong-typed enum? The callback will be used by a linked library, if that helps.

For instance, if the API / external function looks like this:

using callback_t = void( int );
void set_event( callback_t * );

Then would this approach be safe / well-defined?

enum class result_t : int { /* expected values */ };
using my_callback_t = void( result_t );
// later
void my_callback( result_t );
set_event( &my_callback );

Or would you be required to in cases like this, to write a wrapper callback function just to convert int to result_t?

C++11: Why rvalue reference parameter implicitly converted to lvalue

Following is the simplistic code of my problem,

void overloaded (int&& x) {
  cout << "[rvalue]";
}

template <class T>
void fn (T&& x) {
  overloaded(x);
}

int main() {
    fn(0);
    return 0;
}

I got a compile error

cannot bind ‘int’ lvalue to ‘int&&

  overloaded(x);

I am confused here, x is passed as a rvalue reference into fn(). But why the overload() call in fn() complains x is a lvalue?

Why doesn't moving an object leave it null?

A a5(move(a1));

While after the move the member vars of a1 are set to defaults, a1 itself is not set to null. You can't do a1 == nullptr... to check if a1 is useless...

I find this odd. Is there something I'm misunderstanding here? I would think that if a1 is moved, it becomes useless, this should be indicated by setting it to null somehow. No?

The thing is that by leaving a1 in a non null state, it still can be used. There is no compiler warning or error. There is no real indication that the object is in a messed up state. if a has two member vars, an int and a dynamically alloc object, the dyn alloc object will point to nullptr but the int will have a def value (of course only if implemented right...easy to mess up). So you can

a1.getInt() and get back a number not realizing that a1 has been reset.

EDIT Added sample move c'tor

A(A&& other) : num(other.num), s(other.s){
   other.num = 0;
   other.s = nullptr;     //dyn alloc obj
}

Find 2 subsets in array that have minimum difference and consecutive elements

I came across a variation of the subset sum problem that i find quite interesting. So, given an array of (positive) elements, you have to partition it in 2 sets so that their difference is minimum. But here is the catch. The elements have to be consecutive and they also work in circular order. Here are 2 examples so you can understand what I mean:

EXAMPLE 1:

INPUT: 7 5 1 3 8 9 11 8

OUTPUT: 0 ( set 1: {11,8,7},set 2: {5,1,3,8,9}

result picture.


EXAMPLE 2:

INPUT:10 14 75 90 3 5 40 4 8

OUTPUT: 27 (set 1: {4,8,10,14,75},set 2: {90,3,5,40})

What is a possible solution using C++? Thanks!

Use of auto vs auto& in C++

I've seen auto& used in range for loops to avoid copying members in the loop. But I don't have a deep, meaningful understanding when I should use auto vs auto&. Can somebody please give the theory on it, as well as concrete usage cases?

How can we sequentially receive multiple data from boost::asio::tcp::ip::read_some calls?

Let us suppose that a client holds two different big objects (in terms of byte size) and serializes those followed by sending the serialized objects to a server over TCP/IP network connection using boost::asio.

  • For client side implementation, I'm using boost::asio::write to send binary data (const char*) to the server.

  • For server side implementation, I'm using read_some rather than boost::asio::ip::tcp::iostream for future improvement for efficiency. I built the following recv function at the server side. The second parameter std::stringstream &is holds a big received data (>65536 bytes) in the end of the function.

When the client side calls two sequential boost::asio::write in order to send two different binary objects separately, the server side sequentially calls two corresponding recv as well. However, the first recv function absorbs all of two incoming big data while the second call receives nothing ;-(. I am not sure why this happens and how to solve it.

Since each of two different objects has its own (De)Serialization function, I'd like to send each data separately. In fact, since there are more than 20 objects (not just 2) that have to be sent over the network.

void recv (
    boost::asio::ip::tcp::socket &socket,
    std::stringstream &is) {

    boost::array<char, 65536> buf;

    for (;;) {
        boost::system::error_code error;
        size_t len = socket.read_some(boost::asio::buffer(buf), error);
        std::cout << " read "<< len << " bytes" << std::endl;  // called multiple times for debugging!

        if (error == boost::asio::error::eof)
          break;
        else if (error)
          throw boost::system::system_error(error); // Some other error.

        std::stringstream buf_ss;
        buf_ss.write(buf.data(), len);
        is << buf_ss.str();
    }
}

Client main file:

int main () {
    ... // some 2 different big objects are constructed.
    std::stringstream ss1, ss2;
    ... // serializing bigObj1 -> ss1 and bigObj2-> ss2, where each object is serialized into a string. This is due to the dependency of our using some external library
    const char * big_obj_bin1 = reinterpret_cast<const char*>(ss1.str().c_str());
    const char * big_obj_bin2 = reinterpret_cast<const char*>(ss2.str().c_str());

    boost::system::error_code ignored_error;
    boost::asio::write(socket, boost::asio::buffer(big_obj_bin1, ss1.str().size()), ignored_error);
    boost::asio::write(socket, boost::asio::buffer(big_obj_bin2, ss2.str().size()), ignored_error);

    ... // do something
    return 0;
}

Server main file:

int main () {
    ... // socket is generated. (communication established)
    std::stringstream ss1, ss2;
    recv(socket,ss1); // this guy absorbs all of incoming data
    recv(socket,ss2); // this guy receives 0 bytes ;-(
    ... // deserialization to two bib objects
    return 0;
}

insertion seg fault RBT

I have been having trouble implementing the insertion method of the red-black tree. I am following a template for the assignment and the part that seems to causing the seg fault is when using the standard binary tree insert before doing all the rotations. The rotation method was provided in class. Whenever I remove the binary insert it works all the way through but of course it will only be able to insert three elements (root and left and right)

The comments for cout were just to pinpoint where the errors start occurring. It could also be in the left and right rotate. I will include them underneath the following code. As stated, it was provided in class because we are supposed to inherit this code to create other code but I am not even able to get past inserting 3 elements correctly.

I also tried to delete the x pointer because it is a new node but that also did not solve the issue. i know we are supposed to delete them once used but these are inside the red-black tree so we shouldn't need to be deleted correct?

template <class myType>
void redBlackTree<myType>::insert(myType value)
{
cout << "beginning insert" << endl;
if(search(value) == true){
    cout << "returning" << endl;
    return;}

cout << "creating new node" << endl;
nodeType<myType> *x = new nodeType<myType>;
x->right = NULL;
x->left = NULL;
x->parent = NULL;
x->keyValue = value;
x->color = RED;

if(root == NULL)
{
    root = x;
    x->color = BLACK;
    return;
}

nodeType<myType> *curr = root;

cout << "setting this x: " << x->keyValue << endl;
/* code that seems to be causing the seg fault. Able to get to 4 elements inside before the seg fault comes.
while(true)
{   
    if(curr->keyValue > x->keyValue)
    {
        if(curr->left == NULL)
            break;

        curr = curr->left;
    }       
    else
    {       
        if(curr->right == NULL)
            break;

        curr = curr->right;
    }   
}
*/  
if(curr->keyValue > x->keyValue)
{   
    x->parent = curr;
    curr->left = x;
    x->color = RED;
}
else
{
    x->parent = curr;
    curr->right = x;
    x->color = RED;
}   

while(x != root && x->parent->color == RED)
{
    if(x->parent == x->parent->parent->left)
    {
        cout << "in if" << endl;

        if(x->parent->parent->right != NULL && x->parent->parent->color == RED)
        {
            cout << "in if of if" << endl;
            x->parent->color = BLACK;
            x->parent->parent->right->color = BLACK;
            x->parent->parent->color = RED;
            x = x->parent->parent;
        }
        else
        {
            cout << "in else of if" << endl;
            if(x == x->parent->right)
            {
                x = x->parent;
                leftRotate(x);
            }
            cout << "past else of if" << endl;
            x->parent->color = BLACK;
            x->parent->parent->color = RED;
            rightRotate(x->parent->parent);
            cout << "about to exit" << endl;
        }
    }

    else
    {
        cout << "in else" << endl;
        if(x->parent->parent->left != NULL && x->parent->parent->color == RED)
        {
            x->parent->color = BLACK;
            x->parent->parent->left->color = BLACK;
            x->parent->parent->color = RED;
            x = x->parent->parent;
        }
        else
        {
            if(x == x->parent->right)
            {
                x = x->parent;
                rightRotate(x);
            }

            x->parent->color = BLACK;
            x->parent->parent->color = RED;
            leftRotate(x->parent->parent);
        }
    }

    if(x == root)
        x->color = BLACK;

    cout << "looping" << endl;
}
cout << "out of exit" << endl;
};  

left rotate

template <class myType>
void redBlackTree<myType>::leftRotate(nodeType<myType> *x)
{
nodeType<myType> *y = y->right;
x->right = y->left;

if(x->right != NULL)
    root = y;
else if(x == x->parent->left)
    x->parent->left = y;
else
    x->parent->right = y;

x->left = x;
x->parent = y;
};

right rotate

template <class myType>
void redBlackTree<myType>::rightRotate(nodeType<myType> *y)
{

nodeType<myType> *x = y->left;
x->left = x->right;

if(x->right != NULL)
    x->right->parent = y;

x->parent = y->parent;

if(x->parent == NULL)
    root = x;
else if(y == y->parent->left)
    y->parent->left = x;
else
    y->parent->right = x;

x->right = y;
y->parent = x;

};

Why require copy constructor for packaged_task in VS

class MoveOnlyOperation
{
public:
    MoveOnlyOperation()                         = default;
    MoveOnlyOperation(const MoveOnlyOperation&) = delete;
    MoveOnlyOperation(MoveOnlyOperation&&)      = default;

    int operator()()
    {
        return 0;
    }
};

I want to wrap an object instance inside a packaged_task like this:

std::packaged_task<void()> task(MoveOnlyOperation{}); 

I get "error C2280: 'MoveOnlyOperation::MoveOnlyOperation(const MoveOnlyOperation &)': attempting to reference a deleted function"

The documentation for C++ 11 says one can perfect forward the instance inside the packaged_task though. I also don't have issues with clang.

It there something implementation defined about how packaged_task should be implemented or a bug in VS 2015 (and possibly later because I get same issue with http://rextester.com/WBEH22233)

factoring Eigen3 temporaries to improve computation speed

I'm sorry to raise a general question about Eigen3'scheme of optimized computation. Let's imagine we do possess two Eigen3 matrices, M and N. Imagine we need to compute the following:

Eigen::Matrix<double, 3,3> M;
Eigen::Matrix<double, 3,3> N;

// here is the computation:
Eigen::Matrix<double, 3,3> D = Eigen::Matrix<double, 5,5>::Identity() + M;
Eigen::Matrix<double, 3,3> R = D * N * D.transpose();

What I would like to know is: is there a ways to avoid copying the expression I + M into a full matrix (thus a copy), and instead use a lazy-evaluation scheme in such an expression. Hopefully, it would be feasible to write in C++11 something like this instead:

auto D = Eigen::Matrix<double, 3,3>::Identity() + M;
Eigen::Matrix<double, 3,3> R = D * N * D.transpose();

Normally, D is in this case a compound (potentially complex) template lazy-eval. type, so this normally should solve the problem. Could you correct me if not so ?

In the same order of idea, I would like to do the same with:

auto E = <undisclosed_type coma initializer>(
                M,
                Eigen::Matrix<double, 3,3>::Zero());
Eigen::Matrix<double, 6,6> R = E * N * E.transpose();

but I do not see how to perform such an optimization. So, if there is a way to optimize this out in term of instruction number in the evaluation process, this could help me.

Thanks in advance for your help.

Initializing a tuple's elements with non-const references to another tuple's elements of different type

I'm trying to do a conversion initialization of an std::tuple (called w) with elements from another std::tuple (called t) with same size but different element types.

In my application, the elements of w must be constructed using a non-const reference to the respective element of t.

Unfortunately, there only exists a 4) converting copy-ctor and a 5) converting move-ctor for std::tuple (reference). This means, the new element from w can only be initialized using either a const reference or rvalue reference to the element of t, and both are not applicable.

Example

First we have a element modifier class, that only binds to references of its element type.

template<typename T>
struct SingleElementModifier {
    T& ref;
    SingleElementModifier(T& ref) : ref(ref) { }
};

Next a type trait to get the type of w given the type of t. Essentially it wraps each element from t into the SingleElementModifier.

template<typename T> struct ModifierTuple;
template<typename... Ts>
struct ModifierTuple<std::tuple<Ts...>> {
    using Type = std::tuple<SingleElementModifier<Ts>...>;
};

Now we have a TupleModifier that takes a tuple t and stores a tuple w with modifiers to each element of the first tuple.

template<typename Tuple>
struct TupleModifier {
    using TupleType = typename ModifierTuple<Tuple>::Type;
    TupleType w;
    TupleModifier(Tuple& t) : w{ t } { }
};

Now we only need to choose some tuple t and create the modifer.

int main() {
    /* just some example types, could be any type inside. */
    std::tuple<double, std::pair<int, int>> t;
    TupleModifier mod(t);
}

Live example

Here the compiler will stop and complain to me that no constructor for w{ t } could be found, for the reason explained in the beginning.

Bad workaround

Theoretically, I could have SingleElementModifier take a const T& and use const_cast to get rid of the const, but I was hoping for a better solution that doesn't require me to throw away const-correctness.

declaring templated function as argument to non-templated function

template<typename Type>
void execute(absl::string_view expected_name){
  std::cout << "*** expected type: " << expected_name
            << " | actual type: " << typeid(Type);
}

void handle(std::function<void(absl::string_view)> executor){
  executor<int>("int");
  executor<double>("double");
}

I have this piece of code (which, of course, didn't compile). I want to be able to pass a templated function to a "normal" function and have the "normal" function define the concrete type as it needs, as shown in the example.

Is there a way to declare on the handle parameter list that executor is a templated function?

Range_error at memory location 0x000000158F2FF408

Doing my home exercise and stock with memory location error, the code looks fine, why it doesn't work? Could you please help me, really don't get why it comes out of range.

 #include "stdafx.h"
#include "std_lib_facilities.h"

double num;
double sumV;
double maxV;
double minV;
double avrV;

double vectorSum(vector<double> v) {

    for (int i = 0; i < v.size(); ++i) {
        sumV = sumV + v[i];
    }
    return sumV;
}
double vectorMax(vector<double> v) {
    sort(v.begin(), v.end());
    maxV = v[0];
    return maxV;
}
double vectorMin(vector<double> v) {
    sort(v.begin(), v.end());
    minV = v[v.size()];
    return minV;
}
double vectorAvr(vector<double> v) {
    avrV = vectorSum(v) / v.size();
    return avrV;
}

int main()
{
    vector<double> dif;
    cout << "Enter values of distance between two cities: " << endl;
    while (cin >> num) dif.push_back(num);
    cout << "Sum of your distances is: " << vectorSum(dif) << endl << "Minimum distance is: " << vectorMin(dif) << endl
        << "Maximum of your distance is: " << vectorMax(dif) << endl << "Avrage of your distance is: " << vectorAvr(dif) << endl;
    keep_window_open();
    return 0;
}

Does Boost asio ip tcp iostream support asynch?

I am coding network stuff via tcp/ip. Specifically I have been using boost::asio. Recently, to ease coding, I started using boost::asio::ip::tcp;:iostream. It can be useful for fast developing! But I am not sure whether it uses async_read or asynch_write. Can anybody know whether it does?

Avoid template overloading in c++

template<int ... p>
class Separate {
private:
    int range;
    vector<int> pos{p...};

    template<int end>
    void _split(int cur) {
        for (int i = cur; i < end; i++)
            cout << " " << i;
        cout << endl;
        for (int i = end; i < range; i++)
            cout << " " << i;
        cout << endl;
    }

    template<int end, int... args>
    void _split(int cur) {
        for (int i = cur; i < end; i++)
            cout << " " << i;
        cout << endl;
        _split<args...>(end);
    }

    void _split1(int cur, vector<int>::iterator iterator) {

        if (iterator == pos.end())
            _split1(cur);
        else {
            int end = *iterator;
            for (int i = cur; i < end; i++)
                cout << " " << i;
            cout << endl;
            _split1(end, ++iterator);
        }
    }

    void _split1(int cur) {
        for (int i = cur; i < range; i++)
            cout << " " << i;
        cout << endl;
    }

public:
    explicit Separate(int r) : range(r) {}

    void split() {
        _split<p...>(0);
        _split1(0, pos.begin());
    }
};

int main() {
    Separate<1, 4> a(6);
    a.split();
/* 0
 * 1 2 3
 * 4 5
 * */

    Separate<> b(2);
    b.split();
/* 0 1 
 * */

I use the normal way to show what I want to.And the hardest part is resolving function overloading and match empty template args.I want to do this because I see something similar to annotation in java.Use template to describe where will Separate class split.

In c++11, how can auto distinguish short from long at compile time?

I'm excited to start using auto variables in my C++ programs. I know that "auto" variables use template rules to deduce variable types, but I'm confused about how that works for numeric types. For example, suppose I have

auto foo = 12;

The type for foo could reasonably be int or even unsigned char. But suppose later in my program, I do some math and assign foo a value of 4 billion. At that point, I would want foo to have type unsigned int or perhaps long. How can compilers anticipate values that will be assigned later in the program?

The exact precedence of actions the compiler does to a stack frame?

I have this code:-

int i;
class A
{
public:
    ~A()
    {
        i = 10;
    }
};

int& foo()
{
    i = 3;
    A ob;
    return i;
}

int main()
{
    cout << "i = " << foo() << endl;
    return 0;
}

The output is 10, as the destructor updates the value of foo() i.e i. My question is, shouldnt foo() not exist anymore since the function is out of scope ? Or is foo i.e the return value stored somewhere in memory ? If so then how long is it stored ? I want to know the actions the compiler does in order.

Thankyou.

xutility read access violation on returning isstream with custom vector

So i have a custom made vector class with also an custom allocator:

alloc.h:

#ifndef ALLOC1234_GUARD
#define ALLOC1234_GUARD

namespace mem {

template<typename T>
class allocator {
public:
    //
    T* allocate(int n);                 //allocate space for n objects of type T
    void deallocate(T* p/*, int n*/);       //deallocate n objects of type T starting at p

    void construct(T* p, const T& v);   // construct a T with the value v in p
    void destroy(T* p);                 // destroy the T in p
};

template<typename T>
T* allocator<T>::allocate(int n)                    //allocate space for n objects of type T
{

    T* res = (T*)malloc(sizeof(T)*n);
    if (res == nullptr)
        throw std::bad_alloc();

    return res;
}

template<typename T>
void allocator<T>::deallocate(T* p/*, int n*/)      //deallocate n objects of type T starting at p
{
    free(p);
}

template<typename T>
void allocator<T>::construct(T* p, const T& v)                  // construct a T with the value v in p
{
    new(p) T(v);
}

template<typename T>
void allocator<T>::destroy(T* p)                    // destroy the T in p
{
    p->~T();
}

}
#endif

vector.h:

#ifndef VECTOR1234_GUARD
#define VECTOR1234_GUARD

#include "alloc.h"
#include <exception>
#include <sstream>
#include <string>
#include <iostream>

template<typename T,typename A = mem::allocator<T>>
class vector {
    A alloc;        //use allocate to handle memory for elements
    int sz;         //the size
    T* elem;        //a pointer to the elements
    int space;      //size + free space
public:
    using size_type = unsigned long;
    using value_type = T;
    using iterator = T*;
    using const_iterator = const T*;


    vector():sz{0}, elem{nullptr}, space{0}{}
    explicit vector(int s) :sz{ s }, elem{ new T[s] }, space{ s }
    {
        for (int i = 0; i < sz; ++i) elem[i] = 0;           // elements are initalized
    }

    vector(const vector& arg);                              //copy constructor
    vector& operator =(const vector& a);                    //copy assignment

    vector(vector&& a);                                     //move constructor
    vector& operator=(vector&& a);                          //move assignment

    ~vector() { delete[] elem; }                            //destructor

    T& at(int n) {                                          //checked access;
        if (n < 0 || sz <= n)
            throw std::out_of_range("vector");
        return elem[n]; 
    };                                          
    const T& at(int n) const{
        if (n < 0 || sz <= n)
            throw std::out_of_range("vector");
    return elem[n];
    };

    T& operator[](int n) { return elem[n]; }                //access: return reference
    const T& operator[] (int n) const { return elem[n]; }   

    int size() const { return sz; }                         //the current size
    int capacity() const { return space; }                  

    void reserve(int newalloc);
    void resize(int newsize , T val = T());                             //growth
    void push_back(const T& val);

    iterator begin() { return elem; }
    const_iterator begin()const { return elem; }
    iterator end() { return elem + sz; }
    const_iterator end() const { return elem + sz; }
    size_type size() { return sz; }

    iterator back() { return end() - 1; }
    const_iterator back() const { return end()-1; }

    iterator insert(iterator p, const T&val);
    iterator erase(iterator p);
};

template<typename T, typename A>
vector<T,A>::vector(const vector<T,A>& a)                   //copy constructor
    :sz{a.sz}, elem{new T[a.sz]}
{
    copy(a.elem, a.elem + sz, elem);
}

template<typename T, typename A>
vector<T, A>& vector<T, A>::operator =(const vector<T, A>& a)   //copy assignment
{
    if (this == &a) return *this;           //return if self assignment

    if (a.sz <= space) {                    //enough space no need for new allocation
        for (int i = 0; i < a.sz; ++i)      //copy elements
            alloc.construct(&elem[i], a.elem[i]);
        sz = a.sz;
        return *this;
    }

    T* p = alloc.allocate(a.sz);//allocate new size
    for (int i = 0; i < a.sz; ++i)  //copy elements
        alloc.construct(&p[i], a.elem[i]);
    for (int i = 0; i < sz; ++i)
        alloc.destroy(&elem[i]);            //destroy
    alloc.deallocate(elem);
    space = sz = a.sz;              //set new size
    elem = p;                       //set new elements
    return *this;                   //return a self reference
}

template<typename T, typename A>
vector<T,A>::vector(vector<T,A>&& a)        //move constructor
    :sz{a.sz},elem{a.elem}
{
    a.sz = 0;                           //make a the empty vector
    a.elem = nullptr;
}

template<typename T, typename A>
vector<T,A>& vector<T,A>::operator=(vector<T,A>&& a)            //move assignment
{
    delete[] elem;                  //deallocate old space
    elem = a.elem;                  //copy a's elem and sz
    sz = a.sz;
    a.elem = nullptr;               //make a the empty vector
    a.sz = 0;
    return *this;
}

template<typename T, typename A>
void vector<T, A>::reserve(int newalloc)
{
    if (newalloc <= space) return;      //never decrease allocation
    T* p = alloc.allocate(newalloc);        //alocate new space
    for (int i = 0; i < sz; ++i)
        alloc.construct(&p[i], elem[i]);    //copy
    for (int i = 0; i < sz; ++i)
        alloc.destroy(&elem[i]);            //destroy
    alloc.deallocate(elem/*, space*/);          //deallocate old space
    elem = p;                               
    space = newalloc;
}

template<typename T, typename A>
void vector<T,A>::push_back(const T& val)
{
    if (space == 0)
        reserve(8);
    else if (space == sz)
        reserve(2 * space);
    alloc.construct(&elem[sz], val);    //add val at the end
    ++sz;
}

template<typename T, typename A>
void vector<T, A>::resize(int newsize, T val)
{
    reserve(newsize);
    for (int i = sz; i < newsize; ++i)
        alloc.construct(&elem[i], val);     //construct
    for (int i = newsize; i < sz; ++i)
        alloc.destroy(&elem[i]);            //destroy
    sz = newsize;
}


template<typename T, typename A>    //requires Element<T> && Allocator<A>
typename vector<T, A>::iterator vector<T, A>::erase(iterator p)
{
    if (p == end()) return p;
    for (auto pos = p + 1; pos != end(); ++pos)
        *(pos - 1) = *pos;          //copy element "one position to the left
    alloc.destroy(&*(end() - 1));   //destroy surplus copy of last element
    --sz;
    return p;
}

template<typename T, typename A>    //requires Element<T> && Allocator<A>
typename vector<T, A>::iterator vector<T, A>::insert(iterator p, const T&val)
{
    int index = p - begin();
    if (size() == capacity())
        reserve(size() == 0 ? 8 : 2 * size());  //make sure we have space
    //first copy last element in uninitalized space:
    alloc.construct(elem + sz, *back());
    ++sz;
    iterator pp = begin() + index;      //the place to put val
    for (auto pos = end() - 1; pos != pp; --pos)
        *pos = *(pos - 1);      //copy elements one position to the right;
    *(begin() + index) = val;   //insert val;
    return pp;
}

template<typename T, typename A>    //requires Element<T> && Allocator<A>
std::ostream& operator<<(std::ostream& os, const vector<T,A>& obj)
{
    for (const auto& x : obj)
        os << x<<' ';
    os << '\n';
    return os;
}

template<typename T, typename A>
std::istream& operator>>(std::istream& is, vector<T, A>& obj)
{
    std::string line;
    std::getline(is , line);
    if (is.bad() || is.fail())
        return is;

    std::istringstream istr{ line };
    vector<T, A> tmp;

    while (true) {
        T tmp_in = T();
        istr >> tmp_in;
        if (istr.fail()) {
            istr.clear();
            std::string invalid;
            istr >> invalid;
            continue;
        }
        tmp.push_back(tmp_in);
        if (istr.eof())break;
    }

    for (const auto& x : tmp)
        obj.push_back(x);
    return is;  // it sends me to xutility.h here
}

#endif

main.cpp:

#define _SCL_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <exception>
#include "vector.h"
using namespace std;

inline void keep_window_open(string s)
{
    if (s == "") return;
    cin.clear();
    cin.ignore(120, '\n');
    for (;;) {
        cout << "Please enter " << s << " to exit\n";
        string ss;
        while (cin >> ss && ss != s)
            cout << "Please enter " << s << " to exit\n";
        return;
    }
}

int main()
try {


    //vector <int>test;   //this works fine
    vector <string> test;

    while (true) {
        cin >> test;
        cout << test << '\n';
    }
    keep_window_open("~");
}
catch (runtime_error& e) {
    cerr << e.what() << "\n";
    keep_window_open("~");
}
catch (out_of_range& e) {
    cerr << "out of range access " << e.what() << "\n";
    keep_window_open("~");
}
catch (bad_alloc& e) {
    cerr <<"memory alloc failed "<< e.what() << "\n";
    keep_window_open("~");
}
catch (...) {
    cerr << "unknown error " << "\n";
    keep_window_open("~");
}

Now the following problem. I can read in vector values if the vector is vector. So adding 1 2 3 4 5 is no problem. Also vector works fine. If i change the container type to vector and read in "hello this is a test" via cin >> test; I get a crahs in xutility.h:

        // MEMBER FUNCTIONS FOR _Container_base12
inline void _Container_base12::_Orphan_all() _NOEXCEPT
    {   // orphan all iterators
 #if _ITERATOR_DEBUG_LEVEL == 2
    if (_Myproxy != 0)               //It points on this line
        {   // proxy allocated, drain it
        _Lockit _Lock(_LOCK_DEBUG);

        for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter;
            *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter)
            (*_Pnext)->_Myproxy = 0;
        _Myproxy->_Myfirstiter = 0;
        }
 #endif /* _ITERATOR_DEBUG_LEVEL == 2 */
    }

Visual Studio 2017 throws: Exception thrown: read access violation.this was 0xC83FB858.

How can this header even get called and what is the meaning of it? I really have no idea whats going on.

I replaced the custom vector with std::vector and then it works.

reduction of eigen based templates

I am trying to do a reduction based on eigen matrix.

#include <iostream>
#include <Eigen/Dense>
#include <type_traits>

template<typename T1, typename T2, int n1, int n2>
auto reduction(Eigen::Matrix<T1, n1, n2> &a1,
               Eigen::Matrix<T2, n1, n2> &a2)
     -> decltype(T1{}*T2{})
{
  using BaseT3 = 
    typename std::remove_cv<typename std::remove_reference<decltype(T1{}*T2{})>::type>::type;

  BaseT3 res = a1(0, 0)*a2(0, 0);

  for (int i=0; i<n1; ++i)
    for (int j=0; j<n2; ++j)
      if (i+j)
        res = res + a1(i, j)*a2(i, j);

  return res;
}

int main()
{
  Eigen::Matrix<double, 3, 3> m;
  Eigen::Matrix<Eigen::Vector3d, 3, 3> n;

  std::cout << reduction(m, n) << std::endl;
}

Basically, Im a trying to get sum_{i, j} a1[i, j] * a2[i, j] where a1 and a2 are some eigen mathix but I get compilation errors. The error I get is

error: no match for ‘operator=’ (operand types are ‘BaseT3 {aka 
Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<double>, 
const Eigen::Matrix<double, 3, 1> >}’ 
and 
‘const Eigen::CwiseBinaryOp<Eigen::internal::scalar_sum_op<double>, 
const Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<double>, 
const Eigen::Matrix<double, 3, 1> >, 
const Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<double>, 
const Eigen::Matrix<double, 3, 1> > >’)
         res = res + a1(i, j)*a2(i, j);
             ^

If I am not mistaken, for the given main, type BaseT3 should have been Eigen::Vector3d. I also tried to static cast so the operator= should not fail but I then get other errors.

This is c++11, I use Eigen3 and the compiler is g++ 5.4.1.

Is a threadpool necessary here?

Is a threadpool necessary when my use case creates threads for a particular use-case only once in the life time of the application since the use case is called only once? And in no other place is threads used?

Socket crash during async_write_some

/*Basic Things has been done.*/
/*Like setting connection and receiving */
namespace bar = boost::asio::error;
void doWrite(char* buffer, size_t size_) {
    boost::asio::async_write_some(socket, boost::asio::buffer(buffer ,size), boost::bind(&Handler, this, bar::error, bar::bytes_transferred));
}

/*handler*/
void handler(/*parameters*/)
{
}

while my server is continuously transferring the data. sometimes client gets crash /*purposely */. errorCode.message() gives error of boost::asio::error::bad_descriptor and whole program crashes. i have copied the program from boost chat server example. how can i prevent even if client abruptly closes. server should not get crash.

overloading () operator for unordered_set

I have a class, whose objects I put into a unordered_set. To do this I have written custom hash generators and comparators to be able to use the class objects in unordered_set. Everything works fine. The comparator of this class looks like this :

struct MyClassComparator
{
  bool
  operator()(const MyClass & obj1, const MyClass & obj2) const
  {
    if (obj1.getName() == obj2.getName())
      return true;
    return false;
  }
};

So I am comparing the names (strings) of the objects (nothing fancy). I use this to find a MyClass object in a set using .find function.

Now the question is : Is it possible to over load this () operator resulting in the following code

struct MyClassComparator
{
  bool
  operator()(const MyClass & obj1, const MyClass & obj2) const
  {
    if (obj1.getName() == obj2.getName())
      return true;
    return false;
  }

  bool
  operator()(const MyClass & obj1, const std::string & name) const
  {
    if (obj1.getName() == name)
      return true;
    return false;
  }
};

and use the .find function like

my_set.find("my_class_name")

if yes is there a performance overhead in doing so.

OpenMP #pragma num_threads

I am trying to understand OpenMP a bit, but I am confused how I am allowed to enter variables in num_threads() when it is a part of a #pragma which is a place to give information to the compiler. I was expecting it would not allow variables as a parameter to the num_threads but looks like I am allowed to use variables. How is that? How does it work?

dimanche 25 février 2018

C++11 brace/aggregate initialization. When to use it?

After reading up on C++11 and common guidelines surrounding it, I often read about how you should use in-class initialization as well as aggregate initialization.

Here's an example from what seems to be the "old" way of doing things:

class Example
{
public:
    // Set "m_x" to "x", "m_y" gets set to the default value of 5
    Example(int x) : m_x(x), m_y(5)
    {
    }

private:
    int m_x;
    int m_y;

};

And to my understanding this is what people recommend now:

class Example
{
public:
    Example(int x) : m_x{x}
    {
    }

private:
    int m_x{0}; // Supposedly {} works too? I guess this would
                // only be necessary if I had another constructor
                // taking in 0 arguments, so "m_x" doesn't go uninitialized
    int m_y{5};

};

My question is: How does this affect pointers, references, and some of the STL classes? What's the best practice for those? Do they just get initialized with {}? Additionally, should I be doing this even if the constructor initializes the variables anyway? (i.e. Writing m_x{} even though it gets set to something else by the constructor anyway)

Thank you.

Different address after struct initialization

I'm looking at this simple struct:

struct Journal
{
  std::string title;
  std::vector<std::string> entries;

  explicit Journal (const std::string& title): title(title)
  {
    std::cout << "Address of title is " << &title << std::endl;
  }

  void add(const std::string& entry)
  {
    std::cout << "Address of title is " << &title << std::endl;
    entries.push_back(entry);
  }
};

int main() {
  std::string title = "Hello";
  std::string entry = "World";

  std::cout << "Address of title is " << &title << std::endl;
  Journal *journal = new Journal(title);

  (*journal).add(entry);
  std::cout << journal->entries.front() << std::endl;
  return 0;
}

I always thought the address of title should be the same through the whole execution, however, I was wrong as I got the following output:

Address of title is 0x7ffee90d3978
Address of title is 0x7ffee90d3978
Address of title is 0x7fa86f402740
World

Can somebody explain what happened after the initialization? Why would I get a different address? Does that mean a copy happened?

What is the simplest way for me to expand this program to calculate the inverse of up to a 10x10 matrix?

The program I have below finds the inverse of only a 3x3 matrix, but I'm wondering if there is a simple way for me to expand it to find the inverse of a user entered sized matrix UP TO 10x10. Thanks

#include<iostream>
using namespace std;

int main()
{
    int mat[3][3], i, j;
    float determinant = 0;

    cout<<"Enter elements of the matrix:"<<endl;
    for(i = 0; i < 3; i++)
        for(j = 0; j < 3; j++)
           cin>>mat[i][j];


    //finding determinant
    for(i = 0; i < 3; i++)
        determinant = determinant + (mat[0][i] * (mat[1][(i+1)%3] * mat[2][(i+2)%3] - mat[1][(i+2)%3] * mat[2][(i+1)%3]));


    cout<<"\n\nInverse of matrix is: "<<endl;
    for(i = 0; i < 3; i++){
        for(j = 0; j < 3; j++)
            cout<<((mat[(j+1)%3][(i+1)%3] * mat[(j+2)%3][(i+2)%3]) - (mat[(j+1)%3][(i+2)%3] * mat[(j+2)%3][(i+1)%3]))/ determinant<<"\t";

        cout<<endl;
    }

    return 0;
}

Sharing data between API and application threads

My API computes some data in its own thread:

/*** API is running in its own thread ***/
class API {
public:
    std::shared_ptr<Data> retrieveData() { return mData; }

private:
    std::shared_ptr<Data> mData;
    std::mutex mDataMutex;

    void run () {
        std::thread t([](){
            while (!exitApi) {
                mDataMutex.lock();

                updateData(mData);

                mDataMutex.unlock();
        });
        t.join();
    }
};

An application that uses our API will retrieve the shared data in another thread:

/*** Application is running in another thread ***/
class Application {
private:
    Api mApi;

    void run () {
        std::thread t([](){
            while (!exitApp) {
                std::shared_ptr<Data> data = mApi.retrieveData();

                /* API thread can update the data while the App is using it! */
                useData(data);
        });
        t.join();
    }

How can I ensure a secure exchange of the shared data between the two threads? I can think of three options but do not like any of them:

  1. Instead of sharing the pointer, the API will return a copy of all the data. However, the amount of data can get quite large and copying it should be avoided.
  2. The API will lock the data when it hands it over to the application and the application needs to explicitly ask the API to unlock it again after performing all computations. Even if documented correctly this is very much prone to deadlocks.
  3. When the API hands over the data to the application retrieveData will also return an already locked std::unique_lock. Once the application is done with using the data it has to unlock the unique_lock. This is potentially less prone to error but still not very obvious for the application developer.

Are there any better options to design the API (in modern C++11 and beyond) that is as developer-friendly as possible?

Delegation vs Instantiation

Say if I have a class A with an instance variable B b;. What's the difference between initializing the variable in A's constructor or using constructor delegation?

class A
{
public:
    A();

private:
    B b;

};

What's the difference between:

A::A() {
    this.b = B();
}

and

A::A() : b() {}

vector of string to istringstreama

I want to populate a istringstream object with content from vector of strings. Is there an elegant way to do this? I am doing the following now, which is not nice:

vector<string> vec = {"apple", "banana", "dog", "cat"};
string one_str;
for (string s: vec) {
    one_str += s + " ";
}
istringstream iss(one_str);

Why can't I dereference the result iterator when ranges::find_if takes an infinite range as rvalue?

Let

auto empty_line = [](auto& str){ return str.size() == 0; };

Now, we can do this:

auto line_range_with_first_non_empty = 
                ranges::view::drop_while(ranges::getlines(std::cin),empty_line);
auto input1 = std::stoi(*line_range_with_first_non_empty.begin());

We also can do this:

auto line_range2 = ranges::getlines(std::cin);
auto iter2 = ranges::find_if_not(line_range2,empty_line);
auto input2 = std::stoi(*iter2);

Unfortunately, when I try to shorten version above...

auto iter3 = ranges::find_if_not(ranges::getlines(std::cin),empty_line);
// Error when deref.
// auto input3 = std::stoi(*iter3);

Why can't I dereference when ranges::find_if takes an infinite range as rvalue?

godbolt.org/g/BZkT72

Separating write function from calculation (design)

I am currently in refactoring my code. I try to use more OOP features instead of using one large main function. Though I struggle with using the right approach to separate the calculation from writing the file. I want to use the write(...) routine as an interface, so I can swap out the ParallelWriter with, say NullWriter. Is using a template in an interface a right choice?

Since the writing is actually not very much, I don't want it to stand in the way of the calculation. So enqueue_write actually just blocks for a moment and buffers the data. In any case, both ParallelWriter and Calc have to know about struct d, right? So if for example Calc is using some OpenCL which is placed inside struct d, I have to include the same header files in both compilation units?

From a design perspective, is using a pointer to Writer is the right approach? I mean, its non-owning, and has to be flexible. Or should Calc own the writer because it has to know about the datastructure struct d?

Note: I use struct to keep the code a bit shorter. Also, I do not know a lot about programming design principles.

struct d {cl_uint x;};
template <class T> struct Writer {
  virtual ~Writer() {}
  virtual void enqueue_write(T &data) = 0;
  virtual void close() = 0;
};
struct ParallelWriter : public Writer<std::unique_ptr<struct d>> {
  void enqueue_write(std::unique_ptr<struct d> &data) override {
    std::cout << "move into internal buffer, gets written somewhen. "
                 "Calculation can continue\n";
  }
  void close() override { /* ... */ }
};
struct Calc {
  Calc(Writer<std::unique_ptr<struct d>> *writer) { m_writer = writer; }
  void run(int param) {
    std::cout << "allocate struct s, work on it w/ param, send to writer\n";
    auto data = std::make_unique<struct d>();
    data->x = static_cast<cl_uint>(2 * param);
    m_writer->enqueue_write(data);
  }
  void stop() {}
  Writer<std::unique_ptr<struct d>> *m_writer = nullptr;
};
int main() {
  auto writer = ParallelWriter{/*filename*/};
  auto calculation_object = Calc{&writer /*, options */};
  calculation_object.run(42);
  calculation_object.stop();
  writer.close();
}

Cheers, Jonas

Strange performance for measuring time

Consider the following two code fragments, I try to measure the running time of func(dataMatrix, dim).

1st code fragment:

auto start_s=chrono::high_resolution_clock::now();

func(dataMatrix, dim);

auto end_s=chrono::high_resolution_clock::now();

double online_Time=(chrono::duration_cast<chrono::nanoseconds>(end_s-start_s).count());

2nd code fragment:

double**PP=new double*[n];
double*A=new double[n];

for(int i=0;i<n;i++)
    PP[i]=new double[dim];

delete[] A;
for(int i=0;i<n;i++)
    delete[] PP[i];

delete[] PP;

auto start_s=chrono::high_resolution_clock::now();

func(dataMatrix, dim);

auto end_s=chrono::high_resolution_clock::now();

double online_Time=(chrono::duration_cast<chrono::nanoseconds>(end_s-start_s).count());

After I measure the time, I find that the elapsed time of func(dataMatrix, dim) in 2nd code fragment is significantly (71x) slower than the 1st fragment.

I originally think that the elapsed time should be the same since the first 11 lines of the 2nd code fragment should not affect the elapsed time.

What is/are the reason(s) behind that?

returning reference to a pointer

I was looking at this link about returning reference to a pointer. According to this, we have to return reference to a static or global variable. My question here is, in case we create memory block inside a function using new, will it be a problem if we use a local variable since memory allocated using new is permanent until deleted? I wrote below code to test this and it seems to be working. But I am not really sure if such usage is a good practice or not.

int* &returnPtrByRef(int numElements)
{
    static int *ptr = new int(numElements);

    return ptr;
}
int main (void)
{
    int num=5;
    int *&ptrRef = returnPtrByRef(num);
    for(int cnt=0;cnt<num;cnt++)
    *(ptrRef+cnt) = cnt*2;
    for(int cnt=0;cnt<num;cnt++)
    cout<<*(ptrRef+cnt)<<'\t';
    return 0;
  }

Using an Array[10] and incrementing it with a While loop using modulo 10 to Pair User inputs together

#include <iostream>
using namespace std;

int main()
{
    long int number;
    int digits;
    cout << "Enter Number: ";
    cin >> number;
    int counter[10] = { 0,0,0,0,0,0,0,0,0,0 };
    while (number != 0) {
        digits = number % 10;
        counter[digits] = counter[digits] + 1;
        number = number / 10;
    }
    for (int i = 0; i<10; i++) {
        if (counter[i] != 0) {
            cout << i << ": " << counter[i] << endl;
        }
    }
    return 0;
    system("pause");
}

I'm having an issue with my code that when I run it and enter a Number nothing really happens. It is supposed to run something like 1234556789 and the output should look like 1 : 9 2 : 8 3 : 7 4 : 6 5 : 5

I know sometimes if there isn't a system pause this happens where it runs part of the code and just ends, but I'm not sure whats wrong here.

samedi 24 février 2018

Passing lambdas directly to functions

I'm writing an Option class which represents a value that may or may not exist. The if_opt function is intended to take an Option and a function which will be called on the value held in the Option, but only if the value exists.

template <class T>
class Option {
private:
    std::shared_ptr<T> m_value;
public:
    explicit operator bool()const noexcept
    {
        return (bool)m_value;
    }

    Option() = default;

    explicit Option(T value)
    {
        m_value =  std::make_shared<T>(value);
    }

    template <class U>
    friend void if_opt(Option<U>&, std::function<void(U&)>);
};

template <class T>
void if_opt(Option<T>& opt, std::function<void(T&)> f)
{
    if (opt) f(*opt.m_value);
};

I've noticed that this works if I use it like so:

Option<int> none;
Option<int> some(10);

function<void(int&)> f1 = [](int& none)
{
    cout << "This should never be reached" << endl;
};

function<void(int&)> f2 = [](int& some)
{
    cout << "The value of some is: " << some << endl;
};

if_opt(none, f1);

if_opt(some, f2);

But I'd like to be able to put the lambda expression directly in the call, but when I do:

if_opt(none, [](int&)
{
    cout << "This should never be reached" << endl;
});

if_opt(some, [](int& some)
{
    cout << "The value of some is: " << some << endl;
});

I get an error:

error: no matching function for call to 'if_opt(Option<int>&, main()::<lambda(int&)>)'

I know that the type of a lambda expression is undefined in the standard, and that it merely has to be assignable to std::function<R(T)>, so this sort of makes sense, but is there a way that I can get the lambda argument to implicitly convert to a std::function<void(T&)> so that I can define the lambda in the call to if_opt the way I attempted?

can you give a derived class object as a function parameter in place of a base class object

I am trying to do matrix addition using expression templates and for this task I have base class: Exp

template<typename subtype>
class Exp{
public:
  inline const subtype& self(void) const{
    return *static_cast<const subtype*>(this);
  }

};

a derived class: matrix

template<typename T,unsigned rows_,unsigned cols_ >
class matrix : public Exp<matrix<T,rows_,cols_>>{
   //some members
};

and another derived class: addExp

template<typename T, typename Op1 , typename Op2>
class addExp: public Exp< addExp<T,Op1,Op2> >{
  const Op1& op1;
  const Op2& op2;

public:
  addExp(const Op1& a, const Op2& b): op1(a), op2(b){}

  T& operator()(const std::size_t i,const std::size_t j) const{ 
    return op1(i,j) + op2(i,j); 
  }
}; 

I am now trying to do operator overloading on addExp for adding matrices.

template<typename T,typename Lhs, typename Rhs>
inline addExp<T,Lhs, Rhs>
operator+(const Exp<Lhs> &lhs, const Exp<Rhs> &rhs) {
  return addExp<T,Lhs, Rhs>(lhs.self(), rhs.self());
}

later in my code I try to put two matrix objects(which should have Exp as base class) as function parameters here but I get an error:

prog.cpp: In function ‘int main()’:
prog.cpp:76:25: error: no match for ‘operator+’ (operand types are ‘matrix<int, 3u, 3u>’ and ‘matrix<int, 3u, 3u>’)
  matrix<int,3,3> m3 = m1+m2;
                       ~~^~~
prog.cpp:69:1: note: candidate: template<class T, class Lhs, class Rhs> addExp<T, Lhs, Rhs> operator+(const Exp<Lhs>&, const Exp<Rhs>&)
 operator+(const Exp<Lhs> &lhs, const Exp<Rhs> &rhs) {
 ^~~~~~~~
prog.cpp:69:1: note:   template argument deduction/substitution failed:
prog.cpp:76:26: note:   couldn't deduce template parameter ‘T’
  matrix<int,3,3> m3 = m1+m2;  

where did I go wrong here and how do I fix this?