How to create data structures using value types? - oop

Data Structures like double linked list, trees and Graph ..etc needs reference type nodes to be implemented. usually implemented with classes and objects
is there is a way to use value types like structs in implementing those?

Liked list implementation using struct:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Program to create a simple linked
// list with 3 nodes
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with
// the second node
// assign data to second node
second->data = 2;
// Link second node with the third node
second->next = third;
return 0;
}

Related

gtest expected args in mock method

I have mocked a function which takes std::set (stl) as an argument and I expected it to be called with the right args. std::set is a set of user-defined struct and I just want to verify one field of that struct to have one value for all the member of the set.
ie
struct my_struct {
int i;
int j;
int k;
}
using my_set = std::set<my_struct>;
MOCK_METHOD(void, my_func, (my_set));
EXPECT_CALL(obj, my_func(_))
.Times(1);
Now I want to expect my_func to be called with my_set and each member of my_set is my_struct and my_struct.i should be 1 for all the members.
I understand it could be done with Matcher and Each but now sure how to do that as I run into compilation error
The key is to use ::testing::Each matcher with ::testing::Field matcher combined. Each iterates over all elements of the container argument and Field matcher allows you to set proper expectations on the user-defined struct fields. Complete example:
struct my_struct {
int i;
int j;
int k;
};
auto my_set_comp = [](const auto& l, const auto& r) { return std::tie(l.i, l.j, l.k) < std::tie(r.i, r.j, r.k); };
using my_set = std::set<my_struct, decltype(my_set_comp)>;
class MockClass {
public:
MOCK_METHOD(void, my_func, (my_set));
};
TEST(SetTest, test1) {
MockClass obj{};
my_set a_set{my_set_comp};
a_set.emplace(my_struct{1, 1, 1});
a_set.emplace(my_struct{1, 2, 2});
a_set.emplace(my_struct{1, 3, 3});
EXPECT_CALL(obj, my_func(::testing::Each(::testing::Field(&my_struct::i, 1)))).Times(1);
obj.my_func(a_set);
}
or here.

What is a need of defining indegree vector in private for finding All Topological Sorts of DAG?

What is the importance of defining indegree vector in the private of a class? It could have been defined in alltopologicalSort() function.
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency list
list<int> *adj;
// Vector to store indegree of vertices
vector<int> indegree;
// A function used by alltopologicalSort
void alltopologicalSortUtil(vector<int>& res,
bool visited[]);
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// Prints all Topological Sorts
void alltopologicalSort();
};
And how it is functioning in below addedge function
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v's list.
// increasing inner degree of w by 1
indegree[w]++;
}
Use of indegree, please explain here the role of addEdge function in decrementing indegree
void Graph::alltopologicalSortUtil(vector<int>& res,
bool visited[])
{
// To indicate whether all topological are found
// or not
bool flag = false;
for (int i = 0; i < V; i++)
{
// If indegree is 0 and not yet visited then
// only choose that vertex
if (indegree[i] == 0 && !visited[i])
{
// reducing indegree of adjacent vertices
list<int>:: iterator j;
for (j = adj[i].begin(); j != adj[i].end(); j++)
indegree[*j]--;
// including in result
res.push_back(i);
visited[i] = true;
alltopologicalSortUtil(res, visited);
// resetting visited, res and indegree for
// backtracking
visited[i] = false;
res.erase(res.end() - 1);
for (j = adj[i].begin(); j != adj[i].end(); j++)
indegree[*j]++;
flag = true;
}
}
}
This is the link to complete code of finding All Topological Sorts of Directed Acyclic Graph
https://www.geeksforgeeks.org/all-topological-sorts-of-a-directed-acyclic-graph/
I have got my answer from above discussion with Gupta and kaya3
Indegree could have been defined in some function and then passed to alltopologicalSort() function as a reference. But then defining it in class makes it easier to deal with.
And Data members of a class are always kept private because of encapsulation rules

boost multi index - loop through key value of specific entry

I have a multi index with 2 indexes(in real code, they are of different type).
class CrUsersKeys{
int IMSI;
int TIMESTAMP;
}
After i find an entry in the multi index, I have the iterator of the entry.
auto it = multi.GetIteratorBy<IMSI_tag>(searchKey);
Now i want to loop through all the indexed members in this specific (*it) and check them. Note that i don't want to iterate through the iterator, but through the the indexed element of CrUsersKeys. How can i do it?
for(key in it)
{
if(isGoodKey(key))
std::cout<<"key "<<key <<" is good key"<<std::endl;
}
So it should check isGoodKey((*it).IMSI) and isGoodKey((*it).TIMESTAMP).
CrUsersKeys is template parameter, so i can't really know the members of CrUsersKeys.
Code example at http://coliru.stacked-crooked.com/a/d97195a6e4bb7ad4
My multi index class is in shared memory.
Your question has little to do with Boost.MultiIndex and basically asks for a way to compile-time iterate over the members of a class. If you're OK with CrUsersKeys being defined as a std::tuple (or a tuple-like class), then you can do something like this (C++17):
Edit: Showed how to adapt a non-tuple class to the framework.
Live On Coliru
#include <tuple>
template<typename Tuple,typename F>
bool all_of_tuple(const Tuple& t,F f)
{
const auto fold=[&](const auto&... x){return (...&&f(x));};
return std::apply(fold,t);
}
#include <iostream>
#include <type_traits>
bool isGoodKey(int x){return x>0;}
bool isGoodKey(const char* x){return x&&x[0]!='\0';}
template<typename Tuple>
bool areAllGoodKeys(const Tuple& t)
{
return all_of_tuple(t,[](const auto& x){return isGoodKey(x);});
}
struct CrUsersKeys
{
int IMSI;
const char* TIMESTAMP;
};
bool areAllGoodKeys(const CrUsersKeys& x)
{
return areAllGoodKeys(std::forward_as_tuple(x.IMSI,x.TIMESTAMP));
}
int main()
{
std::cout<<areAllGoodKeys(std::make_tuple(1,1))<<"\n"; // 1
std::cout<<areAllGoodKeys(std::make_tuple(1,"hello"))<<"\n"; // 1
std::cout<<areAllGoodKeys(std::make_tuple(1,0))<<"\n"; // 0
std::cout<<areAllGoodKeys(std::make_tuple("",1))<<"\n"; // 0
std::cout<<areAllGoodKeys(CrUsersKeys{1,"hello"})<<"\n"; // 1
std::cout<<areAllGoodKeys(CrUsersKeys{0,"hello"})<<"\n"; // 0
std::cout<<areAllGoodKeys(CrUsersKeys{1,""})<<"\n"; // 0
}

Binary Search Tree (Struct format)

I was studying BST from GeeksforGeeks, and I came across this:
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
What is this format of defining a structure? Can somebody explain this?
I have always seen the structure format as:
struct *Name of the structure*
{
body of structure
}
This is not a definition of a structure, it is a function that will return a struct node*.

How do i copy to a List?

I have this code in CLI
List<Codec^> ^GetCodecs()
{
List<Codec^> ^l = gcnew List<Codec^>;
bool KeepLooping = Encoder_MoveToFirstCodec();
while (KeepLooping)
{
Codec ^codec = gcnew Codec(); // here... and that call encoder_init many times... which call register codec many times... which is a mass...
codec->Name = gcnew String(Encoder_GetCurrentCodecName());
codec->Type = Encoder_GetCurrentCodecType();
char pix_fmts[200]; // array of 200 is probably enough
int actual_pix_fmts_sz = Encoder_GetCurrentCodecPixFmts( pix_fmts , 200 );
for (int i = 0 ; i < actual_pix_fmts_sz ; i++)
{
//copy from pix_fmts to the :List
codec->SupportedPixelFormats->Add(pix_fmts[i]);
}
This is the Encoder_GetCurrentCodecPixFmts function in C:
int Encoder_GetCurrentCodecPixFmts( char *outbuf , int buf_sz )
{
int i=0;
while ( (i<buf_sz) && (codec->pix_fmts[i]!=-1) )
{
outbuf[i] = codec->pix_fmts[i];
i++;
}
return i;
}
This is a new class i did:
#pragma once
using namespace System;
using namespace System::Collections::Generic;
public ref class Codec
{
public:
String^ Name;
int ID; // this is the index
int Type; // this is the type
List<int> ^SupportedPixelFormats;
Codec(void)
{
SupportedPixelFormats = gcnew List<int>;
// do nothing in the constructor;
}
};
Which contain also the: SupportedPixelFormats
The constructor in this new class should be empty but i needed somewhere to make an instance for the List make a NEW for the List.
Now in the C++ i need to transfer from pix_fmts char array to codec->Supported
Or to copy from pix_fmts to the :List
So i did as above:
codec->SupportedPixelFormats->Add(pix_fmts[i]);
But i'm not sure if this the meaning of copy.
Is that right what i did ?
It works, it's a kind of a deep copy. What makes you think it doesn't work? Do the results turn out wrong? If they do, put a breakpoint in there and try to get what is wrong.
Instead of copying one by one perhaps you can use the Enumerable::ToList extension method.
I hope this helped you.