for(int t(0); t < 10;++t) { cout<<t<<endl;}
I'm just biginer in C++, and want to know how can I take the last elemnt of my "cout...."; in this case my laste element is 9
thx for help ;)
int c = 0;
for(int t = 0; t<10; t++)
{
c = t;
}
cout<<c;
This might be what you are looking for I am not sure I understand your question properly though.The variable c should hold the last element of t when the loop ends.
You can extract int t from the for loop :
int t;
for (t = 0; t < 10; ++t)
{
cout << t << endl;
}
int t = 9;
cout << t << endl;
Now you have the last element, #9.
ghagha, in C++ the ranges are run from 0 to n-1, in your example you have a range of 0 to < 10 hence 0 to 9, therefore your last element is 9. But as I said you can do any range as n-1 for the last element, provided that it follows normal conventions (it is possible to have a range from 1 to n if you code it that way)
It is not clear what you want but in any case your loop contains a bug. Instead of
for(int t(0); t < 10; t) { cout<<t<<endl;}
should be
for(int t(0); t < 10; t++) { cout<<t<<endl;}
that is variable t has to be incremented.
One simple way -
int t = 0;
for (; t < 10; ++t)
cout << t << ;
Tough the correct way to do it will be (one variable should not have two meanings, i.e 1. last element, 2. iterator context) -
int last_element;
for (int t = 0; t < 10; ++t;
{
cout << t << ;
last_element = t;
}
Related
Basically i generated a adj_matrix and i want to make an adj_list from the adj_matrix...However I keep getting an error saying "no match for call..."
i tried it without aPair i still get the same error i can't seem to figure out what my problem is. Can anyone tell me why list isn't working? the list is at the very end of the code
int **gen_random_graph(int n)
{
srand(time(0));
int **adj_matrix = new int*[n];
for(int i = 0; i < n; i++)
{
for (int j = i; j < n; j++) //generating a N x N matrix based on the # of vertex input
{
adj_matrix[i] = new int[n];
}
}
for(int u = 0; u < n; u++)
{
for (int v = u; v < n; v++)
{
bool edgeOrNot = rand() % 2; //decide whether it has an edge or not
adj_matrix[u][v] = adj_matrix[v][u] = edgeOrNot;
if(adj_matrix[u][v] == true)
{
adj_matrix[v][u] = true;
if(u == v) //We can't have i = j in an undirected graph so we set it to false
{
adj_matrix[u][v] = -1;
}
}
else //if adj_matrix[u][v] is false set the symmetry to be false
{
adj_matrix[v][u] = adj_matrix[u][v] = -1;
}
}
}
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++) //create the N x N with edges and sets the weight between the edge randomly
{
if(adj_matrix[i][j] == true)
{
int weight = rand() % 10 + 1;
adj_matrix[i][j] = adj_matrix[j][i] = weight;
cout << " ( " << i << "," << j << " ) " << "weight: " << adj_matrix[i][j] << endl;
}
}
}
for(int i = 0; i < n; i++)
{
vector<int> adj_list;
for(int j = i; j < n; j++)
{
if(adj_matrix[i][j] > 0)
{
int weight = adj_matrix[i][j];
adj_list.push_back(j);
cout << adj_list[i] << " " << endl;
}
}
}
print(n,adj_matrix);
return (adj_matrix);
}
I see that adj_list is not callable, so your code there is broken. There are a couple simple solutions to that. Taking a look at these docs, you may simply either access listObj.front() and listObj.back() OR you may also just create an iterator using listObj.begin() and iterating over the two elements (which may be desirable if you ever decide to put more than two elements in the list). See this tutorial for a simple example on creating an iterator for a list, in the code snippet right above the summary.
Note, here, your list object which I called listObj for simplicity/abstraction would simply be adj_matrix[i][j] in that bottom loop. That should fix your syntax error.
Also, aside from the syntax of your code, I don't get why you're trying to push weights to a list, then you're printing out and returning the adjacency matrix. I also don't get why you would use lists of pair objects when it seems like you only want to push integer weights onto it. For that, you can use a simple vector of integers (i.e.: vector <int> adj_list;)... or even simpler, you could use a simple array of integers... rather than using a vector of lists of pairs.
EDIT: After running the code locally and taking a look at the values, I realized the issue a bug in the OP's output was simply that he was using "true" in C++ in place of an integer, which was creating a bug, as explained in this SO post. The OP also has a further design decision to make where adjacency lists are concerned. More on what an adjacency list is, conceptually, found on Wikipedia.
Array<Personne> personnes;
while (in) {
Personne newPersonne;
in >> newPersonne;
if (in.eof()) break;
personnes.add(newPersonne);
if (personnes.size() > 1) {
for (int i = 0; i < personnes.size() - 1; ++i)
for (int j = i + 1; j < personnes.size(); ++j) {
string typeRelation = personnes[i].getTypeRelation(personnes[j]);
if (typeRelation != "")
cout << personnes[i].getNom() << " and " << personnes[j].getNom() << " are " << typeRelation << endl;
if (j == personnes.size() -1){
personnes.delete(i); //doesn't work very well, want to delete the first element when finishing the copmarison withe the other elements.
}
}
}
}
I want to delete the first elements of the Array when the second loop reaches its end.
It's tricky with arrays, removing the first item requires you to move everything after it left one (so the 2nd item becomes the 1st item). you can use a loop for this if you want but I think the better option would be to use a different data structure like a Deque http://www.cplusplus.com/reference/deque/deque/
A couple of killers in the Tableau::delete method:
The function will not compile because of the use of the delete keyword as the function's name
elements[index+1] will allow reading elements[nbElements] Which may or may not be out of the array's bounds, but is certainly one more than intended.
Try instead:
template <class T>
void Tableau<T>::remove(size_t index) // size_t is unsigned and prevents input of
// negative numbers. One less test required.
// nbElements should also be made unsigned to match
// function name changed to something legal.
{
assert(index < nbElements); // this also ensures nbElements is > 1
// so nbElements-- will not go out of bounds
nbElements--; // moved above the loop because the index+1 will grab the last element
for( ; index < nbElements; index++) // no need to have an i. Index already does this
{
elements[index] = elements[index+1];
}
}
for (int i = 0; i < personnes.size() - 1; ++i)
// other file
template <class T>
void Tableau<T>::delete (int index)
{
assert(index < nbElements && index >= 0);
for(int i = index; i < nbElements; i++) elements[i] = elements[i+1];
nbElements--;
}
if size() is calculated with nbElements, then choose between :
for (int i (index); i < personnes.size();)
and changing the way you remove empty cases of your Array. (without changing the position of the next person tested)
because i believe you jump 1 person out of two :
you check person i then you replace person i + 1 to person i then you check person i+1 (which is actually person i+2)
I have two vectors - one is global and second one local. I need to copy elements from local vector to global in order 1st, 4th, 7th, ... In the local one is array of size 6. My code works fine but it always make one more iteration which leads to loading wrong data. On the last iteration it also copy wrong data. Do you have any idea what is wrong in my code?
int iter = 0;
float nr;
for (i = 0; i < vect_local.size(); i++){
iter += 1;
nr = vect_local[i];
vect_global.push_back(nr);
i += 2;
if((vect_local.size()/iter) == 3){
iter = 0;
break;
}
}
EDIT: for (i = 0; i < = vect_local.size(); i++)
Stupid typo. But my problem is still the same...
your loop condition should be i < vect_local.size() because the last index is size-1
int iter = 0;
float nr;
for (i = 0; i < vect_local.size(); i+=3){
// ^
Maybe Something like this ?
int main () {
int globalarray[16]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int localarray[6]={0,0,0,0,0,0};
int internalcounter=0;
for(int i=0;i<int(sizeof(globalarray)/sizeof(int));i=i+3)
{
localarray[internalcounter] = globalarray[i];
internalcounter+=1;
}
for(int i=0;i<6;i++)
{
cout<<localarray[i]<<endl;
}
return 0;
}
That prints :
1
4
7
10
13
16
I am trying to create a nested for loop that fills in values in an array from 1 to 20.
IE) array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
int array[20];
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
Supposedly, The array index should count up with "i", and should be equated to "j" which is also counting up. The array element is printed to the console as it is filled.
I expected 1 -20 to be printed out once, but when I run the code, 1-20 prints out multiple times. Can someone tell me the problem? Thanks!
Your outer for loop runs 21 times, your inner for loop runs 20 times each of the outer for loop iterations, so you have a total of 21 * 20 = 420 print statements.
You can simply do
for(int i = 0 ; i < array.length ; i++)
{
array[i] = i + 1;
cout << array[i] << endl;
}
If you look at your array when you're done, it will also be just a series of 20s. The first loop is saying "do this 20 times" and then the second loop is saying "set and print the value of that array element 20 times." What you need to do is include a check for whether you're assigning the correct j value to the correct array[i] value, and only set the value in that case. Something like:
if (j == i + 1) array[i] = j;
Why do you need a nested loop?
for(int i = 0; i<20; i++)
{
array[i] = i + 1;
cout<< array[i];
}
yes, you have two loops when you only need one:
for(int i = 0; i<21; i++)
{
array[i] = i + 1;
cout<< array[i];
}
In order to fill the array and to print the result you just need two simple for loops
for(int i = 0; i<20; i++)
{
array[i] = j;
}
for(int j =0; j<20; j++)
{
cout<< array[i];
}
The nested loop that you created above will do exactly what you described.
For each loop of the outer for loop it will execute the full 20 loops of the inner loop.
so in total you will execute it 21 * 20 times.
Also be careful with your index. You want to start with int i = 0 to i < 20 which loops exactly 20 times.
I don't know why you are attempting to print a single element in you array, but it isn't necessary to use nested loops here; in fact, a loop isn't required at all:
// vector version
std::vector<int> vec(20);
std::iota(vec.begin(), vec.end(), 1);
// array version
int arr[20];
std::iota(std::begin(arr), std::end(arr), 1);
If you want to print out the whole array after you've initialized it:
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
I see a lot of people answered about this question, so I will not repeat them, I'll just mention that you are writing outside the array size.
if you have int array[20], you should loop
for(int i = 0; i<20; i++)
the last index is 19
The outer loop 21 times repeats the inner loop
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
The inner loop does the same operation that is assigns elements of the array sequantial numbers. Moreover your code has a bug because due to the outer loop youare trying to access element array[20] that does not exist, because if the array was defined as
int arrat[20];
then the valid indicies are 0 - 19.
That do not bother about writing correctly required loop or loops you could use standard algorithm std::iota
For example
#include <iostream>
#include <numeric>
#include <iterator>
#include <algorithm>
int main()
{
const size_t N = 20;
int array[N];
std::iota( std::begin( array ), std::end( array ), 1 );
std::copy( std::begin( array ), std::end( array ), std::ostream_iterator<int>( std::cout, " " ) );
}
Or instead of the algorithms you could use the range based for statement. For example
#include <iostream>
int main()
{
const size_t N = 20;
int array[N];
int i = 1;
for ( int &x : array )
{
x = i++;
std::cout << x << ' ';
}
}
If you really want to use nested solution, (for example game board coordinates) then this is my solution.
// nesting arrays for example game board coordinates
#include <iostream>
int main(){
int x = 20;
int y = 40;
int array[x][y];
// initialize array of variable-sized.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
array[i][j] = 0; // or something like i + j + (i * (y-1)) if you wish
// and send it to cout
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
//notice, that when sent to cout like this, x and y flips on screen, but
//logics of coordinates is ok
// and then do something usefull with it
return EXIT_SUCCESS;
}
int size = 20;
for (int i = 0; i < size; i++)
{ int array[i];
array[i] = i + 1;
cout << array[i]<< " ";
}
You could populate your array with 1 for loop, and gauge the size of your array like stated above.
I've searched and found similar problems, but they all didn't seem to fit with mine. Basically, I need to write a recursive function that nests a loop N times and prints everything only on the very last loop. If you can find another solution to the problem, that would be great.
0 = *
1 = +
2 = ABC
3 = DEF
...
8 = STU
9 = VWXYZ
Here is the full code: http://pastebin.com/2YdQ693N
Here is a hard-coded N=3 example:
//sout is a vector<string>
for(int i = 0; i < sout[0].size(); i++)
{
for(int j = 0; j < sout[1].size(); j++)
{
for(int k = 0; k < sout[2].size(); k++)
{
cout << sout[0][i] << sout[1][j] << sout[2][k] << endl;
}
}
}
the following output of this particular example (input is "123"):
+AD
+AE
+AF
+BD
+BE
+BF
+CD
+CE
+CF
The closest I got before coming here was a recursion function similar to this one here: http://v2.cplusplus.com/forum/beginner/68434/ but I couldn't get it to work for my case.
I need the indexes to go in this type of order:
000
001
002
010
011
012
020
021
022
except the length has to be variable (and therefore height as well).
Here is my recursion function I've been trying so far:
void recurseLoop(const vector<string>& sout, int numLoops)
{
if(numLoops > 0)
{
for(int i = 0; i < sout[1].size(); i++)
{
//cout << i;
recurseLoop(sout, numLoops - 1);
}
}
else
{
//cout << endl;
return;
}
}
However the result that 'i' gives is pretty much unintelligible and I'm having trouble getting the correct structure of loops/if statements to get this to work. Any help is appreciated!
void recursion(int N, const vector<string>&sout, vector<int>&index, int I=0)
{
if(I<N-1)
for(index[I]=0; index[I]<sout[I].size(); index[I]++)
recursion(N,sout,index,I+1);
else if(I==N-1)
for(index[I]=0; index[I]<sout[I].size(); index[I]++) {
for(int k=0; k<N; ++k)
std::cout << sout[k][index[k]];
std::cout << std::endl;
}
}
void loop_N_times(const vector<string>&sout)
{
std::vector<int> index(sout.size());
recursion(sout.size(),sout,index,0);
}
Why are you always use sout[1] in recursion? It probably should be something like
for (int i = 0; i < sout[sout.size() - numLoops].size(); ++i)