I have n players, each player has a weight w. I want to distribute players among two teams so that the weight difference can be as minimum as possible.
Restriction: I have to use backtracking technique and C++ language
I have n players, each player has a weight w. I want to distribute players among two teams so that the weight difference can be as minimum as possible.
Restriction: I have to use backtracking technique and C++ language
This lines are not working properly:
for (auto prod : productions_[*productionNonterm])
productions_[nonterminal].push_back(prod);
If productions_[*productionNonterm] has only 1 element, everything is good. But if it has at least 2 elements, productionNonterm is modified and I have no idea why.
vector<string> nonterminals_;
unordered_map<string, vector<string>> productions_;
for (const auto &nonterminal : nonterminals_) {
for (auto productionNonterm = productions_[nonterminal].begin(); productionNonterm != productions_[nonterminal].end(); ++productionNonterm) {
if (cntNonterminalsInProduction(*productionNonterm) == 1 && cntTerminalsInProduction(*productionNonterm) == 0) {
nonterminals_.erase(find(nonterminals_.begin(), nonterminals_.end(), *productionNonterm));
for (auto prod : productions_[*productionNonterm])
productions_[nonterminal].push_back(prod);
productions_[*productionNonterm].erase(productions_[*productionNonterm].begin(), productions_[*productionNonterm].end());
productions_[nonterminal].erase(productionNonterm);
--productionNonterm;
}
}
}
I was trying to enumerate a variadic tuple, so that i can perform certain operations on each of its elements.
#include <iostream>
#include <tuple>
#include <utility>
template <size_t N, typename ...Args>
typename std::enable_if<N == sizeof...(Args), void>::type
print(std::tuple<Args...>& tuples)
{ }
template <size_t N, typename ...Args>
typename std::enable_if<(N < sizeof...(Args)), void>::type
print(std::tuple<Args...>& tuples)
{
std::cout << std::get<N>(tuples);
print<N + 1>(tuples);
}
template <typename ...Args>
void printTuples(std::tuple<Args...>& tuples)
{
print<0>(tuples);
}
int main(int argc, char** argv)
{
printTuples(std::make_tuple(1, 2.,3.));
return 0;
}
In visual studio 2013 this results in following error:
1>main.cpp(15): error C2770: invalid explicit template argument(s) for 'std::enable_if<N<1,void>::type print(std::tuple<_Types1...> &)'
1>main.cpp(15): error C2893: Failed to specialize function template 'std::enable_if<N==1,void>::type print(std::tuple<_Types1...> &)'
This compiles fine in VS2015. Could anyone please explain me why sizeof...(Args) was deduced to 1, even though a tuple with 3 arguments have been passed? Also why is this an error in VS2013 and not on VS2015?
Note: I built a work-around (for VS2013) by enumerating the tuple backwards (starting at the end)
First of all, I want to point out that it is the first time I am using dynamic polymorphism and the composite design pattern.
I would like to use the composite design pattern to create a class Tree which is able to take different objects of the type Tree, a composite type, or Leaf, an atomic type. Both Tree and Leaf inherit from a common class Nature. Tree can store Leaf or Tree objects into a std::vector<std::shared_ptr<Nature>> children. I would like to fill the vector children with a syntax of this kind (so I guess I have to use variadic, to consider a generic number of inputs in the input lists), as in the following:
Leaf l0(0);
Leaf l1(1);
Tree t0;
Tree t1;
t0.add(l0,l1);
t1.add(t0,l0,l1); // or in general t1.add(t_00,...,t_0n, l_00,...,l_0n,t10,...,t1n,l10,...,l1n,.... )
Then I would also access different elements of a Tree by means of the operator[ ]. So for example t1[0] returns t0 and t1[0][0] returns l0, while t1[0][1] returns l0.
Also I would like an homogeneous behaviour. So either use -> or the dot for accessing the methods on all levels (tree or leaf).
Is it possible to achieve this behaviour?
The implementation of such classes can be like the following:
class Nature
{
public:
virtual void nature_method() = 0;
virtual~Nature();
//virtual Nature& operator[] (int x);
};
class Leaf: public Nature
{
int value;
public:
Leaf(int val)
{
value = val;
}
void nature_method() override
{
std::cout << " Leaf=="<<value<<" ";
}
};
class Tree: public Nature
{
private:
std::vector <std::shared_ptr< Nature > > children;
int value;
public:
Tree(int val)
{
value = val;
}
void add(const Nature&);
void add(const Leaf& c)
{
children.push_back(std::make_shared<Leaf>(c));
}
void add(const Tree& c)
{
children.push_back(std::make_shared<Tree>(c));
}
void add(std::shared_ptr<Nature> c)
{
children.push_back(c);
}
template<typename...Args>
typename std::enable_if<0==sizeof...(Args), void>::type
add(const Leaf& t,Args...more)
{
children.push_back(std::make_shared<Leaf>(t));
};
template<typename...Args>
typename std::enable_if<0==sizeof...(Args), void>::type
add(const Tree& t,Args...more)
{
children.push_back(std::make_shared<Tree>(t));
};
template<typename...Args>
typename std::enable_if<0<sizeof...(Args), void>::type
add(const Leaf& t,Args...more)
{
children.push_back(std::make_shared<Leaf>(t));
add(more...);
};
template<typename...Args>
typename std::enable_if<0<sizeof...(Args), void>::type
add(const Tree& t,Args...more)
{
children.push_back(std::make_shared<Tree>(t));
add(more...);
};
void nature_method() override
{
std::cout << " Tree=="<< value;
for (int i = 0; i < children.size(); i++)
children[i]->nature_method();
}
}
I could implement the overload operator [] to return a pointer to Nature or a Nature object, like so:
Nature& operator[] (int x) {
return *children[x];
}
std::shared_ptr< Nature > operator[] (int x) {
return children[x];
}
In both cases, the return type is Nature related. This because it could be a Leaf or a Tree, which is not known in advance. But since the return type of the operator has to be known at compile time, I cannot do something else.
However, if the returned type would be Tree related, I cannot use the operator [] anymore, because I have enforced it to be Nature.
How can I dynamically choose the return type, Tree or Leaf related, of []? Is there any workaround for this?
I could consider operator [] a virtual method in the Nature class, but still I would no what to make out of this.
I have read about covariant types as well, but I do not know if they would be applicable here.
Thank you.
In the simplest possible example, let's say I have a function that starts a thread, which sets the value of a local variable to true. We join the thread, then leave the function.
bool func() {
bool b = false;
std::thread t([&]() { b = true; });
t.join();
return b;
}
Will this function return true, or is the behavior undefined?
In the following code, is using atomics necessary to guarantee race-free semantics on all platforms or does the use the use of a promise.set_value/future.wait imply some kind of implicit memory barrier that would allow me to rely on the flag write having become visible to the outer thread?
std::atomic_bool flag{false}; // <- does this need to be atomic?
runInThreadPoolBlocking([&]() {
// do something
flag.store(true);
});
if (flag.load()) // do something
// simplified runInThreadPoolBlocking implementation
template <typename Callable>
void runInThreadPoolBlocking(Callable func)
{
std::promise<void> prom;
auto fut = prom.get_future();
enqueueToThreadPool([&]() {
func();
prom.set_value();
});
fut.get();
}
In general, are there any "implicit" memory barriers guaranteed by the standard for things like thread.join() or futures?
How to implement the addInfo function. We have to find and sort the lines based on their serial number using chaining hash function. But before I need to do addInfo. For example: the first line "1009 1 "Royal Queen" 2015 160" the serial number is 1009 and if there is other ships that have the serial number ended with 9 we have to display them together. Here is the code that I have so far:
#include <iostream>
#include <fstream>
using namespace std;
struct ShipRecord
{
int serialNum;
int shipType;
string name;
int year;
int cap;
ShipRecord *next;
ShipRecord(int x)
{
serialNum = x;
next = nullptr;
}
};
const int SIZE = 10;
class HashMgr
{
ShipRecord *head = nullptr;
ShipRecord *tail = nullptr;
public:
HashMgr()
{
ShipRecord * hashTable[SIZE] = {nullptr};
string line;
ifstream myfile;
myfile.open("shipRecords.txt");
if(myfile.is_open())
{
while (!myfile.eof())
{
getline (myfile, line);
addInfo(line);
}
myfile.close();
}
}
addInfo(string line)
{}
displayOne(int serialNum)
{}
displayAll()
{}
int main()
{
HashMgr hm;
hm.displayAll();
hm.displayOne(1009);
hm.displayOne(1010);
hm.displayOne(1019);
hm.displayOne(1029);
hm.displayOne(1039);
hm.displayOne(1014);
hm.displayOne(1008); /// Prompt a message to that the record does not exist
hm.deleteOne(1009);
hm.deleteOne(1039);
hm.displayAll();
return 0;
}
/*
Here is the txt.file
1009 1 "Royal Queen" 2015 160
1010 2 "Carnival" 2016 1600
1019 1 "Ocean King" 2013 110
1029 2 "Royal Prince" 2012 2000
1039 2 "Royal Princess" 2010 2100
1014 2 "Royal Caribbean" 2016 1600
*/