Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
In the below code snippet, from ReadFile() function I am calling SetParams() and Execute() multiple times.
Can I optimize each SetParams() and Execute() with single call?
bool SubscriptionRead::ReadFile()
{
IVerification* pReader = new FileReader();
std::wstring oemPathPublicKey(oemFolderPath)
, oemPathSessionKey(oemFolderPath)
, oemPathUserChoices(oemFolderPath);
oemPathPublicKey.append(PUBLIC_KEY_FILE);
oemPathSessionKey.append(SESSION_KEY_FILE);
oemPathUserChoices.append(USERCHOICES_FILE);
pReader->SetParams((wchar_t*)oemPathPublicKey.c_str(), L"file");
pReader->Execute();
pReader->SetParams((wchar_t*)oemPathSessionKey.c_str(), L"file");
pReader->Execute();
pReader->SetParams((wchar_t*)oemPathUserChoices.c_str(), L"file");
pReader->Execute();
return True;
}
void FileReader::SetParams(wchar_t* wszParams, wchar_t* wszParamType)
{
m_wszParamType = wszParamType;
m_wszParams = wszParams;
}
bool FileReader::Execute()
{
if (wcscmp(m_wszParamType, L"registry") == 0)
{
function1();
}
else
{
function2();
}
return true;
}
If your problem is calling the functions with different paras, in different lines, you can use std::ref as follows to iterate through the initializer_list of reference wrapper to the objects(i.e. std::wstring s), which reduces some typing:
#include <functional> // std::ref
#include <initializer_list> // std::initializer_list
bool SubscriptionRead::ReadFile()
{
IVerification* pReader = new FileReader();
// .... other code
for(auto strKey: {std::ref(oemPathPublicKey), std::ref(oemPathSessionKey), std::ref(oemPathSessionKey)})
{
pReader->SetParams((wchar_t*)strKey.c_str(), L"file");
pReader->Execute(); // does it needed to executed for every path? if no: outside the loop!
}
return True;
}
Also note that, in modern C++ you have smart pointers. Therefore use them, whenever appropriate and avoid manual memory allocations.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?
class A {
//..implementation
int id() { return 1; }
};
class B {
//..implementation
int id() { return 2; }
bool hasSmth() { return true; }
};
int main()
{
auto obj = someFunction();//returns A or B
if (obj.id() == 1 || (obj.id() == 2 && obj.hasSmth())) {
...
}
}
If the function returns obj of type B, then we are good.
But if it returns obj of type A, compiler will complain about A not having hasSmth, regardless of that part of if never been evaluated.
Can someone give a workaround please?
Can someone give a workaround please?
Read the declaration of someFunction to see what it returns. In the case it doesn't return B, then don't write obj.hasSmth(). Problem solved.
Now, let's change the question a bit. Let's say that you want to make this work without knowing the return type. Perhaps because rather than main you may be actually writing a template that works with different types. There are several approaches, but function overloads are a simple one:
bool check([[maybe_unused]] const A&) {
return true;
}
bool check(const B& b) {
return b.hasSmth();
}
template<bool returnsA>
void foo() {
auto obj = someTemplate<returnsA>(); // returns A or B
if (check(obj)) {
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
typedef std::priority_queue< Task*, std::vector< Task* > > Priority_Q;
class TaskQueue : public Priority_Q
{
public:
TaskQueue();
// Queue op
void push(Task* t){
Priority_Q::push(t);
}
void pop(){
Priority_Q::pop();
}
}
Is it the correct way to use priority_queue. I will be pushing objects derived from Task and popping it.
It should be easier to write a wrapper class and make STL priority_queue a member variable. But to make sure you set up the custom comparator for your queue, otherwise the STL data structure won't know how to order your objects. There are a couple of ways to do it. I'm just using one as example here.
If you want to add synchronization to your data structure, you can simple add internal locks and/or condition variables in your class to lock/unlock the member variable q.
class TaskQueue {
public:
TaskQueue() {};
bool empty() {
return q.empty()
}
void push(Task* t) {
q.push(t);
}
void pop() {
if (q.empty()) {
// You may want to do something here like throw an exception or not
}
// if not empty
q.pop();
}
Task* top() {
if (q.empty()) {
// You may want to do something here like throw an exception or not
}
return q.top();
}
private:
class TaskPtrComparator {
public:
bool operator()(Task* t1, Task* t2) {
// Comparison code here
}
};
priority_queue<Task*, vector<Task*>, TaskPtrComparator> q;
};
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My class has an array of objects, call it Foo. It is stored as Foo* m_Foos in the class. Say it has a value at [0], guaranteed, and Foo has a property called IsSetthat's just a bool or something.
void TryThis()
{
Foo returnValue;
GetValue(returnValue);
returnValue.IsSet = true;
if(m_Foo[0].IsSet != returnValue.IsSet)
{
// ERROR!!!!
}
}
void GetValue(Foo &container)
{
container = m_Foos[0];
}
Can anyone explain why m_Foo[0] =/= returnValue? Where is the error in my syntax?
I expect m_Foo[0] to be the same reference as returnValue, the same Foo in memory.
TryThis() is not modifying the Foo object that is stored in the m_Foos array.
GetValue() is assigning the Foo object from m_Foos[0] to another Foo object that is local to TryThis(). A copy is being made during that assigment. TryThis() is then modifying the copy, not the original.
If you want TryThis() to modify the original Foo object directly, you need to do something more like this instead:
void TryThis()
{
Foo &returnValue = GetValue();
returnValue.IsSet = true;
// m_Foo[0] is set true.
}
Foo& GetValue()
{
return m_Foos[0];
}
Or this:
void TryThis()
{
Foo *returnValue;
GetValue(returnValue);
returnValue->IsSet = true;
// m_Foo[0] is set true.
}
void GetValue(Foo* &container)
{
container = &m_Foos[0];
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following function:
CompareType CompareByCitizensNum(const City& c1, const City& c2) {
if (c1.getNumCitizens() > c2.getNumCitizens()
|| ((c1.getNumCitizens() == c2.getNumCitizens())
&& (c1.getCityId() > c2.getCityId()))) {
return BIGGER;
} else if (c1.getCityId() == c2.getCityId()) {
return EQUALS;
}
return SMALLER;
}
and this is the method that needs to use this function:
avlTreeVertix(City newKey, avlTreeVertix* fatherToBe,
CompareType (*compare)(const City&, const City&)) :
bf(0), key(newKey), RightHigh(0), LeftHigh(0), vertexesInSubTree(1), father(
fatherToBe), childL(NULL), childR(
NULL), compare(compare) {
CHECK_NULL(father,);
if (compare(key, father->key) == BIGGER) {
//if (isGreater(father)) {
father->childR = this;
} else {
father->childL = this;
}
}
I tried to call it by the following line:
rankTree = new avlTreeVertix(c, NULL, CompareByCitizensNumx);
But it says:
no matching function for call to wet2::avlTreeVertix::avlTreeVertix(wet2::City&, NULL, <unresolved overloaded function type>)
Any ideas?
Thanks!
OK guys, the problem was that the function was a member function, so I needed to add a "static" at the function decleration and now it's working! fool on me..
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is a sample program for my problem, I am using VisualStudio 2008
void abc()
{
static int i = 0;
if (i==0)
{
xyz();
i++;
}
abc();
}
The static variable retain the value one in next debug session also, thus not calling xyz(), how can I call a function just once without using static variable??
How about this:
void abc(int init)
{
if(init == 1) xyz();
abc(0);
}
int main(void) {
abc(1);
}
It has the advantage of showing clearly what is going on. You could even declare an enum:
enum INIT {FIRST_TIME, RECURSING};
and do
void abc(enum INIT init) {
if(init == FIRST_TIME) xyz();
abc(RECURSING):
}
You can see a complete example at work at http://codepad.org/7euiC5LQ
#include <stdio.h>
enum INIT {FIRST, RECURSING};
void abc(enum INIT init) {
if(init == FIRST) {
printf("first time\n");
abc(RECURSING);
}
else {
printf("last time\n");
}
}
int main(void) {
abc(FIRST);
}
In this example, the second time is the last time. Obviously you can embellish from there; usually you will want to pass a parameter to your abc function that might decrease with each call until you reach some point that says "this is the end of the recursion" (think factorials, Fibonacci, etc). In that case, passing an "invalid" parameter (e.g. -1) for the initial call would be a good solution. You still have only one parameter.
Finally - when you are using C++, you could consider overloading your function. Call it with a parameter, and you include xyz; call it without, and you don't. A bit like the abcStart of one of the other answers. But since you tagged your question both C and C++, and there was no evidence in your code that you really intended C++, I am not even going there...
You can pass a callflag to abc() function as an indication that whether to call xyz() function or not.
void abc(int callflag){
// do somwork
if(callflag)
xyz(); // xyz() willbe called when callflag = !0
// do other stuff
abc(0)
}
void abcStart(){
abc(1);
//abc(0); If you don't want to call xzy even for first time.
}
I think this is flexible call xyz() within abc() whenever you wants.
Not sure this is what you're looking for but it works
void abc(){
abc();
}
void abcStart(){
xyz();
abc();
}
int main(){
abcStart();
}
Doing this you don't need to specify any flag or use any if. You just call the "start" function of your recursion
Use a Boolean variable in the caller and pass it to the called function.
#include <stdbool.h> // C99 and latter supports.
void abc(bool flag)
{
if (flag)
{
xyz();
flag = false;
}
abc(flag);
}
int main(void) // T is return type
{
...
bool flag = true;
abc(flag);
...
}
Here's a solution which doesn't hard code it to running xyz a single time i.e. you could later trivially change it to run it an arbitrary number of times (credit to Floris whose answer I adapted):
void abc(int i)
{
if(i > 0)
{
xyz();
i--;
}
abc(i);
}
int main()
{
abc(1);
}