I am very certain that I saw the syntax for what I want to do on this website a while ago, but I cannot find it anymore and I forgot what it was. Say I wanted to store the values from 1 to a 100 in an array. What would be the syntax without using a loop. I remember the syntax being something like this:
int line [] = {1 .. 100};
What is the correct syntax?
UPDATE: I figured out what I meant by this question. What I read a while ago was the syntax to have all the elements in an array equal to a number. For example, in a GCC compiler, you can set all the elements in an array equal to zero like this:
int line [10] = {[0 ... 9] = 0};
By doing this, all the elements in the array will be equal to 0. It is a very useful thing to know in my opinion and much easier than using a for-loop.
Try like this:
const int line[5] = { 1, 2, 3, 4, 5 };
Related
I've been trying to learn how to use vectors in c++, and they seem much more complicated in java. In order to add items to a vector, I've had to use an iterator. What I'd like to be able to do is just use add remove functions and loop over them as in java. Is this possible? I'm trying to achieve something like the line I marked with an error below : insert(index 3, number 13), but this throws an error. Thanks in advance.
vector<int> myvector(0,0);
vector<int>::iterator it;
it = myvector.begin();
int q = 0;
for(it=myvector.begin();q<16;q++){
it = myvector.insert (it, q);
}
myvector.insert(3,13); //ERROR
You got advice above how to populate the vector.
If you want to insert something at specific index, you can do the following
//similar to myvector.insert(3,13); //ERROR
myvector.insert( myvector.begin()+3, 13);
The code above will insert 13 before element #3 so that 13 becomes element #3 (numeration starts with 0, so "begin" corresponds to element #0).
To replace element #3 with 13, you simply use
myvector[3] = 13;
Here is the link where you can learn about the C++ STL(Standard Template Library), such as: vector, queue, stack, list etc.
Is it possible to characterize an integer array in C++? Once characterized, arrays containing same set of elements will have same characteristics.
I was thinking on lines of hashcode, each hashcode will uniquely identify an array!
For example ary[]={4,5,3,2,4} and ary_two[]={4,4,2,3,5} should both have same characteristics/ hashcode!
I am trying to solve this question( asked in an interview ): A number of variable sized arrays are being generated. For each array determine if we have encountered an array before containing the same elements as this array!
Investigate std::hash. You can probably overload it to do what you want. For instance, if you want the arrays with values {4, 5, 3, 2, 4} and {4, 4, 2, 3, 5} to hash to the same value, you could specialize it like this:
template<> struct hash<std::array<int, 5>>
{
size_t operator()(const std::array<int, 5> &ary) const
{
return std::accumulate(std::begin(ary), std::end(ary), 0U) * 16777619;
}
};
One possible solution would be to use the elements hashes themselves (assuming the content of the array is hashable). Then just fold them together with some suitable function (e.g. an xor or better yet +). Make sure the folding function is commutative and associative, or the order of the array will make a difference.
EDIT: Sorry, this turned out just to be my mistake in initializing in the code below.
const int kDigits = 7;
std::vector<int> number(kDigits);
for (int i = kDigits - 1; i >= 0; i--) {
number[i] = i + 1;
}
The vector number is initialized to 7, 6, 5, 4, 3, 2, 1.
My goal is to generate the permutations in decreasing order:
7654321
7654312
7654231
7654213
7654132
This code works:
do {
...
}
while (std::prev_permutation(number.rbegin(), number.rend()));
However, I'm not understanding why. Since 7654321 is the largest lexicographical permutation, shouldn't while (std::prev_permutation(number.begin(), number.end())); (no reverse iterators) generate it correctly, since it would generate the previous permutation in order? However, this returns false on the first try, even though it should generate the "lower permutation."
Also, in the code shown above, since it uses reverse iterators, my mind interprets it as finding the previous permutation of 1234567 (7654321 backwards), which seems to me should have none.
Thanks so much for the help in advance! I look forward to figuring out what I misinterpreted / what I'm missing.
The vector number is initialized to 1,2,3,4,5,6,7, not 7,6,5,4,3,2,1. That's why your code works.
If you want it initialized to 7,6,5,4,3,2,1, you need to fix the initialization routine.
The first permutation, by definition, has no previous permutation in forward order. Otherwise it wouldn't be first. That's why you need rbegin to get the "first" permutation for a reverse iterator (which is the last permutation).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generating all Possible Combinations
Is there a good LINQ way to do a cartesian product?
How to generate combination of N elements with limited supply of 2 each without explicit nested loops
I have a list of lists, and I want to iterate all the possible combinations where I choose one element from each inner list. This is pretty straightforward if I know at compile-time how many lists there are, but how can I do it when I don't know in advance how many lists there will be?
If I have three lists (and if I know, at compile-time, that there will be exactly three lists), and I want all the combinations of choosing a single element from each of the three lists, I can do that easily with a LINQ query:
var list1 = new[] { 1, 2 };
var list2 = new[] { 3, 4 };
var list3 = new[] { 5, 6 };
var combinations = from item1 in list1
from item2 in list2
from item3 in list3
select new[] { item1, item2, item3 };
// Results:
// {1, 3, 5}
// {1, 3, 6}
// {1, 4, 5}
// {1, 4, 6}
// {2, 3, 5}
// {2, 3, 6}
// {2, 4, 5}
// {2, 4, 6}
But how can I do the same thing when I don't know at compile-time how many lists there will be?
var lists = new[] {
new[] { 1, 2 },
new[] { 3, 4 },
new[] { 5, 6 } };
var combinations = ???;
// This particular example happens to be the same inputs as above, so it
// has the same expected outputs. But there could be two lists instead,
// or four, so the three hard-coded "from" clauses won't work.
It seems like this should actually be doable in LINQ -- SelectMany already does the equivalent of two nested foreach loops, so all I need to do is do a bunch of SelectMany calls and then combine all the results with another SelectMany. Or something. But when it starts getting meta like that, my brain gets all tied in knots. I can't get a handle on how to put the pieces together. I can't even figure out what the generic type arguments to the outer SelectMany call would be.
How can I iterate those lists of lists, and return all the combinations, without knowing at compile-time how many lists there will be?
(Note: everywhere I used arrays above, I'd be fine with using IEnumerable<T> instead. Arrays are easier to write in sample code, but I'm expecting that the output is more likely to be in the form IEnumerable<IEnumerable<int>> rather than the int[][] I show in my sample output above.)
You don't use SelectMany to combine the SelectMany calls; you use Aggregate. Code courtesy of Eric Lippert (answering on a question that's much more specific than this one, but giving a general answer that fits this question as well):
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item}) :
);
}
As with all of Eric's answers, he includes a detailed discussion that lays out exactly how and why this works, in terms of the equivalent non-LINQ code.
Is there any way to check if a given index of an array exists?
I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.
I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++
PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks
In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:
int i[10];
i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about
It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result:
#include <map>
#include <string>
// Declare the map - integer keys, string values
std::map<int, std::string> a;
// Add an item at an arbitrary location
a[2] = std::string("A string");
// Find a key that isn't present
if(a.find(1) == a.end())
{
// This code will be run in this example
std::cout << "Not found" << std::endl;
}
else
{
std::cout << "Found" << std::endl;
}
One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value
if(a[2] == 0)
{
a[2] = myValueToPutIn;
}
as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.
My personal vote is for using a vector. They will resize dynamically, and as long as you don't do something stupid (like try and access an element that doesn't exist) they are quite friendly to use.
As for tutorials the best thing I could point you towards is a google search
To do this without vectors, you can simply cross-check the index you are tying to access with the size of array. Like: if(index < array_size) it is invalid index.
In case the size is not known to you, you can find it using the sizeof operator.
For example:
int arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int arr_size = sizeof(arr)/sizeof(arr[0]);
It sounds to me as though really a map is closest to what you want. You can use the Map class in the STL (standard template library)(http://www.cppreference.com/wiki/stl/map/start).
Maps provide a container for objects which can be referenced by a key (your "index").