Using a bitset library - c++

I am doing my first steps with C++ and with some help I have created a code to make an easy function. But I have a problem. I am using a bitset function that needs a specific library and I don't know who to introduce this library in my code.
I have been reading some information in the net but I don't achieve to do it, so I wonder if any of you can tell me in a detailed way how to do it.
So that you make an idea I have been looking in http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html, http://www.boost.org/doc/libs/1_46_0/libs/dynamic_bitset/dynamic_bitset.html#cons2 and simmilar places.
I attached my code so that you make and idea what I am doing.
Thanks in advance :)
// Program that converts a number from decimal to binary and show the positions where the bit of the number in binary contains 1
#include<iostream>
#include <boost/dynamic_bitset.hpp>
int main() {
unsigned long long dec;
std::cout << "Write a number in decimal: ";
std::cin >> dec;
boost::dynamic_bitset<> bs(64, dec);
std::cout << bs << std::endl;
for(size_t i = 0; i < 64; i++){
if(bs[i])
std::cout << "Position " << i << " is 1" << std::endl;
}
//system("pause");
return 0;
}

If you don't want your bitset to dynamically grow, you can just use the bitset that comes built-in with all standards compliant C++ implementations:
#include <iostream>
#include <bitset>
int main() {
unsigned long long dec;
std::cout << "Write a number in decimal: ";
std::cin >> dec;
const size_t number_of_bits = sizeof(dec) * 8;
std::bitset<number_of_bits> bs(dec);
std::cout << bs << std::endl;
for (size_t i = 0; i < number_of_bits; i++) {
if (bs[i])
std::cout << "Position " << i << " is 1" << std::endl;
}
return 0;
}
To use the dynamic_bitset class, you have to download the Boost libraries and add the boost folder to your compiler's include directories. If you are using the GNU C++ compiler you should something like:
g++ -I path/to/boost_1_46_1 mycode.cpp -o mycode

Related

How can I turn my program into a .dll file and run it in cmd using rundll32.exe?

I have a program that creates multiple threads and prints some strings in a loop. My task is to turn this program into a .dll and run it using rundll32.exe, but I've got no idea how can I run a .dll as an executable file.
#define _CRT_SECURE_NO_WARNINGS
#include<windows.h>
#include <stdlib.h>
#include<process.h>
#include<stdio.h>
#include<string>
#include<ctime>
#include<vector>
#include<iostream>
typedef struct {
std::string info;
unsigned int m_number;
int m_stop_thread;
int m_priority_thread;
unsigned m_cycles;
unsigned m_currentThread;
}data;
HANDLE tmp;
unsigned int __stdcall Func(void* d) {
data* real = (data*)d;
std::cout << "\nCurrent thread ID: " << GetCurrentThreadId() << std::endl;
if (real->m_currentThread == real->m_priority_thread)
SetThreadPriority(tmp, 2);
std::cout << "Thread priority: " << GetThreadPriority(tmp) << std::endl;
for (int j = (real->m_currentThread - 1) * real->m_cycles / real->m_number;j < real->m_currentThread * real->m_cycles / real->m_number;j++) {
for (int i = 0;i < real->info.size();++i)
std::cout << real->info[i];
std::cout << std::endl;
}
return 0;
}
int main(int argc, char* argv[]) {
int threadsNumber, priority, stop;
std::string str;
std::cout << "Enter the info about a student:\n";
std::getline(std::cin, str);
std::cout << "Enter the number of threads:\n";
std::cin >> threadsNumber;
int cycles;
std::cout << "Enter the number of cycles:\n";
std::cin >> cycles;
std::cout << "Which thread priority do you want to change? ";
std::cin >> priority;
std::cout << "Which thread do you want to stop? ";
std::cin >> stop;
std::vector<HANDLE> threads;
data* args = new data;
args->info = str;
args->m_number = threadsNumber;
args->m_cycles = cycles;
args->m_priority_thread = priority;
args->m_stop_thread = stop;
clock_t time = clock();
for (int i = 1;i <= threadsNumber;++i) {
args->m_currentThread = i;
tmp = (HANDLE)_beginthreadex(0, 0, &Func, args, 0, 0);
threads.push_back(tmp);
}
WaitForMultipleObjects(threads.size(), &threads.front(), TRUE, INFINITE);
time = clock() - time;
std::cout << "time: " << (double)time / CLOCKS_PER_SEC << "s" << std::endl << std::endl;
getchar();
return 0;
}
Does anyone know how can I put this code into a dll and run it using command line?
When you compile your program you make something called Portable Executable [PE] in Windows. Among files that share that family are .exe,.dll, .scr and you can recognize them by opening them in text editor (such as notepad) and looking if file starts with MZ which are signature for Mark Zbikowski.
In short there isn't much difference in *.dll or *.exe except some minor blocks depedning on version. So in short you are making an "dll" when you compile it. But if you wish to compile your program as dll exactly, that depends on your compiler:
If you are working in Visual Studio, Microsoft has some tutorials for that
For MinGW you have in code tutorial
And for CygWin you have command line arguments for compiler
And for Clang I would suggest this question
But I would be careful with deployment of such file, since #Richard nicely pointed it out that RunDll32 is deprecated, but it is still used in gears of some programming language libraries. So if you are building something for self testing purposes I would recommend those 4 options depending on your compiler.

My double is rounding up the decimals and I don't want it to

I converted a string to a double using ::atof, it converts OK but it rounds up the decimal and I don't want it to.
string n;
double p;
cout << "String? :" << endl;
cin >> n
p = ::atof(n.c_str());
cout << p << endl;
I usually type in numbers like 123,456.78, 12,345.87, 123,456,789.12. When I type in a smaller number like 1,234.83 or bigger the programs starts messing with the decimals.
It would be of huge help if anybody helps. Thanks!
You need to set the precision used when sending data to the output stream using setprecision as shown below.
Of course the problem with this code is that atof() isn't your best option. However, to answer your question the use of atof() doesn't matter.
#include <iomanip>
#include <iostream>
#include <string>
int main()
{
double x;
std::string n;
std::cout << "String? :" << std::endl;
std::cin >> n;
x = ::atof(n.c_str());
std::cout << std::setprecision(10) << x << std::endl;
}
To convert and catch conversion errors you could use the following:
try
{
x = std::stod(n);
}
catch(std::invalid_argument)
{
// can't convert
}

Mean and Mode of vector array - How can I make a smaller improvement in the function

Doing an exercise to find the mean and mode of a list of numbers input by a user. I have written the program and it works, but I'm wondering if my function 'calcMode' is too large for this program. I've just started looking into functions which is a first attempt. Would it be better to write smaller functions? and if so what parts can I split? Im pretty new to C++ and also looking if I can improve this code. Is there any changes I can make to make this run more efficient?
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int calcMean(vector<int> numberList)
{
int originNumber = numberList[0];
int nextNumber;
int count = 0;
int highestCount = 0;
int mean = 0;
for (unsigned int i = 0; i <= numberList.size() - 1; i++)
{
nextNumber = numberList[i];
if (nextNumber == originNumber)
count++;
else
{
cout << "The Number " << originNumber << " appears " << count << " times." << endl;
count = 1;
originNumber = nextNumber;
}
}
if (count > highestCount)
{
highestCount = count;
mean = originNumber;
}
cout << "The Number " << originNumber << " appears " << count << " times." << endl;
return mean;
}
int main()
{
vector<int> v;
int userNumber;
cout << "Please type a list of numbers so we can arrange them and find the mean: "<<endl;
while (cin >> userNumber) v.push_back(userNumber);
sort(v.begin(), v.end());
for (int x : v) cout << x << " | ";
cout << endl;
cout<<calcMean(v)<<" is the mean"<<endl;
return 0;
}
One thing to watch out for is copying vectors when you don't need to.
The function signature
int calcMode(vector<int> numberList)
means the numberList will get copied.
int calcMode(const & vector<int> numberList)
will avoid the copy. Scott Meyer's Effective C++ talks about this.
As an aside, calling is a numberList is misleading - it isn't a list.
There are a couple of points that are worth being aware of in the for loop:
for (unsigned int i = 0; i <= numberList.size()-1; i++)
First, this might calculate the size() every time. An optimiser might get rid of this for you, but some people will write
for (unsigned int i = 0, size=numberList.size(); i <= size-1; i++)
The size is found once this way, instead of potentially each time.
They might even change the i++ to ++i. There used to a potential overhead here, since the post-increment might involve an extra temporary value
One question - are you *sure this gives the right answer?
The comparison nextNumber == originNumber is looking at the first number to begin with.
Try it with 1, 2, 2.
One final point. If this is general purpose, what happens if the list is empty?
Would it be better to write smaller functions?
Yes, you can make do the same job using std::map<>; which could be
a much appropriate way to count the repetition of the array elements.
Secondly, it would be much safer to know, what is the size of the
array. Therefore I suggest the following:
std::cout << "Enter the size of the array: " << std::endl;
std::cin >> arraySize;
In the calcMode(), you can easily const reference, so that array
will not be copied to the function.
Here is the updated code with above mentioned manner which you can refer:
#include <iostream>
#include <algorithm>
#include <map>
int calcMode(const std::map<int,int>& Map)
{
int currentRepetition = 0;
int mode = 0;
for(const auto& number: Map)
{
std::cout << "The Number " << number.first << " appears " << number.second << " times." << std::endl;
if(currentRepetition < number.second )
{
mode = number.first; // the number
currentRepetition = number.second; // the repetition of the that number
}
}
return mode;
}
int main()
{
int arraySize;
int userNumber;
std::map<int,int> Map;
std::cout << "Enter the size of the array: " << std::endl;
std::cin >> arraySize;
std::cout << "Please type a list of numbers so we can arrange them and find the mean: " << std::endl;
while (arraySize--)
{
std::cin >> userNumber;
Map[userNumber]++;
}
std::cout << calcMode(Map)<<" is the mode" << std::endl;
return 0;
}
Update: After posting this answer, I have found that you have edited your function with mean instead of mode. I really didn't get it.
Regarding mean & mode: I recommend you to read more. Because in general, a data set can have multiple modes and only one mean.
I personally wouldn't split this code up in smaller blocks, only if i'd want to reuse some code in other methods. But just for this method it's more readable like this.
The order of excecution is aroun O(n) for calc which is quite oke if you ask me

Return Pointers With Multiple Value Win32 Linking Error

I have encountered the typical No Entry Point Personality V0 error before and worked around it with: -fno-exceptions. Although this time when I use the workaround cmd crashed and only runs the first cin >> line of the program.
However, I can run the program no problem in MSYS.
I compiled with:
g++ ReturnPointer.cpp -o ReturnPointer.exe (gave error)
g++ ReturnPointer.cpp -o ReturnPointer.exe -fno-exceptions (runs: MSYS Shell Only)
#include <iostream>
short factor(int, int*, int*);
int main()
{
int number, squared, cubed;
short error;
std::cout << "Enter a number (0 - 20 ): ";
std::cin >> number;
error = factor(number, &squared, &cubed);
if (!error)
{
std::cout << "number: " << number << "\n";
std::cout << "square: " << squared << "\n";
std::cout << "cubed: " << cubed << "\n";
}
else
std::cout << "Error encountered!!\n";
return 0;
}
short factor(int n, int* pSquared, int* pCubed)
{
short value = 0;
if (n > 20)
{
value = 1;
}
else
{
*pSquared = n * n;
*pCubed = n * n * n;
value = 0;
}
return value;
}
Granted, this isn't the end of the world. I am just expanding my knowledge on an area of C++ that trips me up a lot. Although, if I were to ever use pointers in this manner in a larger program...that would turn into a mess.
I would just like to know what needs to be done or what I am missing to run this in CMD.

How do you append an int to a string in C++? [duplicate]

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 6 years ago.
int i = 4;
string text = "Player ";
cout << (text + i);
I'd like it to print Player 4.
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?
With C++11, you can write:
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
Well, if you use cout you can just write the integer directly to it, as in
std::cout << text << i;
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
Alternatively, you can just convert the integer and append it to the string.
oss << i;
text += oss.str();
Finally, the Boost libraries provide boost::lexical_cast, which wraps around the stringstream conversion with a syntax like the built-in type casts.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
This also works the other way around, i.e. to parse strings.
printf("Player %d", i);
(Downvote my answer all you like; I still hate the C++ I/O operators.)
:-P
These work for general strings (in case you do not want to output to file/console, but store for later use or something).
boost.lexical_cast
MyStr += boost::lexical_cast<std::string>(MyInt);
String streams
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
For the record, you can also use a std::stringstream if you want to create the string before it's actually output.
cout << text << " " << i << endl;
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
string text = "Player: ";
int i = 4;
cout << text << i << endl;
would work fine.
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
In fact, you can use templates to make this approach more powerful:
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
Now, as long as object b has a defined stream output, you can append it to your string (or, at least, a copy thereof).
Another possibility is Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
Here a small working conversion/appending example, with some code I needed before.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
the output will be:
/dev/video
/dev/video456
/dev/video321
/dev/video123
Note that in the last two lines you save the modified string before it's actually printed out, and you could use it later if needed.
For the record, you could also use Qt's QString class:
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
cout << text << i;
One method here is directly printing the output if its required in your problem.
cout << text << i;
Else, one of the safest method is to use
sprintf(count, "%d", i);
And then copy it to your "text" string .
for(k = 0; *(count + k); k++)
{
text += count[k];
}
Thus, you have your required output string
For more info on sprintf, follow:
http://www.cplusplus.com/reference/cstdio/sprintf
cout << text << i;
The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as:
cout << text;
cout << i;
cout << "Player" << i ;
cout << text << " " << i << endl;
The easiest way I could figure this out is the following..
It will work as a single string and string array.
I am considering a string array, as it is complicated (little bit same will be followed with string).
I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps.
length is just to measure the size of array. If you are familiar with programming then size_t is a unsigned int
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}
There are a few options, and which one you want depends on the context.
The simplest way is
std::cout << text << i;
or if you want this on a single line
std::cout << text << i << endl;
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
Player 1
Player 2
If you are unlucky you might get something like the following
Player Player 2
1
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
std::cout << text;
std::cout << i;
std::cout << endl;
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
printf("Player %d\n", i);
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
You also try concatenate player's number with std::string::push_back :
Example with your code:
int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;
You will see in console:
Player 4
You can use the following
int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);
If using Windows/MFC, and need the string for more than immediate output try:
int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);