my name is Adam, I have just begun to learn C++, I love it, but am only on pg 181 in the seventh edition of sams teach yourself C++ in one hour a day, and pg 102 in the seventh edition of C++ for dummies. I have seven multi page notes on the sams book, and twenty one multi page notes on the for dummies book. Please help me understand why I get 5 errors with my simple program which will be shown shortly. I do not want to use -fpermissive option, I need to learn how to code correctly as I am not very experienced. Thank you everyone, very very much, I absolutely love C++, and even have a very good idea on a simple program I plan to learn how to write, which could allow program development time, or writing time to be reduced by 5-20 times on average. The following program shown is not this program however, but please help me so I may one day write, and use my program idea for a college paper. Thank you again, problem program follows:
#include <iostream>
using namespace std;
int main()
{
cout<< "how many integers do you wish to enter? ";
int InputNums = 0;
cin>> InputNums;
int* pNumbers = new int [InputNums];
int* pCopy = pNumbers;
cout<< "successfully allocated memory for "<<
InputNums<< " integers"<<endl;
for(int Index = 0; Index < InputNums; ++Index)
{
cout<< "enter number "<< Index << ": ";
cin>> *(pNumbers + Index);
}
cout<< "displaying all numbers input: " <<endl;
for(int Index = 0, int* pCopy = pNumbers;
Index < InputNums; ++Index)
cout<< *(pCopy++) << " ";
cout<< endl;
delete[] pNumbers;
cout<< "press enter to continue..." << endl;
cin.ignore(10, '\n');
cin.get();
return 0;
}
The problem is indicated as being in the multiple initializations of the second for loop. Please tell me why my problem program will not compile. Thank you all. Sincerely Adam.
My first advice would be to find a better book.
Once you've done that, forget everything you think you know about using new to allocate an array (e.g., int* pNumbers = new int [InputNums];). It's an obsolete construct that you shouldn't use (ever).
If I had to write a program doing what you've outlined above, the core of it would look something like this:
cout<< "how many integers do you wish to enter? ";
int InputNums;
cin>> InputNums;
std::vector<int> numbers;
int temp;
for (int i=0; i<InputNums; i++) {
cin >> temp;
numbers.push_back(temp);
}
cout<< "displaying all numbers input:\n";
for (auto i : numbers)
cout << i << " ";
Directly answer your question: you cannot initialize variables of different types in the same for loop declaration.
In your example:
for(int Index = 0, int* pCopy = pNumbers;
int and int * are different types. Even if you use auto to let the compiler automatically deduct the types, both variables cannot have different deducted types.
The solution:
int Index = 0;
for(int *pCopy=pNumbers; ...
Having this one single secondary effect: Index is now not only confined to the scope of the for. Should this be a problem, you may do:
{
int Index = 0;
for(int *pCopy=pNumbers; ...
...
}
And now the scope of Index is limited to the surrounding curly braces.
Related
I need to set the last element inside an array by multiply the last "i" with it self like this. but when i try to do i*i, i is undefined. also, when i try to print the result, cout is undefined.
void firstArray(void)
{
int MyArray[10] ;
for (unsigned int i=0; i<10; ++i)
{
MyArray[i] = i;
}
MyArray [9] = i*i;
for (unsigned int i=0; i<10; ++i)
{
cout(MyArray[i]);
}
}
I tried to put MyArray [9] = i*i inside the loop; with a condition( and it whould work), but i cant use any if for this assignment.
also, I tried to put with System.out like in java before cout, but System is undefined.
what do i need to change to make it work?
Ok, so first of all, if you want "i" outside of your loop, you need to initialize "i" outside of your loop too.
... Unsigned int i; for(i =0; i<10; i++) ...
Now, "i" will be equal the last increment outside your loop.
Also, i suggest you to read the basics for c++, System dont exist in c++, instead its with std namespace.
There is two way to do that:
Using namespace std;
Inside the function, or by write "std::" before cout and:
Std::cout << MyArray[i]
Pay attention how i wrote it, you will find
How to do in the c++ website:
https://www.cplusplus.com/reference/iostream/cout/
I have two message:
messageA: "Frank is one of the "best" students topicId{} "
messageB: "Frank is one of the "top" students topicId{} "
I need to find SHA256 partially collision of these two messages(8 digits).
Therefore, The first 8 digests of SHA256(messageA) == The first 8 digest of SHA256(messageB)
We can put any letters and numbers in {}, Both {} should have same string
I have tried brute force and birthday attack with hash table to solve this problem, but it costs too much time. I know the cycle detection algorithm like Floyd and Brent, however i have no idea how to construct the cycle for this problem. Are there any other methods to solve this problem? Thank you so much!
This is pretty trivial to solve with a birthday attack. Here's how I did it in Python (v2):
def find_collision(ntries):
from hashlib import sha256
str1 = 'Frank is one of the "best" students topicId{%d} '
str2 = 'Frank is one of the "top" students topicId{%d} '
seen = {}
for n in xrange(ntries):
h = sha256(str1 % n).digest()[:4].encode('hex')
seen[h] = n
for n in xrange(ntries):
h = sha256(str2 % n).digest()[:4].encode('hex')
if h in seen:
print str1 % seen[h]
print str2 % n
find_collision(100000)
If your attempt took too long to find a solution, then either you simply made a mistake in your coding somewhere, or you were using the wrong data type.
Python's dictionary data type is implemented using hash tables. That means you can search for dictionary elements in constant time. If you implemented seen using a list instead of a dict in the above code, then the search at line 11 would take an awful lot longer.
Edit:
If the two topicId tokens have to be identical, then — as pointed out in the comments — there is little option but to grind through somewhere in the order of 231 values. You will find a collision eventually, but it could take a long time.
Just leave this running overnight and with a bit of luck you'll have an answer in the morning:
def find_collision():
from hashlib import sha256
str1 = 'Frank is one of the "best" students topicId{%x} '
str2 = 'Frank is one of the "top" students topicId{%x} '
seen = {}
n = 0
while True:
if sha256(str1 % n).digest()[:4] == sha256(str2 % n).digest()[:4]:
print str1 % n
print str2 % n
break
n += 1
find_collision()
If you're in a hurry, you could maybe look into using a GPU to speed up the hash calculations.
I'm assuming the space at the end of the strings in the question was intentional so I left it in.
"Frank is one of the "top" students topicId{59220691223} "
6026d9b323898bcd7ecdbcbcd575b0a1d9dc22fd9e60074aefcbaade494a50ae
"Frank is one of the "best" students topicId{59220691223} "
6026d9b31ba780bb9973e7cfc8c9f74a35b54448d441a61cc9bf8db0fcae5280
It actually took about 7 billion tries to find one using brute force, a lot more than I expected.
I figure 2^32 is roughly 4.3 billion and so chance of not finding any match after 4.3 billion tries is about 36.78%
I actually found a match after about 7 billion tries, there was less than a 20% chance of no matches in 7 billion tries.
This is the C++ code I used running on 7 threads, each thread gets a different starting point and it quits once a match is found on any thread. Each thread also updates its progress to cout every 1 million attempts.
I've fast forwarded to where the match was found on threadId=5, so it takes less than a minute to run. But if you change the starting point you can look for other matches.
And I'm not sure either how one would use Floyd and Brent since the strings have to use the same topicId so you are locked in on both the prefix and suffix.
/*
To compile go get picosha2 header file from https://github.com/okdshin/PicoSHA2
Copy this code into same directory as picosha2.h file, save it as hash.cpp for example.
On Linux go to command line and cd to directory where these files are.
To compile it:
g++ -O2 -o hash hash.cpp -l pthread
And run it:
./hash
*/
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
// I used picoSHA2 header only file for the hashing
// https://github.com/okdshin/PicoSHA2
#include "picosha2.h"
// return 1st 4 bytes (8 chars) of SHA256 hash
std::string hash8(const std::string& src_str) {
std::vector<unsigned char> hash(picosha2::k_digest_size);
picosha2::hash256(src_str.begin(), src_str.end(), hash.begin(), hash.end());
return picosha2::bytes_to_hex_string(hash.begin(), hash.begin() + 4);
}
bool done = false;
std::mutex mtxCout;
void work(unsigned long long threadId) {
std::string a = "Frank is one of the \"best\" students topicId{",
b = "Frank is one of the \"top\" students topicId{";
// Each thread gets a different starting point, I've fast forwarded to the part
// where I found the match so this won't take long to run if you try it, < 1 minute.
// If you want to run a while drop the last "+ 150000000ULL" term and it will run
// for about 1 billion total (150 million each thread, assuming 7 threads) take
// about 30 minutes on Linux.
// Collision occurred on threadId = 5, so if you change it to use less than 6 threads
// then your mileage may vary.
unsigned long long start = threadId * (11666666667ULL + 147000000ULL) + 150000000ULL;
unsigned long long x = start;
for (;;) {
// Not concerned with making the reading/updating "done" flag atomic, unlikely
// 2 collisions are found at once on separate threads, and writing to cout
// is guarded anyway.
if (done) return;
std::string xs = std::to_string(x++);
std::string hashA = hash8(a + xs + "} "), hashB = hash8(b + xs + "} ");
if (hashA == hashB) {
std::lock_guard<std::mutex> lock(mtxCout);
std::cout << "*** SOLVED ***" << std::endl;
std::cout << (x-1) << std::endl;
std::cout << "\"" << a << (x - 1) << "} \" = " << hashA << std::endl;
std::cout << "\"" << b << (x - 1) << "} \" = " << hashB << std::endl;
done = true;
return;
}
if (((x - start) % 1000000ULL) == 0) {
std::lock_guard<std::mutex> lock(mtxCout);
std::cout << "thread: " << threadId << " = " << (x-start)
<< " tries so far" << std::endl;
}
}
}
void runBruteForce() {
const int NUM_THREADS = 7;
std::thread threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) threads[i] = std::thread(work, i);
for (int i = 0; i < NUM_THREADS; i++) threads[i].join();
}
int main(int argc, char** argv) {
runBruteForce();
return 0;
}
So, I am new to C++. I've researched Segmentation Fault (core dumped), memory allocation, and new/delete although I am having trouble understanding the concepts. I do believe my problem lies with memory allocation though and that's why I thought "delete" would have solved my problem. May someone please push me in the right direction?
Input
#include <iostream>
#include <string>
using namespace std;
struct CandyBar
{
string name;
double weight;
int calories;
} ;
int main()
{
CandyBar* backpack = new CandyBar[3];
backpack[0] = {"Choco Chalk", 5.1, 725};
backpack[1] = {"Twisty String", 1.8, 300};
backpack[2] = {"Gummy Nums", 4.4, 475};
cout << "Name\t\tWeight\tCalories" << endl << endl;
for (int x = 0; x < 4; x++)
{
cout << backpack[x].name << "\t" << backpack[x].weight << "\t" << backpack[x].calories << endl;
}
delete backpack;
return 0;
}
Output
Name Weight Calories
Choco Chalk 5.1 725
Twisty String 1.8 300
Gummy Nums 4.4 475
(Segmentation fault) core dumped
I see two bugs:
Your loop for (x = 0; x < 4; x++) will iterate through x values 0, 1, 2, 3. However, since you allocated backpack with new Candybar[3], backpack points to only enough memory to hold 3 CandyBars, namely backpack[0], backpack[1], backpack[2]. As it stands, on its fourth time through, your loop will attempt to access backpack[3], which is off the end of the array.
When you allocate memory with new[] (as you did since you allocated an array of CandyBar), you have to deallocate it with delete[], not just plain delete. See delete vs delete[] operators in C++.
When I changed your loop exit condition to x < 3 and your deallocation to delete[] backpack;, the program worked for me.
I want to generate pseudo-random numbers in C++, and the two likely options are the feature of C++11 and the Boost counterpart. They are used in essentially the same way, but the native one in my tests is roughly 4 times slower.
Is that due to design choices in the library, or am I missing some way of disabling debug code somewhere?
Update: Code is here, https://github.com/vbeffara/Simulations/blob/master/tests/test_prng.cpp and looks like this:
cerr << "boost::bernoulli_distribution ... \ttime = ";
s=0; t=time();
boost::bernoulli_distribution<> dist(.5);
boost::mt19937 boostengine;
for (int i=0; i<n; ++i) s += dist(boostengine);
cerr << time()-t << ", \tsum = " << s << endl;
cerr << "C++11 style ... \ttime = ";
s=0; t=time();
std::bernoulli_distribution dist2(.5);
std::mt19937_64 engine;
for (int i=0; i<n; ++i) s += dist2(engine);
cerr << time()-t << ", \tsum = " << s << endl;
(Using std::mt19937 instead of std::mt19937_64 makes it even slower on my system.)
That’s pretty scary.
Let’s have a look:
boost::bernoulli_distribution<>
if(_p == RealType(0))
return false;
else
return RealType(eng()-(eng.min)()) <= _p * RealType((eng.max)()-(eng.min)());
std::bernoulli_distribution
__detail::_Adaptor<_UniformRandomNumberGenerator, double> __aurng(__urng);
if ((__aurng() - __aurng.min()) < __p.p() * (__aurng.max() - __aurng.min()))
return true;
return false;
Both versions invoke the engine and check if the output lies in a portion of the range of values proportional to the given probability.
The big difference is, that the gcc version calls the functions of a helper class _Adaptor.
This class’ min and max functions return 0 and 1 respectively and operator() then calls std::generate_canonical with the given URNG to obtain a value between 0 and 1.
std::generate_canonical is a 20 line function with a loop – which will never iteratate more than once in this case, but it adds complexity.
Apart from that, boost uses the param_type only in the constructor of the distribution, but then saves _p as a double member, whereas gcc has a param_type member and has to “get” the value of it.
This all comes together and the compiler fails in optimizing.
Clang chokes even more on it.
If you hammer hard enough you can even get std::mt19937 and boost::mt19937 en par for gcc.
It would be nice to test libc++ too, maybe i’ll add that later.
tested versions: boost 1.55.0, libstdc++ headers of gcc 4.8.2
line numbers on request^^
I have written the following simple C++ code.
#include <iostream>
#include <omp.h>
int main()
{
int myNumber = 0;
int numOfHits = 0;
cout << "Enter my Number Value" << endl;
cin >> myNumber;
#pragma omp parallel for reduction(+:numOfHits)
for(int i = 0; i <= 100000; ++i)
{
for(int j = 0; j <= 100000; ++j)
{
for(int k = 0; k <= 100000; ++k)
{
if(i + j + k == myNumber)
numOfHits++;
}
}
}
cout << "Number of Hits" << numOfHits << endl;
return 0;
}
As you can see I use OpenMP to parallelize the outermost loop. What I would like to do is to rewrite this small code in CUDA. Any help will be much appreciated.
Well, I can give you a quick tutorial, but I won't necessarily write it all for you.
So first of all, you will want to get MS Visual Studio set up with CUDA, which is easy following this guide: http://www.ademiller.com/blogs/tech/2011/05/visual-studio-2010-and-cuda-easier-with-rc2/
Now you will want to read The NVIDIA CUDA Programming Guide (free pdf), documentation, and CUDA by Example (A book I highly recommend for learning CUDA).
But let's say you haven't done that yet, and definitely will later.
This is an extremely arithmetic heavy and data-light computation - actually it can be computed without this brute force method fairly simply, but that isn't the answer you are looking for. I suggest something like this for the kernel:
__global__ void kernel(int* myNumber, int* numOfHits){
//a shared value will be stored on-chip, which is beneficial since this is written to multiple times
//it is shared by all threads
__shared__ int s_hits = 0;
//this identifies the current thread uniquely
int i = (threadIdx.x + blockIdx.x*blockDim.x);
int j = (threadIdx.y + blockIdx.y*blockDim.y);
int k = 0;
//we increment i and j by an amount equal to the number of threads in one dimension of the block, 16 usually, times the number of blocks in one dimension, which can be quite large (but not 100,000)
for(; i < 100000; i += blockDim.x*gridDim.x){
for(; j < 100000; j += blockDim.y*gridDim.y){
//Thanks to talonmies for this simplification
if(0 <= (*myNumber-i-j) && (*myNumber-i-j) < 100000){
//you should actually use atomics for this
//otherwise, the value may change during the 'read, modify, write' process
s_hits++;
}
}
}
//synchronize threads, so we now s_hits is completely updated
__syncthreads();
//again, atomics
//we make sure only one thread per threadblock actually adds in s_hits
if(threadIdx.x == 0 && threadIdx.y == 0)
*numOfHits += s_hits;
return;
}
To launch the kernel, you will want something like this:
dim3 blocks(some_number, some_number, 1); //some_number should be hand-optimized
dim3 threads(16, 16, 1);
kernel<<<blocks, threads>>>(/*args*/);
I know you probably want a quick way to do this, but getting into CUDA isn't really a 'quick' thing. As in, you will need to do some reading and some setup to get it working; past that, the learning curve isn't too high. I haven't told you anything about memory allocation yet, so you will need to do that (although that is simple). If you followed my code, my goal is that you had to read up a bit on shared memory and CUDA, and so you are already kick-started. Good luck!
Disclaimer: I haven't tested my code, and I am not an expert - it could be idiotic.