I have a program where I created the output:
std::ofstream OutA("A.dat");
There is a loop in this program where data is created to put in A:
for ( k = 1; k < n_iterations ; k++ ){
OutA << Data_for_A << std::endl;
}
However, now I wanted to do another loop.
The evolution of the values that I will put in A depends on a variable, T.
So, I'll make several tables for different T. There will be a loop like this:
for ( T = 0; T < x; T = T + 0.5){
for ( k = 1; k < n_iterations ; k++ ){
OutA << Data_for_A << std::endl;
}
}
But it would be convenient if, as the loop changed the value of T, it would write in different files with different names, according to the variable T.
Example:
The first time you run the loop, pass the data to "OutA1.dat", the second time "OutA2.dat" and follow with the indexes 1,2, ...
Or that the indexes are not 1,2, ... but rather the values of T. Thus: "OutA_T0.dat", in the next "OutA_T0.5.dat", with indexes varying T = 0,0.5 , 1.1.5, ...
What would be the best way to do this?
use std::to_string function.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string Data_for_A() {
return "hello";
}
int main() {
double x = 3;
int n_iterations = 5;
for (double T = 0; T < x; T = T + 0.5) {
string name = "OutA_T" + std::to_string(T) + ".dat";
std::ofstream OutA(name.c_str());
for (int k = 1; k < n_iterations ; k++ ) {
OutA << Data_for_A() << std::endl;
}
}
return 0;
}
Related
I wrote the following function to store the (x, y, z) of a vtkPoint in an array of type double and size of 3*N, where N is the number of vertices (or points).
double* myClass::getMyPoints(void)
{
double* vertices = new double[this->m_numberOfVertices * 3];
for (vtkIdType ivert = 0; ivert < this->m_numberOfVertices; ivert++)
for (auto i = 0; i < 3; ++i)
this->m_points->GetPoint(ivert, &vertices[3 * ivert]);
return vertices;
}
where m_points is a member of myClass and is of type vtkSmartPointer<vtkPoints>.
This function does what I want and works just fine. I was wondering if there is an elegant way of getting the sequential pointers. I tried GetVoidPointer(), which looks like an elegant one-line code, to avoid the for loop but it does not get the coordinates correctly after the function returns vertices.
(double*)(m_points->GetData()->GetVoidPointer(0));
Could someone help me with this?
vtkPoints internally stores it's data as a float array instead of a double array. So you may need to modify your function to work with float* instead of double*. If we want to use double array for vtkPoints then we should call SetDataTypeToDouble() on the vtkPoints object.
#include <stdio.h>
#include <stdlib.h>
#include <vtkPoints.h>
#include <vtkSmartPointer.h>
int main(){
// Create data
auto N = 5;
vtkNew<vtkPoints> pts;
pts->SetDataTypeToDouble();
for(auto i=0; i < N; ++i)
pts->InsertNextPoint(rand()%100,rand()%100,rand()%100);
// Read using for loop
std::cout<< "Using for loop ... " << std::endl;
for( auto j=0; j < N; ++j ){
double p[3];
pts->GetPoint( j, p );
std::cout<< p[0] << "," << p[1] << "," << p[2] << std::endl;
}
// Read using GetVoidPointer()
std::cout<< "Using GetVoidPointer() ... " << std::endl;
auto data_ptr = (double*) pts->GetData()->GetVoidPointer(0);
for( auto k = 0; k < N; ++k )
std::cout<< *(data_ptr + 3*k) << ","
<< *(data_ptr + 3*k + 1) << ","
<< *(data_ptr + 3*k + 2) << std::endl;
return 0;
}
This gives result as follows:
Test that there are N = 5 tuples.
Using for loop ...
83,86,77
15,93,35
86,92,49
21,62,27
90,59,63
Using GetVoidPointer() ...
83,86,77
15,93,35
86,92,49
21,62,27
90,59,63
I'm trying to make my program calcul all these multiplications:
999*999 , 999*998, 998*998, 998*997, ......... Until 100*100.
Right now, it only calcul 999*999 998*998 997*997 ... 100*100.
I don't get why? Can you take a look on my code?
Thanks
BR
#include <iostream>
#include <vector>
#include <cmath>
int main () {
int i = 999;
int j = 999;
while (j >= 100) {
i == j ;
while (i >= j-1) {
std::cout << i*j << std::endl;
i -= j;
}
j = j-1;
}
return 0;
}
You are not seeing your loops correctly. Try to write the numbers you want to compute in a table first, and use it to build your loops.
For one value of your first loop variable - call it i, you want it multiplied by one, then two, then three (etc), values of j.
Regardless of what those values of j actually are, your loops should look like:
for(int i=999; i>=100; --i)
for(int j=999; j>=i; j--)
; //computation goes here
Here you clearly see that for one value of i, you will use one value of j when i=999, then two values of j, then thre...
If you are new at coding, I would recommend starting with for loops and switch to while when you feel comfortable with the former ones.
You can use two for loops like this:
#include <iostream>
int main()
{
for (int i = 999; i > 99; --i)
{
for (int j = 0; j < 2; ++j)
{
std::cout << i * (i - j) << std::endl;
}
}
}
I was trying to correct your code, but the inner while loop really should be deleted. After I deleted it, I can't tell whether I am rewriting it or correcting it. Anyway, it is delete, no need of it at all.
Here is the right code :
#include <iostream>
#include <vector>
#include <cmath>
int main () {
int i = 999;
int j = 999;
while (j >= 100) {
std::cout << i << " " << j << std::endl;
if (i==j)
--j;
else
--i;
}
return 0;
}
The logic is simple, whenever i==j, we --j. Whenever i!=j, we --i.
We begin with i and j at the same position, during the loop, when i is one step behind j, i takes a step. When i and j is at the same position, j takes a step.
As practice for myself I'm trying to create a genetic algorithm that will solve equations. So far my program can generate random "genes", fill up individuals with these "genes", and do some basic calculations with the genes (at the moment, simply summing the "genes").
However, I've realised now that I want to implement my fitness function that I would have been better off creating a struct for individual, since I need to keep the genes and the fitness outcome together to have the fittest genes reproduce again.
Anyway, here's my code:
// GA.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <random>
#include <string>
const int population_size = 10;
const int number_of_variables = 7;
struct one_individual
{
std::vector<std::vector<double>>individual;;
double evaluation = 0;
double fit = 0;
};
int main()
{
// Generate random number
std::random_device rd;
std::mt19937 rng(rd()); // random-number engine (Mersenne-Twister in this case)
std::uniform_real_distribution<double> dist(-10.0, 10.0);
// Create vector that holds vectors called individual and fill size it to the amount of individuals I want to have.
std::vector<std::vector<double>>individual;
for (int i = 0; i < population_size; i++)
{
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
individual.push_back(variables);
}
// Display entire population
for (auto &count : individual)
{
for (auto &count2 : count)
{
std::cout << count2 << " ";
}
std::cout << "\n";
}
// Do calculation with population. At the moment I just add up all the genes (sum) and display the sum for each individual.
for (int i = 0; i < population_size; i++)
{
int j = 0;
std::cout << "Organism "<< i;
double sum = individual[i].at(j) + individual[i].at(j + 1) + individual[i].at(j + 2) + individual[i].at(j + 3) + individual[i].at(j + 4) + individual[i].at(j + 5) + individual[i].at(j + 6);
std::cout << " is " << sum << "\n";
}
std::cout << "\n";
return 0;
}
What I think I should be doing is something like this:
for (int i = 0; i < population_size; i++)
{
one_individual individual;
std::vector<double>variables;
for (int j = 0; j < number_of_variables; j++)
{
variables.push_back(dist(rng));
}
one_individual.individual.push_back(variables);
}
The above code is not working. What happens when I try to compile is I get a list of errors, I just pasted it into pastebin since it's a pretty big list: www.pastebin.com/EVJaV0Ex. If I remove everything except the parts needed for the "creating individuals part" the errors that remain are: www.pastebin.com/djw6JmXZ. All errors are on line 41 which is the final line one_individual.individual.push_back(variables);
Edited for clarity, apologies that it was unclear.
Consider the instruction
one_individual.individual.push_back(variables);
where one_individual is a type (struct one_individual).
I suppose you should use the defined variable of type one_individual, so
individual.individual.push_back(variables);
Let's say I have the following variables:
int number1 = 2;
int number2 = 4;
...
int numbern = 43;
Now what I want is to access these elements in a for loop over number 'i', so something like the following:
for (int i = 0; i < n; i++)
{
if(number1 == someFunc("number" + to_string(i)))
{
// do stuff
}
}
Here 'someFunc' should make sure that it recognizes that I want to use the number that the string corresponds to. How could I do this?
For using std::map you can do something like this:
#include <iostream>
#include <stdlib.h>
#include <map>
#include <string>
using namespace std;
int main (void)
{
map<string,int> mymap;
mymap["number1"] = 2;
mymap["number2"] = 4;
/* ... */
char number[2];
number[1] = '\0';
for(int ii=1; ii<=2; ii++)
{
number[0] = (char)(ii+48);
cout << string("number")+string(number) << ": ";
mymap[string("number")+string(number)] += 1;
cout << mymap[string("number")+string(number)] << endl;
}
return 0;
}
Here is the string the key through which you can access the actual number. In this example I didn't ensure that the key actually exists anyway this should be done normally.
If the number of numbers is not big then you can write
int i = 0;
for ( int x : { number1, number2, /* other numbers */ numbern } )
{
if ( x == someFunc( "number" + to_string( i ) ) )
{
// do stuff
}
++i;
}
Otherwise you should place the numbers in some container.
I can think of the following two options:
Use an array.
int numbers[] = {/* Put the initialization data*/};
....
if(number1 == someFunc(numbers[i]))
Use a map. This option is useful if the size of the array is open to change or the key is expected to not follow the usual array index values.
std::map<int, int> numbers;
// Add code to initialize the map.
....
if(number1 == someFunc(numbers[i]))
I have a matrix of values (stored as an array of values) and a vector with the matrix dimensions( dims[d0, d1, d2]).
I need to build a string like that:
"matA(j, k, l) = x;"
where j, k, l are the indices of the matrix and x the value of the element. I need to write this for each value of the matrix and for matrices with 2 to n dimensions.
I have a problem isolating the base case and replicating it in a useful way. I did a version in a switch case with a case for each dimension and a number of for cycles equal to the number of dimensions:
for (unsigned int k=1; k<=(dims[2]); k++)
{
for (unsigned int j=1; j<=(dims[1]); j++)
{
for (unsigned int i=1; i<=(dims[0]); i++)
{
strs << matName << "(" << i << "," << j << ","<< k << ")="<< tmp[t]<< "; ";
....
but is not what I wanted.. Any idea for a more general case with a variable number of dimensions?
You need a separate worker function to recursively generate the series of indices and main function which operates on it.
For example something like
void worker(stringstream& strs, int[] dims, int dims_size, int step) {
if (step < dims_size) {
... // Add dims[step] to stringstream. Another if may be necessary for
... // whether include `,` or not
worker(strs, dims, dims_size, step + 1);
} else {
... // Add cell value to stringstream.
}
}
string create_matrix_string(int[] dims, int dims_size, int* matrix) {
... // Create stringstream, etc.
strs << ... // Add matrix name etc.
worker(strs, dims, dims_size, 0);
strs << ... // Add ending `;` etc.
}
The main problem here is the value, since the dimension is not known during compilation. You can avoid that by encoding matrix in single-dimensional table (well, that's what C++ is doing anyway for static multidimensional tables) and call it using manually computed index, eg. i + i * j (for two-dimensional table). You can do it, again, by passing an accumulated value recursively and using it in final step (which I omitted in example above). And you probably have to pass two of them (running sum of polynomial components, and the i * j * k * ... * x product for indices from steps done so far.
So, the code above is far from completion (and cleanliness), but I hope the idea is clear.
You can solve this, by doing i, j and k in a container of the size of dim[] - sample:
#include <iostream>
#include <vector>
template< typename Itr >
bool increment( std::vector< int >& ijk, Itr idim, int start )
{
for( auto i = begin(ijk); i != end(ijk); ++i, ++idim )
{
if( ++*i <= *idim )
return true;
*i = start;
}
return false;
}
int main()
{
using namespace std;
int dim[] = { 5, 7, 2, 3 };
const int start = 1;
vector< int > ijk( sizeof(dim)/sizeof(*dim), start );
for( bool inc_done = true; inc_done
; inc_done = increment( ijk, begin(dim), start ) )
{
// .. here make what you want to make with ijk
cout << "(";
bool first = true;
for( auto j = begin(ijk); j != end(ijk); ++j )
{
if( !first )
cout << ",";
else
first = false;
cout << *j;
}
cout << ")= tmp[t] " << endl;
}
return 0;
}