if() skipping my variable check - c++

I have following code:
std::vector<std::string> GetSameID(std::vector<string>& allFiles, int id) {
std::vector<std::string> returnVector;
for(std::vector<string>::iterator it = allFiles.begin(); it != allFiles.end(); ++it) {
if(GetID(*it) == id) {
int index = (*it).find("_CH2.raw");
if(index > 0) {
continue; //this works
}
if(0 < ((*it).find("_CH2.raw"))) {
continue; //this doesn't
}
string ext = PathFindExtension((*it).c_str());
if(ext == ".raw") {
returnVector.push_back(*it);
}
}
}
return returnVector;
}
My issue is, why is the if(0 < ((*it).find("_CH2.raw"))) not working that way? My files are named
ID_0_X_0_Y_128_CH1.raw
ID_0_X_0_Y_128_CH2.raw
(different ID, X and Y, for Channel 1 and Channel 2 on the oscilloscope).
When I do it the long way around (assign index, and then check index), it works, I don't understand though why the short version, which is more readable imo, is not working.

According to http://en.cppreference.com/w/cpp/string/basic_string/find, string::find() returns a size_t -- which is an unsigned type -- so it can never be less-than zero.
When it doesn't find something, it returns string::npos, which is also an unsigned type, but when you shove it into an int (implicitly converting it) it becomes a negative value -- this is why your first set of code works.

Related

Adding int to long

I am creating a recursive formula to add up all the elements in a vector. The problem them I'm having is that my result is not adding to the vector results so it always returns 0. I have tried static_cast to turn it into an int but I'm still not able to figure it out. Here's my code:
long vectorSum(const std::vector<int>& data, unsigned int position) {
int ret = 0;
if(position == data.size()-1) {
return ret;
} else {
ret += data[position];
return vectorSum(data, position+1);
}
}
I am calling the function like this:
std::vector<int> test1;
for(int i = 0; i < 10; i++) {
test1.push_back(i);
}
cout << vectorSum(test1, 0) << "\n";
This is not correct:
ret += data[position];
return vectorSum(data, position+1);
The new value of ret (+= data[position]) isn't being used anywhere or passed back to the caller.
Remeber: ret is strictly local to each invocation of vectorSum(). It doesn't exist outside of your vectorSum(); it's being set to "0" every time you invoke vectorSum().
long vectorSum(const std::vector<int>& data, unsigned int position) {
if(position == data.size())
return 0;
else
return data[position]+vectorSum(data, position+1);
}
Then call it as
int sum=vectorSum(data,0);
Normally, one adds to the value of a recursive call. You are not doing that. In your code, it will keep calling with a modified position until it hits the terminating condition, then that return 0; goes all the way back up to the caller.
long vectorSum(const std::vector<int>& data, unsigned int position) {
int ret = 0;
if(position == data.size()-1) {
return ret;
} else {
ret += data[position]; //this line has no affect on the result!
return vectorSum(data, position+1); //you don't accumulate anything
//this will always return 0
}
}
Instead, you want to add the current value plus the value from the recursive call:
long vectorSum(const std::vector<int>& data, unsigned int position) {
if(position == data.size()-1) {
//terminating condition, return 0
return 0;
} else {
//add current value plus value from processing the rest of the list
return data[position] + vectorSum(data, position+1);
}
}
As a side note: recursion is a great tool, but it can easily be misused by applying it to problems that already have better and more elegant solutions. For this, something like std::accumulate would probably be the most "natural" solution for C++.

C++ std::set<string> Alphanumeric custom comparator

I'm solving a problem with a sorting non-redundant permutation of String Array.
For example, if input string is "8aC", then output should be order like {"Ca8","C8a", "aC8", "a8C", "8Ca", "9aC"}.I chose C++ data structure set because each time I insert the String into std:set, set is automatically sorted and eliminating redundancy. The output is fine.
But I WANT TO SORT SET IN DIFFERENT ALPHANUMERIC ORDER which is different from default alphanumeric sorting order. I want to customize the comparator of set the order priority like: upper case> lower case > digit.
I tried to customize comparator but it was quite frustrating. How can I customize the sorting order of the set? Here's my code.
set<string, StringCompare> setl;
for (i = 0; i < f; i++)
{
setl.insert(p[i]); //p is String Array. it has the information of permutation of String.
}
for (set<string>::iterator iter = setl.begin(); iter != setl.end(); ++iter)
cout << *iter << endl; //printing set items. it works fine.
struct StringCompare
{
bool operator () (const std::string s_left, const std::string s_right)
{
/*I want to use my character comparison function in here, but have no idea about that.
I'm not sure about that this is the right way to customize comparator either.*/
}
};
int compare_char(const char x, const char y)
{
if (char_type(x) == char_type(y))
{
return ( (int) x < (int) y) ? 1 : 0 ;
}
else return (char_type(x) > char_type(y)) ? 1 : 0;
}
int char_type(const char x)
{
int ascii = (int)x;
if (ascii >= 48 && ascii <= 57) // digit
{
return 1;
}
else if (ascii >= 97 && ascii <= 122) // lowercase
{
return 2;
}
else if (ascii >= 48 && ascii <= 57) // uppercase
{
return 3;
}
else
{
return 0;
}
}
You are almost there, but you should compare your string lexicographically.
I roughly added small changes to your code.
int char_type( const char x )
{
if ( isupper( x ) )
{
// upper case has the highest priority
return 0;
}
if ( islower( x ) )
{
return 1;
}
if ( isdigit( x ) )
{
// digit has the lowest priority
return 2;
}
// something else
return 3;
}
bool compare_char( const char x, const char y )
{
if ( char_type( x ) == char_type( y ) )
{
// same type so that we are going to compare characters
return ( x < y );
}
else
{
// different types
return char_type( x ) < char_type( y );
}
}
struct StringCompare
{
bool operator () ( const std::string& s_left, const std::string& s_right )
{
std::string::const_iterator iteLeft = s_left.begin();
std::string::const_iterator iteRight = s_right.begin();
// we are going to compare each character in strings
while ( iteLeft != s_left.end() && iteRight != s_right.end() )
{
if ( compare_char( *iteLeft, *iteRight ) )
{
return true;
}
if ( compare_char( *iteRight, *iteLeft ) )
{
return false;
}
++iteLeft;
++iteRight;
}
// either of strings reached the end.
if ( s_left.length() < s_right.length() )
{
return true;
}
// otherwise.
return false;
}
};
Your comparator is right. I would turn parameters to const ref like this
bool operator () (const std::string &s_left, const std::string &s_right)
and start by this simple implementation:
return s_left < s_right
This will give the default behaviour and give you confidence you are on the right track.
Then start comparing one char at the time with a for loop over the shorter between the length of the two strings. You can get chars out the string simply with the operator[] (e.g. s_left[i])
You're very nearly there with what you have.
In your comparison functor you are given two std::strings. What you need to do is to find the first position where the two strings differ. For that, you can use std::mismatch from the standard library. This returns a std::pair filled with iterators pointing to the first two elements that are different:
auto iterators = std::mismatch(std::begin(s_left), std::end(s_left),
std::begin(s_right), std::end(s_right));
Now, you can dereference the two iterators we've been given to get the characters:
char c_left = *iterators.first;
char c_right = *iterators.second;
You can pass those two characters to your compare_char function and it should all work :-)
Not absoloutely sure about this, but you may be able to use an enumerated class towards your advantage or an array and choose to read from certain indices in which ever order you like.
You can use one enumerated class to define the order you would like to output data in and another that contains the data to be outputed, then you can set a loop that keeps on looping to assign the value to the output in a permuted way!
namespace CustomeType
{
enum Outs { Ca8= 0,C8a, aC8, a8C, 8Ca, 9aC };
enum Order{1 = 0 , 2, 3 , 4 , 5};
void PlayCard(Outs input)
{
if (input == Ca8) // Enumerator is visible without qualification
{
string[] permuted;
permuted[0] = Outs[0];
permuted[1] = Outs[1];
permuted[2] = Outs[2];
permuted[3] = Outs[3];
permuted[4] = Outs[4];
}// else use a different order
else if (input == Ca8) // this might be much better
{
string[] permuted;
for(int i = 0; i<LessThanOutputLength; i++)
{
//use order 1 to assign values from Outs
}
}
}
}
This should work :
bool operator () (const std::string s_left, const std::string s_right)
{
for(int i = 0;i < s_left.size();i++){
if(isupper(s_left[i])){
if(isupper(s_right[i])) return s_left[i] < s_right[i];
else if(islower(s_right[i]) || isdigit(s_right[i]))return true;
}
else if(islower(s_left[i])){
if(islower(s_right[i])) return s_left[i] < s_right[i];
else if(isdigit(s_right[i])) return true;
else if(isupper(s_right[i])) return false;
}
else if(isdigit(s_left[i])){
if(isdigit(s_right[i])) return s_left[i] < s_right[i];
else if(islower(s_right[i]) || isupper(s_right[i])) return false;
}
}
}

prune recursive search paths

my knowledge is limited, writing in C++ for 2 months
In this function string code is recursively decrements chars until the base case "" is found. I want to prune some paths before the base case is found, and for some string code a path to the base case will not be found. For the prune I want to compare an attribute in the path with parameter int time. This searches a trie made of 'nodeT'
struct charT {
char letter;
nodeT *next;
};
struct nodeT {
bool isOperation;
bool isCode;
int time;
Vector<charT> alpha;
};
nodeT *root
usage:
string code = "12345";
int time = convertToEpoch(20120815); //my epoch function
containsCode(code, time)
bool containsCode(string code, int time)
{
if(root == NULL) return false;
else return containsCodeHelper(root, code, time);
}
bool containsCodeHelper(nodeT *w, string code, int time)
{
if(code == "") //base case: all char found
return w->isCode;
else {
if (w->isOperation && w->time != time) return false; //case 2: time check OK <- at a midpoint in the path
for(int i = 0; i < w->alpha.size(); i++) { //Loop through the leaf
if (w->alpha[i].letter == code[0]) //case 3: leaf exists
return containsCodeHelper(w->alpha[i].next, code.substr(1), time);
}
}
return false; //if no path
}
This function worked well before adding the time check prune, it now loops, returns false if outside time but then starts again with the candidate string code from char location 0.
Questions: 1) Is a nested return false kicking the recursion back to the next call for loop, 2) should the time prune be placed in the for loop with a logical return false or return 'path', 3) is this more fundamentally messed-up and I need to learn a C++ concept <- please explain if yes.
Also, the posted function is a simplified version of the actual function - there is a modifier to time and a 'step over' path that I left out. In past question I found that these 'addons' distract from the question.
after some reworking it now functions fine - possibly it always did; I changed to read attribute return w->isCode to return true, that seemed to be the biggest issue - I will debug the trie constructor and see if it is setting the attribute at the end of each path.
boolcontainsCodeHelper(nodeT *w, string code, int time)
{
if(code == "") //base case: all char found
return true;
else {
if ( w->isOperation && (!((w->begin-wag) <= time && time <= (w->end+wag) ) && time != 9999 ) )
return false; //case 2: time
else {
for(int i = 0; i < w->alpha.size(); i++) { //Loop through all of the children of the current node
if (w->alpha[i].letter == word[0])
return containsCodeHelper(w->alpha[i].next, word.substr(1), time, wag);
else if (word[0] == 'ΕΎ') //step over '0' all subnodes
if (containsCodeHelper(w->alpha[i].next, word.substr(1), time, wag))
return true;
}
}
}
return false; //if char is missing - meaning the exact code is not there - terminates garbage subnode paths
}
I don't see any difference between having return false; at the end and leaving it out. Also still confused as why the special case needs if( bool fn()) return true; rather than just return ( bool fn()); i found that solution through trial and error with help from another stack overflow thread

Subset sum recursion with c++

This is one of the solution of getting true or false from given set and target value
bool subsetSumExists(Set<int> & set, int target) {
if (set.isEmpty()) {
return target == 0;
} else {
int element = set.first();
Set<int> rest = set - element;
return subsetSumExists(rest, target)
|| (subsetSumExists(rest, target- element));
}
}
However, this solution will return true or false value only. How is it possible to get the element that involve in the subset(set that add together will equal to target) as well?
Do I have to use dynamic programming? Coz as i know.. recursion is building up stack actually and after the function return the value, the value inside the frame will be discarded as well.
So, is it possible to get the elements that add up equal to the target value.
Is passing an object a solution of the problem?
Thank you
First of all you can optimize your program a little bit - check if target is 0 and if it is always return true. Now what you need is to have somewhere to store the elements that you have already used. I will show you a way to do that with a global "stack"(vector in fact so that you can iterate over it), because then the code will be easier to understand, but you can also pass it by reference to the function or avoid making it global in some other way.
By the way the stl container is called set not Set.
vector<int> used;
bool subsetSumExists(Set<int> & set, int target) {
if (target == 0) {
cout << "One possible sum is:\n";
for (int i = 0; i < used.size(); ++i) {
cout << used[i] << endl;
}
return true;
} else if(set.empty()) {
return false;
}else {
int element = set.first();
Set<int> rest = set - element;
used.push_back(element);
if (subsetSumExists(rest, target- element)) {
return true;
} else {
used.pop_back();
}
return subsetSumExists(rest, target);
}
}
Hope this helps.

arrays and functions

my assignment requires me to write a function that reads in a title and return the corresponding fee to the calling function. if the title is not in the list, return -1.0.
this is what i have got at the moment:
struct eventType
{
string title;
double fees;
};
eventType eventTable[10];
int findFees (string newTitle, string newFees)
{
int Index = 0;
int flag;
while (Index < 9) && (eventTable[Index].title != newTitle))
Index = Index + 1;
if (eventTable[Index].title == newTitle)
{
eventTable[Index].fees = newFees;
flag = 0;
}
else
flag = -1;
return flag;
}
is anything missing?
update
after looking at the advice u guys have given, i have adopted and changed the codes to:
double findFees (string title)
{
for (int Index = 0 ; Index < 10 ; Index++)
{
if (eventTable[Index].title == title)
{
return eventTable[Index].fees;
}
}
return -1.0;
}
I'm not sure if this is correct either but I do not need a new title or new fees since these values are to be found within eventTable, and return it.
corrections?
I don't want to give away the answer for you, but here are two things you should keep in mind:
When you have a conditional or a loop, you need to surround statements in { and } so that the compiler knows which statements go inside the loop.
Second, C++ is a type-safe language, meaning that if you are assigning variables to a value of a different type, your program won't compile, look through your code and see if you can find anything wrong on that front
It should be:
while (Index < 10)
And you said it should return the fee, but it returns 0 when found. (This is ok, since you are passing in the fee, why return it too?)
I would also change the signature of the function to be:
int findFees (const string &newTitle, const string &newFees)
and while you are at it, have it return a "bool" instead of a flag to denote success since:
if(findFees(blahTitle, blahFees))
sounds a lot better than:
if(findFees(blahTitle, blahFees) == 0)
when checking for whether the title is found.
It seems to me your function does not return the fees, as you described.
It looks like it updates the eventTable, changing the fee stored there, and returns a flag if the update was done successfully.
Please clarify. Do you want to find the fee stored in the eventTable and return it? Or do you want to update the eventTable with new data? Or a hybrid of both.
Still, for a noob, your code is well structured and reasonably well written.
You could simplfy it as so.
int flag = -1;
int Index = 0;
while(Index <= 9)
{
if(eventTable[Index].title == newTitle)
{
eventTable[Index].fees = newFees;
flag = 0
break;
}
}
return flag;
eventTable[Index].fees = newFees;
This won't work because fees is a double and newFees is a string. Also you didn't say anything about changing the fees, so I'm confused by that line.
If you want to return the fees of the item you found, you should just put return eventTable[Index].fees; at that point and change the return value of the function to float.
Your description (return the fee, or -1.0 if not found) does not match your code:
struct eventType
{
string title;
double fees;
};
eventType eventTable[10];
double findFees (string newTitle)
{
for (int Index = 0 ; Index < 10 ; Index++)
{
if (eventTable[Index].title == newTitle)
{
return eventTable[Index].fees;
}
}
return -1.0;
}
The only error I see is
while (Index < 9) && (eventTable[Index].title != newTitle))
should probably be:
while ((Index < 10) && (eventTable[Index].title != newTitle))
Note the missing '('. Otherwise you miss matching the last entry in the array.
I would probably write the function something like:
double findFees (const string& title, double newFee)
{
for (int i = 0; i < 10; i++)
{
if (eventTable[i].title == title)
{
eventTable[i].fees = newFee;
return newFee;
}
}
return -1.0;
}
This way you will not iterate through the entire array if you already found the item you where searching for.