Is there a built-in function that will shuffle an array? [duplicate] - c++

This question already has answers here:
Is it possible to random_shuffle an array of int elements?
(5 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am trying to create a deck of cards in C++. I store that deck in an array array<Card, 52> deckOfCards = generateCards(). Once I create the array, is there any way to shuffle the objects inside of it easily? For example, in Java, you could use the shuffle() algorithm and the objects would be shuffled.
People have mentioned the usage of random_shuffle in the comment, however random_shuffle has been deprecated since C++14, and removed since C++17.

Yes, C++ does have a shuffle() function. However, you must also add a random generator in there manually, which could be daunting at a first glance. However, if you don't really care the exact generator and engine being used, then this could be done simply with:
std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::default_random_engine{/*optional seed*/});
or
std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::random_device{});
Where the first one is deterministic and the second one is non-deterministic.

Related

Two dimensional array in c++ initialization to one value [duplicate]

This question already has answers here:
how to set or initialize default value for all elements of a table or 2d array or multdimentional array
(4 answers)
Closed 3 years ago.
I have two dimensional char array in c++ and want to give all element one value without using loops
is there any function to achieve it ?
char demo[5][7];
memset(demo, '\0', sizeof(demo));
Based on the provided info, does this do what you want?
Since you're using C++ I'd question to use a native char array, as long as you're not required to and/or needing to use the stack.
Otherwise its idiomatic to use the collection classes provided by the STL.
Adding to the answer as requested, this obviously does what the question asks for: initializing the memory of a char array.
Please see the docs for more information on memset: https://en.cppreference.com/w/cpp/string/byte/memset

is there any way to let the user choose which variable is to be inputted? [duplicate]

This question already has answers here:
Accessing a class member variable by its name at runtime [duplicate]
(3 answers)
Closed 5 years ago.
this is for a personal use application in c++
for example:
class x
{...};
int main()
{
string userinput;
cin>>userinput;
cin>>x."userinput";}
is something like this possible?
If what you are talking about is allowing for the user to set variable names at runtime, then no. It is not possible in c++. Depending on what you are trying to achieve, there are a few ways around this.
If you just need the user to be able to access a small number of variables, all of which are known before hand, you can use a switch statement, or a bunch of if/elseifs
If you need to store a larger amount of variables the number of which may not be known at compile time, then there exists a number of data structures that exist just for this purpose. There are arrays, hash tables, linked lists and hundreds of variations on the above. These are all far too complex topics to cover in a single answer however.

std::bitset - how to iterate "set" (or "not set") bits? [duplicate]

This question already has answers here:
Efficient way of iterating over true bits in std::bitset?
(7 answers)
Closed 8 years ago.
I'm using bitset in my code:
std::bitset<MAX_INSTRUMENTS_NUMBER_IN_SYSTEM> updatedInstruments;
Often I need to iterate only values that "set" (or "not set"), this is how I do that:
for (int instrumentId = 0; instrumentId < MAX_INSTRUMENTS_NUMBER_IN_SYSTEM; instrumentId++) {
if (!updatedInstruments[instrumentId]) {
continue;
}
// work
}
Can this iteration be improved to be more readable and possibly faster?
I don't think you can exploit the contiguity of set bits in your code using std::bitset: the interface doesn't provide anything to help in this task, and there's no legal way to access the underlying storage and work directly with it.1
If instead you can afford to change container, you can find several better alternatives. Here for example is a bitset-like structure that provides "enumerators" for active bits (it seems mostly like working with spans on images), and in the duplicate I linked above there are several other suggestions for data structures more specialized for this use case.
Previously I supposed that iterators might have yielded some performance advantage, but turns out std::bitset doesn't have iterators :-o Also, a similar test performed on std::vector<bool> (which should pack bits more or less the same way) gave a ~2x slowdown using iterators both with g++ and clang++.

Multidimensional Array Implementation [duplicate]

This question already has an answer here:
how to traverse a boost::multi_array
(1 answer)
Closed 8 years ago.
After searching for a while I did not find an answer to my question, so apologies in advance if this was already answered somewhere else.
I'm looking for a multi-dimensional data-structure in C++ that allows access not only as N-dimensional array, but also as 1-dimensional.
For an example assume a simple 2-dimensional matrix (it could go to higher dimensions, but in that case let's stick to this example). In most cases the member will be accessed in row-colum-form, e.g. matrix[x][y]. In other cases it might be desireable to access all members as a single list, e.g. for matrix addition using std-algorithms.
Standard-Approach would probably be something like std::array<std::array<double, 4>, 4> and write additionally an iterator with linear access to all members and maybe an extra accessor function.
A second approach is the other way around std::array<double, 16> with accessors in row-colum-form, but in this case it gets tricky to return whole columns .
Or maybe it is doable with boost MultiArray, but I think reducing the dimensions of a MultiArray always results in only getting slices of the MultiArray.
My question boils down to: Is there already an implementation in the standard-library or some well-known library, like boost, for this? If not, am I missing a point and there is a simpler method than the ones I wrote about?
EDIT: I was not looking for only iteration over all values, like in the mentioned question. But however from the pointed documentation I could find that MultiArray can be accessed as C-style array which is enough for my needs. This can then be closed and thanks for all answers
See boost::multi_array::data() and boost::multi_array::num_elements().
As with std::vector, it would appear you can just access it as a solid block of memory by index, if that's all you want. I've never done this, but looks like you can. Just because you can doesn't necessarily mean you should, but, well...
See this answer:
how to traverse a boost::multi_array
There is something like what you are looking for: std::valarray<T>. Well, the intend of the std::valarray<T> class template is to provide different views on the same array and to support potentially vectorized evaluation. That said, it doesn't really work and probably few people are using it.
However, from what you described you probably want to have something providing an array view on an existing array. I'd be pretty sure that this was implemented before, if nothing else as a replacement for std::valarray<T> but I can't point to an implementation.

Find an element in a vector array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to find an item in a std::vector?
I am using C++ Builder to create a VCL Forms application. I also have a vector array of appointment objects that each have a name, type, reminder date/time, a date/time, location and comments.
I am wanting to implement a find feature that will let a user find an appointment given certain criteria.
The user can choose to find an appointment in the vector array by either choosing the name, type etc or a combination of each.
What would be the best programming concept to use for this situation? The vector is not large. No more than 10 or 20 elements.
Thanks
Use std::find_if() and define the required predicate (if C++11 you can use lambda function).
See online demo http://ideone.com/Md7sp.
std::find_if(A.begin(),A.end(),isthatit(conditions));
where isthatit is a predicate object constructed from conditions.
If you have many criterias you should think about
Boost.MultiIndex container which targets different search indexes.
http://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/index.html