I've been looking around the web and this site for an answer to this scenario but everything I've come across is about reading it from an outside file or changing what the command is in the code but not changing what it does. I'm just messing around with code to refresh myself before I do anything practical. I'm verifying that certain constants are equal to a number that I have specified. (I've never posted here and I've been doing this all day so I'm not taking the time to learn the code insert tags.)
string one = "CHAR_MAX"; // <<< I know this doesn't work. It's what I am
// trying to do in the loop.
if (one == 127)
cout << "Max char count: " << CHAR_MAX << ">>> Pass >>> " one;
I know there are other only slightly more tedious ways to accomplish this. But I'm fairly sure there is a way to do this without an external .txt file to be read from and I've spent far too long trying to figure it out. It's driving me crazy and it's been almost 3 hours since I got to this.
Edit:
I'll look more into the 'constexpr' but from what I'm seeing I think it may. There are numerous other ways for me to complete this yes. I just want to understand a way in that backwards manner. For comprehension. As for as intentions (unless you mean something other with 'intend') go I'm looking at different ways to accomplish a silly program that has several variable limit constants. Like min long, max long, short, max int, etc. And I was thinking of ways to compare them with what the number is. Not for any reason to use. It'd be completely useless because they are predefined. I just thought of assigning the commands (forget what they are referred to in source code) such as CHAR_MAX to a variable that changes along with a for loop after outputting the results. I would have to define them in a list prior but I just couldn't figure out how. (Also: Thanks to the mod who changed my code block to read correctly.)
2nd Edit: Take all variable limits. 18446744073709551615 for unsigned long long. 4294967295 for long (not sure why it's this way, int is the same). Get those numbers with associated commands but by means of a for loop where the command is equal to a variable. (AKA 1 or even "one") It doesn't matter the name as long as it can contain the same command. I have a feeling "variable" is an incorrect way to phrase this but you'd be storing it with a changeable memory assigned call that you can use in a for loop by incrementing a counter for that loop and outputting an
if(*command-as-variable* == *what that number is as a corresponding number*)
cout << "Pass";
else cout << "Fail";
enter code here
Depending on the circumstances I associate the terms with it COULD fail but if everything works correctly it should not. Like I said, Meaningless. Just a different way I could more efficiently write this code instead of having 19 different cout statements. It's how to execute the idea I am trying to find out.
I still haven't looked at what constexpr is for but I am about to pass out now. It's been a long day. I'll edit this tomorrow after I look. Or if it's explained that'd be even better! :)
You are assigning a text string to a string variable, then comparing a string variable to an integer. Your compiler should generate at least some warnings.
Maybe you want this:
constexpr int one = CHAR_MAX;
if (one == 127)
//...
The CHAR_MAX is a predefined constant (identifier/macro).
You could also do this:
if (CHAR_MAX == 127)
{
//...
Related
When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?
I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus.
for (unsigned int i = 0; i < someThing.length(); i++) {
SomeThing var = someThing.at(i);
// You get the idea.
}
I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems' part.
I was glad to find a good conversation on this subject, as I hadn't really given it much thought before.
In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case).
unsigned starts to make more sense when:
You're going to do bitwise things like masks, or
You're desperate to to take advantage of the sign bit for that extra positive range .
Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against).
In your example above, when 'i' will always be positive and a higher range would be beneficial, unsigned would be useful. Like if you're using 'declare' statements, such as:
#declare BIT1 (unsigned int 1)
#declare BIT32 (unsigned int reallybignumber)
Especially when these values will never change.
However, if you're doing an accounting program where the people are irresponsible with their money and are constantly in the red, you will most definitely want to use 'signed'.
I do agree with saint though that a good rule of thumb is to use signed, which C actually defaults to, so you're covered.
I would think that if your business case dictates that a negative number is invalid, you would want to have an error shown or thrown.
With that in mind, I only just recently found out about unsigned integers while working on a project processing data in a binary file and storing the data into a database. I was purposely "corrupting" the binary data, and ended up getting negative values instead of an expected error. I found that even though the value converted, the value was not valid for my business case.
My program did not error, and I ended up getting wrong data into the database. It would have been better if I had used uint and had the program fail.
C and C++ compilers will generate a warning when you compare signed and unsigned types; in your example code, you couldn't make your loop variable unsigned and have the compiler generate code without warnings (assuming said warnings were turned on).
Naturally, you're compiling with warnings turned all the way up, right?
And, have you considered compiling with "treat warnings as errors" to take it that one step further?
The downside with using signed numbers is that there's a temptation to overload them so that, for example, the values 0->n are the menu selection, and -1 means nothing's selected - rather than creating a class that has two variables, one to indicate if something is selected and another to store what that selection is. Before you know it, you're testing for negative one all over the place and the compiler is complaining about how you're wanting to compare the menu selection against the number of menu selections you have - but that's dangerous because they're different types. So don't do that.
size_t is often a good choice for this, or size_type if you're using an STL class.
This is a very simple question, but unfortunately, I am stuck and do not know what to do. My program is a simple program that keeps on accepting 3 numbers and outputs the largest of the 3. The program keeps on running until the user inputs a character.
As the tittle says, my question is how I can make this execute faster ( There will be a large amount of input data ). Any sort of help which may include using a different algorithm or using different functions or changing the entire code is accepted.
I'm not very experienced in C++ Standard, and thus do not know about all the different functions available in the different libraries, so please do explain your reasons and if you're too busy, at least try and provide a link.
Here is my code
#include<stdio.h>
int main()
{
int a,b,c;
while(scanf("%d %d %d",&a,&b,&c))
{
if(a>=b && a>=c)
printf("%d\n",a);
else if(b>=a && b>=c)
printf("%d\n",b);
else
printf("%d\n",c);
}
return 0;
}
It's working is very simple. The while loop will continue to execute until the user inputs a character. As I've explained earlier, the program accepts 3 numbers and outputs the largest. There is no other part of this code, this is all. I've tried to explain it as much as I can. If you need anything more from my side, please ask, ( I'll try as much as I can ).
I am compiling on an internet platform using CPP 4.9.2 ( That's what is said over there )
Any sort of help will be highly appreciated. Thanks in advance
EDIT
The input is made by a computer, so there is no delay in input.
Also, I will accept answers in c and c++.
UPDATE
I would also like to ask if there are any general library functions or algorithms, or any other sort of advise ( certain things we must do and what we must not do ) to follow to speed up execution ( Not just for this code, but in general ). Any help would be appreciated. ( and sorry for asking such an awkward question without giving any reference material )
Your "algorithm" is very simple and I would write it with the use of the max() function, just because it is better style.
But anyway...
What will take the most time is the scanf. This is your bottleneck. You should write your own read function which reads a huge block with fread and processes it. You may consider doing this asynchronously - but I wouldn't recommend this as a first step (some async implementations are indeed slower than the synchronous implementations).
So basically you do the following:
Read a huge block from file into memory (this is disk IO, so this is the bottleneck)
Parse that block and find your three integers (watch out for the block borders! the first two integers may lie within one block and the third lies in the next - or the block border splits your integer in the middle, so let your parser just catch those things)
Do your comparisions - that runs as hell compared to the disk IO, so no need to improve that
Unless you have a guarantee that the three input numbers are all different, I'd worry about making the program get the correct output. As noted, there's almost nothing to speed up, other than input and output buffering, and maybe speeding up decimal conversions by using custom parsing and formatting code, instead of the general-purpose scanf and printf.
Right now if you receive input values a=5, b=5, c=1, your code will report that 1 is the largest of those three values. Change the > comparisons to >= to fix that.
You can minimize the number of comparisons by remembering previous results. You can do this with:
int d;
if (a >= b)
if (a >= c)
d = a;
else
d = c;
else
if (b >= c)
d = b;
else
d = c;
[then output d as your maximum]
That does exactly 2 comparisons to find a value for d as max(a,b,c).
Your code uses at least two and maybe up to 4.
Many times people will combine a boolean check by just re-using an int variable they already have and checking for -1 if something exists or not.
However, what if someone wants to use unsigned integers but still wants to use this method and also where 0 actually has a different meaning besides existance.
Is there a way to have a data range be -1 to 4,294,967,294?
The obvious choice here is to just use a bool that detects what you are after but it is my understanding that a bool is a byte, and can really add to the storage size if you have an array of structs. This is why I wondered if there was a way to get the most useful numbers you can (postivies) all while leaving just one number to act as a flag.
Infact, if it is possible to do something like shifting the data range of a data type, it would seem like shifting it to something like -10 to 4,294,967,285 would allow you to have 10 boolean flags at no additional cost (bits).
The obvious hacky method here is just to add whatever number to what your storing and remember to account for it later on, but I wanted to keep it a bit more readable (I guess if thats the case I shouldnt even be using -1, but meh).
If you simply want to pick a value which can not exist in your interpretation of the variable and to use it to indicate an exception or error value, why not to simply do it? You can take such a value, define it as a macro and use it. For example if you are sure that your variable never reaches the max limit, put:
#define MY_FUN_ERROR_VALUE (UINT_MAX)
then you can use it as:
unsigned r = my_function_maybe_returning_error();
if (r == MY_FUN_ERROR_VALUE) {handle error}
you shall also ensure that my_function_maybe_returning_error does not return MY_FUN_ERROR_VALUE in normal conditions when actually no error happens. For this you may use an assert:
unsigned my_function_maybe_returning_error() {
...
// branch going to return normal (not error) value r
assert(r != MY_FUN_ERROR_VALUE);
return(r);
}
I do not see anything wrong on this.
You just asked how to use a value that can be 0 or something greater than 0 to hold the three states: whatever 0 means, something greater than 0, and does not exist. So no, (by the pigeonhole principle I guess) it's not possible.
Nor should it be. Overloading a variable is bad practice unless you're down to your last 3 bytes left of RAM, which you almost certainly aren't. So yes, please use another variable with a correct name and clear purpose.
I've been messing around in C++ a little bit but I'm still pretty new. I searched around a little bit and even using the keywords of exactly the problem I am trying to tackle yields no results. Basically I am just trying to figure out how to tell if a variable has no data. I have a file that my program reads and it searches for a specific character within that file and basically uses delimiters to determine where to store the actual data in a variable. Now I added some comments in the file saying that it should not be edited which has caused me some problems. So I pretty much want to count the number of comments, but I'm not sure how to do it because the way I had it set up was resulting in huge numbers being returned. So I figured I would attempt to fix it with a simple if statement to see if there was any data in the array while it was running the loop, and if there was then simply add +1 to my variable. Needless to say it did not work. Here's the code. And if you know a better way of doing this, by all means please do share.
size_t arySearchData[20];
size_t commentLines[20];
size_t foundDelimiter;
size_t foundComment;
int commentsNum;
foundDelimiter = lineText.find("]");
foundComment = lineText.find("#");
if (foundComment != std::string::npos) {
commentLines[20] = int(foundComment);
if (foundComment = <PROBLEM>){
commentsNum++;
}
}
So it successfully gets the two comments in my file and recognizes that they are located at the first index(0) in each line but when I tried to have it just do commentsNum++ in my first if statement it just comes up with tons of random numbers, and I am not sure why. So as I said my problem is within the second if statement, I need a void or just a better way to solve this. Any help would be greatly appreciated.
And yes I do realize I could just determine if there 'was' data in the there rather than being void or null but then it would have to be specific and if the comment (#) had a space before it, then it would render my method of reading the file useless as the index will have changed.
A variable in C++ always contains data, just it may not be initialised.
int i;
It will have some value, what it is can't be determined until you do something like
i = 1337;
until you do that the value of i will be what ever happened to be in the memory location that i has been assigned to.
The compile may pick up on the fact that you are trying to use a variable which you have not actually given a value your self, but this will normally just be a warning, as their is nothing wrong as such with doing so
You do not initialize commentsNum. Try this:
int commentsNum = 0;
In C++ other than static variables, other variables are assigned undetermined values. This is primarily done to adhere to underlying philosophy -- "you don't pay for things you don't use", so it doesn't zero that memory by default." However, for static variables, memory is allocated at link time. Unlike runtime initialization, which would need to happen in local variables, link time allocation and initialization incur low cost.
I would recommend hence setting int commentsNum = 0;
The Given Problem:
Given a theater with n rows, m seats, and a list of seats that are reserved. Given these values, determine how many ways two friends can sit together in the same row.
So, if the theater was a size of 2x3 and the very first seat in the first row was reserved, there would be 3 different seatings that these two guys can take.
The Problem That I'm Dealing With
The function itself is supposed to return the number of seatings that there are based on these constraints. The return value is a long long.
I've gone through my code many many times...and I'm pretty sure that it's right. All I'm doing is incrementing this one value. However, ALL of the values that my function return differ from the actual solution by 1 or 2.
Any ideas? And if you think that it's just something wrong with my code, please tell me. I don't mind being called an idiot just as long as I learn something.
Unless you're overflowing or underflowing, it definitely sounds like something is wrong with your code. For integral types, there are no precision ambiguities in c or c++
First, C++ doesn't have a long long type. Second, in C99, long long can represent any integral value from LLONG_MIN (<= -2^63) to LLONG_MAX (>= 2^63 - 1) exactly. The problem lies elsewhere.
Given the description of the problem, I think it is unambiguous.
Normally, the issue is that you don't know if the order in which the combinations are taken is important or not, but the example clearly disambiguate: if the order was important we would have 6 solutions, not 3.
What is the value that your code gives for this toy example ?
Anyway I can add a few examples with my own values if you wish, so that you can compare against them, I can't do much more for you unless you post your code. Obviously, the rows are independent so I'm only going to show the result row by row.
X occupied seat
. free seat
1: X..X
1: .X..
2: X...X
3: X...X..
5: ..X.....
From a computation point of view, I should note it's (at least) an O(N) process where N is the number of seats: you have to inspect nearly each seat once, except the first (and last) ones in case the second (and next to last) are occupied; and that's effectively possible to solve this linearly.
From a technic point of view:
make sure you initialize your variable to 0
make sure you don't count too many seats on toy example
I'd be happy to help more but I would not like to give you the full solution before you have a chance to think it over and review your algorithm calmly.