No, it would be a linkage error if you do not initialize them.
ddanbe commented: Nice answer! +15
No, it would be a linkage error if you do not initialize them.
If ur on windows, use Sleep(milliseconds) located on windows.h. If ur on linux use sleep(seconds) located on unistd.h
Also, static variables are initialized to 0, for basic types, by default.
really? I thought you had to explicitly initialize them or else it would be a linkage error. So there is no default initialization.
I don't know what to do. I can't stop thinking about her.
Your probably using it wrong. Try this :
#include <ctime>
#include <iostream>
using namespace std;
int main(){
srand( time(0) ); //seed with different number each execution
for(int i = 0; i < 10; ++i) cout << rand() << endl;
You can create a struct whose sole purpose if to share const global variables, for example :
struct EnvironmentConstants{
static const int TIME_STEP = 1; //in sec
static const int SCREEN_WIDTH = 100; //in pixels
//.. and so on
};
and call it like so :
void update(){
foreach( Entity e : EntityList){
update(*this,EnvironmentConstants::TIME_STEP);
}
}
-1 is still garbage
I think OP is analyzing it way too much. there is no reason why you should rewrite the statement again. Its perfectly clear with its intentions. I think the problem is that you are confused about the theory. You need to just get more practice in first. Then the theory will make more sense because you actually have an concrete understanding of whats being said in the sentence. So for right now, don't waste your time rewriting it. There is no point. Use that free time to go play with friends or something.
How are you representing the binary numbers?
the buffer gets big as it needs to in order to store the input. It grows dynamically as it needs to.
For you example #2, isn't that undefined? You are( or will be) referencing a variable that is out of scope.
In addition to what mike_2000_17 points out, the exception route also gives you finer control over what triggers the exit condition. Any of the iostate flags can be used to control exceptions which enables you to only throw on
failbit
, for instance, instead of also oneofbit
.
But the thing is would you be limited to exactly those bits? So no custom failure would work.
Yes. I understand that user input is a potential for disaster. Consider the following:
#include <iostream> int main() { std::cin.exceptions( std::istream::failbit ); try { int i; std::cin >> i; std::cout << "I got an integer: " << i << std::endl; } catch (std::istream::failure & e) { std::cout << "Exception: " << e.what() << std::endl; } return 0; }
So you can use exceptions to guarantee a type of input is received (this handles the empty input case). However, if you use readline or similar approach where all you get back is a string (or character buffer) you need to roll your own parser and do your own verification.
For instance, if you only want a string and someone provides a number how is the stream to know that is an error? Digits are valid string characters - except maybe in your particular case.
Thats interesting. I never used cin.exception mechanism. I usually just use cin as a boolean arguments.
Just a question, why would one choose that over say this :
int x = 0;
while( !(cin >> x) ){
/* handle error */
}
Just a comment. I find your hierarchy unneeded and wrong. You can easily make a template vector class for the general case, and then typedef certain instantiation of the template vector for easier use.
And have regular function work with the generic template vectors. As a general rule, choose composition over inheritance. So for example, in your particle class, use composition. That way your not limited to one instance of fourvector, and thus you can have a forcevector, position vector and so on.
what constitutes as valid input?
A question on this algorithm :
string random_line(ifstream& file)
{
string line;
string selected_line;
int nlines = 0;
while (getlinefile, line))
if ((rand() % ++nlines) == 0)
selected_line = line;
return selected_line;
}
the while loop only exits if getline fails. getline only fails if it reads the EOF usually. So doesn't that
mean that the algorithm reads the whole file no matter what?
A problem I see by the suggested solutions so far that is, it is inefficient if one calls the function numerous times. So in the long run it will probably be better to read it into a vector and use that vector
to extract lines. That way you get rid of the unknown length problem and you can even use std::random_shuffle to read a random first element. There would only be a one time pay, that is you need to read the whole file once. But I think the benefits one gets from this versus the suggested solution is more.
Some terms to google, function pointers and arrays. Basically, create a typedef of a function pointer, and create an array of that alias.
<iostream> should include <cstring>. i tried adding <cstring>. Same error. I don't know why i always have bad luck with programs that uses string. i know the code works, it would be nice to see it compile properly.
cstring contains c-string functions like strlen and strcpy and so on. string contains std::string class
For the zero problem you can have a cutoff value. Example :
float bandwidthCuttoff(const float value, const float width = 0.000001f){
if(-width <= value && value <= width) return 0.0f;
else return value;
}
then you just pass the j (imaginary part) to this function to make a cut if needed.
I found out list's can't be used to access individual element.
Well it can, but not as fast as arrays. For example :
std::list<int> numbers;
numbers.push_back(10); numbers.push_back(20);
std::list<int>::const_iterator itr = numbers.begin();
while( itr != numbers.end()){
cout << *itr << endl;
++itr;
}
so using iterators you can access individual element but you will have to transverse all elements before it to get to it.
I use to do it, got busy with other stuff. Not sure how many I solved but passed level 1. What problem are you stuck on?
add #include <string>
at the top
You can click on the error and it will take you to that line
This problem comes up so often, maybe we should make some sort of section for problem like these
Another approach is to create your own namespace :
#include <iostream>
using namespace std;
namespace Util{
template<typename T>
T& max(const T& lhs, const T& rhs){ return lhs < rhs ? rhs : lhs ; }
};
int main(){
cout << Util::max(1,2) << endl;
}
Since nodes is of type list of Node you can only add Node into it. For example :
list<Node> nodes;
Node n;
n.name = "test";
nodes.push_back( n );
The second one doesn't complain because it hasn't been instantiated yet. If you call Str like so Str(cp, cp + strlen(cp))
then you would get that same error.
Actually there is little to no reason to make operators virtual, with mild exception to operator=;
As for the syntax you can do this :
struct F{
virtual F& operator+(const F& f)const = 0;
//.. and so on
};
You avoid using it much as possible, instead substitute reference for it. But you might eventually need to use it when you need polymorphism, although you can still use reference, in most cases, pointers might be more practical.
There are couple of option you can choose from :
OPTION #1: Use buffer
const int MAX_SIZE = 1000;
int bufferLength = 0;
int buffer[MAX_SIZE] = {0};
cin >> bufferLength ;
if(bufferLength > MAX_SIZE){ cout << "Error: size to large\n"; return 1; }
for(int i = 0; i < bufferLength; ++i){
//do things with buffer
}
OPTION #2 : dynamic array
int *buffer = 0;
int length = 0;
cin >> length;
buffer = new int[length];
for(int i = 0; i < length; ++i){
//do stuff with buffer
}
delete buffer; //release unused memory
OPTION #3 : std::vector
int length = 0;
cin >> length;
std::vector<int> buffer(length,0);
for(int i = 0; i < buffer.size(); ++i){
//do stuff with buffer
}
There is no such things as stackType use std::stack
srand is in cstdlib. So try to include cstdlib.
srand and rand are in cstdlib. That is what you should include. usually, they might be included indirectly like from iostream library. And usually, you would import ctime library for the time function to generate different seed for srand every run.
And the difference between "3" and '3' in that example is little. "3" is a string that contains '3' and '\0'(null character), thus "3" is null terminated, while '3' is just a char.
since i study alone and my code starts to be more big and more chaotic
i have some questions that maybe will sound silly to more but i have to ask someone.
As with most things, you need to study and work hard yourself. There isn't going to be guru created to make you the best, you have to be your own guru.
1- its better to declare global only the constant variables?
First of all, you should try to avoid global variables as much as possible. If you have no choice then you should encapsulate them.
2- should i create manyyyyy functions small and do simple small tasks each one?
Yes and no. Don't over over do it. But generally, make each function have specific small task. If possible, reduce the function into more function. But be aware, there is always some line, which is subjective.
3- should i let functions take many arguments like that:
Probably not. Try to break the function into sub-function, or maybe even encapsulate things in a struct and pass that struct. Do what make sense.
4- comments!where i should put them?right of each line?or at top of a function or loop?do i need to comment everything?i tried at right of each line and was too messed with many comments
This is a style issue. First put comments where you need it. Don't put comments in areas where the code explains what …
Use std::string
std::string binaryNumber;
cin >> binaryNumber;
for(int i = 0; i < binaryNumber.size(); ++i)
cout << binaryNumber[i] << endl;
Basically anything would be faster.
Well....
float squareRoot(float num){
const float epsilon = 10e-6;
float start = epsilon;
while( start * start < num) start += epsilon;
return start;
}
You should be just setting the root height to 0 then set its left and right height to n+1. No need for get height function.
Just a quick explanation on Abstract Data Type(ADT)
WHO: Abstract Data Type
WHAT: Abstract Data Type are data-type that combines the common functionalities from different related objects into one package, so that those different but related object's interface can inherit from the ADT thus making it more flexible and and less coding for the programmer.
WHERE: Anywhere, when you code, in your life wherever applicable.
WHEN : Use it when you want to generalize a design. When you have many objects that have similar functionalities, you can Abstract the common functionalities into one class, and have the other objects inherit from them.
WHY You would create ADT for numerous reasons. First it generally leads to a flexible design if designed well. Second its less coding for the programmer. Third its more reuseability . Fourth, it leads to easier maintenance. And Fifth, it creates the possibility of polymorphism.
Here is a quick example :
//abstract data type
struct Object{
virtual std::string toString()const = 0;
};
struct Int : Object{
int val;
std::string toString()const{ return boost::lexical_cast<std::string>(val); }
Int(int iVal) : i(iVal){}
};
struct Float: Object{
float val;
std::string toString()const{ return boost::lexical_cast<std::string>(val); }
Float(float fVal) : val(fVal){}
};
int main(){
Int i(0);
Float f(123.456);
std::string strNum = i.toString() + f.toString();
}
You need to deference you pointers
class Temp{
virtual void dr() = 0;
};
>>>>Report the first, 1000th and last elements in your sorted list.
>>It means, you need to sort the array, and print out the last 1000 items in the list.
No, I think it means to print the first, 1000th and last elements. Say you have a std::vector named "my_sorted_array", once it has been sorted, you need to have a printout statement as so:
std::cout << my_sorted_array[0] << std::endl //print the first element. << my_sorted_array[999] << std::endl //print the 1000th element. << my_sorted_array[my_sorted_array.size()-1] << std::endl; //print the last element.
That makes sense, the prof can check that you have a correctly sorted array if those three elements are the same as what he gets from his solution program. (you can also check if your algorithm is correct just by using a simpler, easier sort algorithm or by using std::sort).
Yes you are right.
>>Implement the Random partitioning version of Quicksort
Means simply choose a random partition index from the array.
>>Take care that your data array is not copied (by value) into your subroutines
Means use reference, for example :
void quickSort(float array[] , const int size){
//pick random pivot
partition(array, pivot);
}
void partition(float subArray[], const int size){
}
in that case, the subArray will be the same as array and not a copy of it, since array are reference by default. If you have something like std::vector<int> then you need to pass it by reference explicitly.
void quickSort(std::vector<int>& array){
//pick random pivot
partition(array, pivot);
}
void partition(std::vector<int>& subArray[]){
}
notice the ampersand(i.e '&' ). That tells the compiler not to make a copy of the array and use the same array when passed into the function partition.
>>Report the first, 1000th and last elements in your sorted list.
It means, you need to sort the array, and print out the last 1000 items in the list.
This is what you want( not compiled )
#include <iostream>
#include <string>
using namespace std;
const int MAZE_ROW = 5;
const int MAZE_COL = 5;
void initializeMaze(char maze[MAZE_ROW][MAZE_COL], char initValue){
for(int i = 0; i < MAZE_ROW; ++i){
for(int j = 0; j < MAZE_COL; ++j){
maze[i][j] = initValue;
}
}
}
void printMaze(const char maze[MAZE_ROW][MAZE_COL]){
for(int i = 0; i < MAZE_ROW; ++i){
for(int j = 0; j < MAZE_COL; ++j){
cout << maze[i][j];
}
cout << endl;
}
}
int main(){
char maze[MAZE_ROW][MAZE_COL];
const char WALL = '#';
const char PATH = '+';
initializeMaze(maze,WALL);
printMaze(maze);
}
Now your next step is to implement these functions :
//generate some sort of path in the maze
//does not guarantee that path is solvable
void generatePath(char maze[MAZE_ROW][MAZE_COL]);
//solves the maze
//if solvable, it prints out the path and returns true
//else it returns false
bool solveMaze(const char maze[MAZE_ROW][MAZE_COL]);
Yada yada yada.
You treat her like FWB's then expect her to be your little princess?!
Then you get on your high horse and scream "ALL girls are full of BS". I'm not that smart but I know who is full of BS here...
You could let this one go... Or you can carry on this nonsense, but I said this a long time ago.
Understood.
> if it contains a loop, i.e is a circular linked list
Not exactly. The loop not necessarily includes the head (consider 1->2->3->2). In that case your algorithm will run forever.
The solution takes two pointers traversing the list with different "speeds":
pointer1 <- head pointer2 <- head do: pointer1 <- next(pointer1) pointer2 <- next(next(pointer2)) until - either one of the pointers hits the end of list (not a loop) - or pointer1 becomes equal to pointer2 (loop detected)
Oh I see. I guess I read it wrong. Thanks for the corrections. @OP just make sure you handle the edge cases in this algorithm as well. Ex, if head is null or it only has 1 element.
Surprised none mentioned the use of const.
float computeAverage(const float data[], const int DATA_SIZE){
return std::accumulate(data, data + DATA_SIZE, 0)/ float(DATA_SIZE);
}
To test if it contains a loop, i.e is a circular linked list, what you need to do is transverse through the list, and see if head comes up twice. Here is some psuedo-code.
bool isLoopedLinkedList(const listnode* head){
- bool result = false
- create a listnode headCopy
- while headCopy-> next is not null
- move headCopy next
- check if headCopy equals head
- if so the set result to true and break out of loop
- else continue
- endWhile
}
Line 49 is wrong for sure, it probably should be:
total += data[i*width + j]; //or maybe "data[j*height + i]"
At line 62, the ImageData array was never initialized, so it won't contain the actual pixel values, you should probably use data as above.
For the rest, I think you have it correct, both the mean and stddev.
I think it should be, data[height * i + j]