Posts tagged cpp
C++ Internal Speaker Piano
1If you code in C++ you have probably used the internal speaker for some quick debug of your programs, in Windows, we can use the winapi header (windows.h) to access the built in function Beep():
Beep(frequency,duration);
Where frequency is in Hertz and duration in milliseconds.
So here is a quick something I did on C++ out of boredom, it basically uses your keyboard as a piano, playing each note using the PC Internal Speaker
Here is the source code:
#include<iostream> #include <windows.h> #include <conio.h> using namespace std; void p(char note, bool s, int dur,int sc){ float freq; switch(sc){ case 4: switch(note){ case 'C': (!s)?freq=130.81:freq=138.59; break; case 'D': (!s)?freq=146.83:freq=155.56; break; case 'E': (!s)?freq=164.81:freq=164.81; break; case 'F': (!s)?freq=174.61:freq=185.00; break; case 'G': (!s)?freq=196.00:freq=207.65; break; case 'A': (!s)?freq=220.00:freq=233.08; break; case 'B': (!s)?freq=246.94:freq=246.9; break; } break; case 5: switch(note){ case 'C': (!s)?freq=261.63:freq=277.18; break; case 'D': (!s)?freq=293.66:freq=311.13; break; case 'E': (!s)?freq=329.63:freq=329.63; break; case 'F': (!s)?freq=349.23:freq=369.99; break; case 'G': (!s)?freq=391.00:freq=415.30; break; case 'A': (!s)?freq=440.00:freq=466.16; break; case 'B': (!s)?freq=493.88:freq=493.88; break; } break; } Beep(freq,dur); } void piano(char n){ switch(n){ case 'a': p('E',false,200,4); break; case 's': p('F',false,200,4); break; case 'd': p('G',false,200,4); break; case 'f': p('A',false,200,4); break; case 'g': p('B',false,200,4); break; case 'h': p('C',false,200,5); break; case 'j': p('D',false,200,5); break; case 'k': p('E',false,200,5); break; case 'l': p('F',false,200,5); break; case 'ñ': p('G',false,200,5); break; case '´': p('A',false,200,5); break; case 'ç': p('B',false,200,5); break; // Mayor case 'q': p('D',true,200,4); break; case 'w': p('E',true,200,4); break; case 'e': p('F',true,200,4); break; case 'r': p('G',true,200,4); break; case 't': p('A',true,200,4); break; case 'y': p('B',true,200,5); break; case 'u': p('C',true,200,5); break; case 'i': p('D',true,200,5); break; case 'o': p('E',true,200,5); break; case 'p': p('F',true,200,5); break; case '`': p('G',true,200,5); break; case '+': p('A',true,200,5); break; } } int main(){ char m; while(m!='1'){ if(kbhit()){ m=getch(); piano(m); } } return 0; }
This will only work in computers with an internal speaker installed, yours probably has one if it "beeps" when it turns on. Although it may have it even if that doesn't happen, it doesn't work on Windows Vista x64 and Windows XP 64-Bit Edition though
Best regards,
Alex
Understanding C++ time complexity
0What functions are faster? Which ones are the most efficient? Understanding this will help you optimise your code and impove it's performance.
Each C++ function has a run time, and knowing that will allow you to combine the best methods always.
Here you have the different possible run times, explained and with an example of a function. (Note that they are ordered from fastest to slowest)
Constant time:
This is the fastest a function can work. An example is to measure an array's length:
// Using namespace std; int a[32]; cout << a.size();
What this means is that no matter how large a is, it will always take the same amount of time to perform this operation.
Logarithmic time:
This is also in the fast group of times, there is a formula to get how much time it will actually take (That involves the logarithm of the size of the input)
An example of this would be a function that looks for a key in an array, returning it's index if found:
int binarySearch(int sortedArray[], int first, int last, int key) {
// function:
// Searches sortedArray[first]..sortedArray[last] for key.
// returns: index of the matching element if it finds key,
// otherwise -(index where it could be inserted)-1.
// parameters:
// sortedArray in array of sorted (ascending) values.
// first, last in lower and upper subscript bounds
// key in value to search for.
// returns:
// index of key, or -insertion_position -1 if key is not
// in the array. This value can easily be
// transformed into the position to insert it.
while (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (key > sortedArray[mid])
first = mid + 1; // repeat search in top half.
else if (key < sortedArray[mid])
last = mid - 1; // repeat search in bottom half.
else
return mid; // found it. return position /////
}
return -(first + 1); // failed to find key
}
Source: Fredosaurus.com
Linear time:
A bit slower than logarithmic time, but still fast. Functions that run in this type of time take a time proportional to the size of the input.
An example of this would be to iterate through an array:
int a[40];
// Fill a with data...
for(int i=0;i<40;i++){
std::cout << a[i];
}
Linearithmic time:
Well this one is a bit tricky, it's still fast, and it's run time depends on the size of the input but both linearly and logarithmically. All logarithmic functions that sort work this way, they are also linear because they depend on the size of the array to sort:
There are a lot of different ways of implementing the algorithm quicksort, here you have one sample demonstration of how it works.
Polynomial time:
This one is the slowest time inside the fast run times. It is the one that take up comparison sorts (Functions like insert, sort, select... )
Here you have a sample implementation of the function sort for arrays:
int array[] = { 23, 5, -10, 0, 0, 321, 1, 2, 99, 30 };
int elements = sizeof(array) / sizeof(array[0]);
std::sort(array, array + elements);
for (int i=0; i<elements; ++i)
std::cout << array[i] << ' ';
Exponential time:
Algorithms and functions that run in this type of time are considered slow. This are algorithms of the type brute force, that is, algorithms that try all possibilities, like a solver for a Rubik Cube.
Factorial time:
This is the slowest of all, it corresponds to complex brute force algorithms, like an algorithm to solve the Travelling Salesman Problem by brute force.
I will probably add a bit more to this examples over time, but well to get a grasp of what these times mean I think this will be more than enough,
Alex
C++ Quick guide: STL Vector
0In C++ we have what's called the Standard Template Library (STL) which provides a lot of useful shortcut functions that will help us develop our code.
Today I wanted to show you the basics of the vector library. How arrays will go from being a nightmare to the easiest thing ever in our C++ applications. If you have ever programmed anything in PHP, you'll realize that with the vector template, arrays become something quite similar as those in PHP.
Usage:
First, include the vector file using a normal include:
#include <vector>
We now have access to all of its functions. Let's see them in a sort of logical order.
Constructors:
We will use these to create our arrays, the way they work is very simple, we will use the keyword vector, followed by the type of data it will hold placed between < and >, for example vector<int> and then the name of our array.
// Creates a new vector a vector<int> a; // Creates a new vector b, copy of a vector<int> b(a); // Creates a new vector c, with 4 elements vector<int> c(4); // Creates a new vector d, with 3 elements, each with a value of 10 vector<int> d(3,10);
Now that we have the vectors initialized, let's learn how to do stuff with them:
Basic operations:
Using our newly created vectors is very easy:
// I'll be using our previously created vectors // Check this out, a hadn't any space assigned, but C++ extends it so that I can do this! : a[0] = 4; b = a; // Now c[1] is 4! : c[1] = b[0]; // c[0] is now 8: c[0] = c[1]+b[0];
Well as you have seen it's very easy to operate with them, let's now move on to some more advanced stuff:
Adding elements to our vector:
Before getting into vector functions I want to explain the use of iterators. An iterator is a pointer to an element in an array. We use them to walk through the array, element by element. This is how we set an iterator up:
vector<int>::iterator ite
There are a number of functions for this task, let's see some of them:
insert()
The function insert adds elements to a vector. There are several ways of doing so, I will show you each commented below:
// Let's set iter to after the last element iter = v.end(); // Now insert a 5 at that position iter = v.insert(iter, 5); // We can also insert multiple elements: iter = v.insert(iter, 5, 3); // This inserts 5 integers of value 3 at iter position
push_back()
This is more common than insert, it adds an element at the end of our vector:
v.push_back(6); // This adds a 6 at the end of v, expanding it if necessary
assign()
assign replaces elements in a vector, returning their position:
iter = v.assign(4, 10); // This will replace all elements in v with 4 copies of the integer 10
Removing elements from our vector:
Remember that for all my examples I am using the previously created vector v and the iterator iter. Let's take a look now at some functions for removing elements from our vectors:
erase()
Probably the most used function for this task, it usually takes one argument, an iterator pointing to the element we want to remove. We can also pass directly the number of that element:
v.erase(2); // Removes element at position 2 iter = v.erase(iter); // Removes element at position iter and then returns the next positio
erase() can also be used with two iterators instead of one, to remove elements in that range, for example:
v.erase(0,3); // To remove elements from 0 to 3
The same could be done with two iterators pointing to different elements.
pop_back()
This function removes the last element of a vector.
v.pop_back();
clear()
Be careful with this function! As you can guess, it removes all elements from a vector,
v.clear();
A bit more information on iterators:
We also have some functions to work on iterators. I will keep on using the previously declared iterator iter for these examples, let's take a look at the basics:
iter = v.begin(); // Sets iter to first element iter = v.end(); // Sets it to the last element iter = v.rbegin(); //Sets it to the first element in reverse order (Same with rend() ) // After iter is set to the start or end, both in normal and reverse order, we can use...: iter++; iter--; // ...to increase or decrease the iterator // To get the value of the element the iterator is pointing to we can simply access the pointed memory spot: int value = *iter;
And this is the basics of the Vector STL, hope you enjoyed it
Display character from ASCII value in C++
0I don't know whether this is useful or merely entertaining, but it is quite simple to display the character representation of any ASCII number in C++
We will use the static_cast function to perform this operation, converting from int to char.
Let me show you this sample program that does just that (Looping until you enter 0)
#include <iostream> using namespace std; int main(){ int r; cout < < "Enter a number to see its character: \n" << "Number: "; cin >> r; while(r!=0){ cout < < "\nCharacter: " << static_cast<char>(r); cin.get(); cout < < "\nNumber: "; cin >> r; } return 0; }</iostream>
As you can see we simply ask for a number, and while that number is not 0 we keep on asking for more, as well as displaying its character representation by using the static_cast function.
Hope you enjoyed this
Alex
Overloading input/output operators C++
1As you might know, when we develop a simple program that runs in the system console, using the standard library iostream, we might want to have special ways of displaying a class object.
You have probably heard of the istream and ostream operators (<< and >>), we can use overloading to change their behaviour.
Since they are not functions from our class, we must use a special keyword, friend. A friend function is neither public or private, our class doesn't control it's scope. They are classes that don't belong to a class, but have access to its private members.
Let's create a simple class to demonstrate this:
class simple{ int a,b; public: friend ostream & operator < <(ostream & o, simple & s){ o << s.a << " " << s.b; return o; } friend istream & operator >>(istream & i, simple & s){ i >> s.a >> s.b; return i; } };
This class has two private members, a and b. I haven't created any constructors as we don't really need them for the example. We will change the values of a and b using the input operator >> and we will display them using the output operator <<
How the istream and ostream operators work is quite simple actually. Declaring them friend gives them direct access to private members a and b. But since they don't belong to the class we must pass them a reference to the object from the class simple we want to modify: simple & s. The other parameter is the reference to the i/o stream itself, all our modifications will be "stored" in that reference and then returned.
Let me show you a basic main to show it in use:
main(){ simple obj; cin >> obj; cout < < "\nDisplay my simple object: "; cout << obj << endl; system("pause"); return 0; }
In this sample main we instantiate simple in the object obj, and we then call the input operator >> to give a and b some values.
After that we display the values using the output operator <<.
This simple program generates the following output (Imagine I enter 2 and 3 as input):
2 3 Display my simple object: 2 3
If you want the full working code:
#include <iostream> using namespace std; class simple{ int a,b; public: friend ostream & operator < <(ostream & o, simple & s){ o << s.a << " " << s.b; return o; } friend istream & operator >>(istream & i, simple & s){ i >> s.a >> s.b; return i; } }; main(){ simple obj; cin >> obj; cout < < "\nDisplay my simple object: "; cout << obj << endl; system("pause"); return 0; }
Well I hope you enjoyed this and understood it correctly
If you have any problems or suggestions feel free to comment below,
Alex