Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am creating a program that will read information from a file and use it to create an object for my class Single.
Right now all I have is a person's name and then their age on the following line in the format:
name
age
name
age etc.
I am trying to use a for loop to create an object and name it based on the i value in the loop (the first object is "0", second is "1", etc.).
Does anybody know how I could accomplish this? Everything I try comes up with an error, the most common being redefinition of int i to Single, which makes sense to me. I just need to know if this is possible. Thanks!
If you catch yourself numbering your variables, you are in a scenario where you should use a container. This can be as simple as an array
int numbers[20];
or as complex as an std:: container like vector or list:
std::vector<int> numbers;
std::list<int> more_numbers;
Don't forget to
#include <vector>
#include <list>
if you use the standard containers.
I guess this falls under the XY problem.
As far as I understand your intention, you have multiple options:
Instead of doing what you currently do, create a class that represents the content of the file (one std::string field, on int field) and read two lines in every loop iteration.
Create two std::vectors, one for std::strings and one for ints, and alternate between these two with every loop iteration. E.g. if(i%2 == 0) /* read and insert into string vector */.
This needs to be done in a container. Since you're reading from a file you're most likely going to want to do this in a 'while' loop instead of a 'for' loop during the "while(inputFileStream.read())". Create the vector before the loop and populate it during the loop with the "push_back()" function for vector.
I'm not sure exactly how your file is setup to be read, but it would be easier to have the file delimited with the information you need for each object on the same line, you could store each piece in a temporary variable and then instantiate your object. For instance, assuming you made a constructor for your object "Object object(temp1, temp2)" then simply "v.push_back(object)"
Hope this helps.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I created my own flowchart and I am following that. What stands as a problem for me is that I cant keep different data type at different places(for eg. the array is arr[4][4] then in arr[3][1] and arr[4][3] I want char and rest int)
What I want to try is in a multidimensional array, the first row, last row, first column, last column 4th and 8th both row and column to store '*' and rest numbers
I'm not sure if it is possible or not with templates or by any method.
What stands as a problem for me is that i cant keep different data type at different places(for eg. the array is arr[4][4] then in arr[3][1] and arr[4][3] i want char and rest int)
An array has one element type. All its elements have that type, no other.
However, char is an integer data type, and every C++ implementation you are likely ever to see can accommodate every possible value of a char in an object of type int. Therefore, it is safe, in practice, to store the value of a char in an array element of type int. If you have done so and not subsequently modified that array element, then you can also read it back and store the value in a char.
(Do note, by the way, that there is a big difference between one char and an array of char, such as C uses for its strings. We sometimes see confusion about that around here.)
More generally, though, you should be choosing appropriate data types. If you have hetergeneous data that you want to treat as a unit, then you should be declaring a class to contain it, not using an array for that.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am beginner in oop in c++ fairly say in programming. i am trying to make the array of objects and pass it to member function sort(class_name[size]) to sort by their id number.
i have tried so hard for passing arrays of objects but cant find the solution.
please help on it.
Thanks in advance.
Classically and erroneously, arrays have been passed by:
Name of the array
Address of first element
The biggest issue is the length (capacity) of the array. In C and C++ the array (not std::array), does not store it's capacity. So the receiving function has no clue to the end of the array.
Another issue is the number of elements in the array. In C and C++, the array structure does not maintain the number of items in the array. An array may have a capacity of 32 elements, but only 3 loaded.
If you write your own functions and use an array, please provide arguments for the array, the capacity and the number of elements in the array.
Edit 1:
One problem with passing a pointer or the address of the first element is that the pointer only points to a single character, and technically, not an array object. The assumption has been that an array is a container where the elements are consecutive with no other data types between. Thus you only needed to know the first position of the array.
A problem is that I could pass a pointer to a single character and the receiving function would treat the data as an array of characters instead of a single character. Thus creating undefined behavior often known as buffer overruns.
So to be more type safe, you should use the array syntax when passing arrays rather than a pointer to the first element. For better safety, using std::vector or std::array or put the array in a structure and pass the structure.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using a code that someone else wrote for calculating chemical reactions. The user must specify many values for a calculation and this can lead to mistakes. I am trying to automate/simply this process.
I can instantiate a class by doing (for example):
Algorithm<double> chlorine;
I would like to do multiple instantiations--for example, chlorine, hydrogen, and oxygen. I don't understand why I get a segmentation fault when I put "chlorine," "hydrogen," and "oxygen" as elements in a vector of strings called "chemicalElements"and then do:
for (i = 0; i < chemicalElements.size(); i++)
{
Algorithm<double> chemicalElements[i].data();
}
Am I missing something simple here? When I write:
Algorithm<double> chlorine;
"chlorine" is just a string, right? So why would it not work to add "chlorine" from an element in a vector of strings?
chlorine is not a string in your example code, it's an identifier for a variable (of type Algorithm<double>).
Variables must be given compile-time identifiers; that means the identifier must be specified when the compiler is traversing your code. The result of chemicalElements[i].data() is unknown until runtime.
C++ doesn't have any facility for creating variable names at runtime, so you cannot do what you are directly asking. However, it sounds like what you really need is a collection of algorithm objects, one for each of your elements. To create an array of algorithm objects, you can do:
Algorithm<double> algorithms[15];
This creates 15 distinct algorithm objects, which you can map to your elements however you like. You can of course choose a different number than 15, so long as that number is a compile-time constant value.
You may also be interested in learning about std::vector<T>, a type that allows you to create dynamically-resizing arrays, or std::map<K,V> which allows you to create an associative mapping between a key value (a string, such as "chlorine," and a value, such as the associated algorithm).
To use the latter, you can do something like this:
std::map<std::string, Algorithm<double>> algorithms;
algorithms["chlorine"] = Algorithm<double>();
algorithms["argon"] = Algorithm<double>();
and then later:
auto results = algorithms["chlorine"].data();
(You should of course peruse the linked documentation on the above types, since I am omitting some error handling for brevity.)
Algorithm chlorine , means that
You've instantiated an "Algorithm" object named "chlorine"
to make array of "Algorithm"
you code it like:
Algorithm<double> chemicalElements[Const_num];
and to pass through each one of its items you call the array's name + it's index like:
chemicalElements[0 or 1 or 2 or ... etc].data();
So it would be like
for (i = 0; i < Const_num i++)
{
chemicalElements[i].data();
}
In this statement
Algorithm<double> chlorine;
chlorine is not a string. It is an identificator that names an object of type Algorithm<double>.
This construction
Algorithm<double> chemicalElements[i].data();
has no syntaxical sense in C++ and the compiler shall issue an error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello I am doing project where I have different sorting algorithms (QuickSort, BubbleSort etc).
I measure time of each of them and at the end I need to make some comparison which one is the fastest, and so on.
bool testyBubblesort(){
long int before = GetTickCount();
a.BubbleSort_int();
long int after = GetTickCount();
double dif = double((after - before));
result &= testEqual(zoradane.vypis_pola(), a.vypis_pola(),dif, "Test sort array-int");
comparison(dif);
vypisVysledkuTestu(result, "Testy triedenia BubbleSortom");
return result;
}
This is my function, it tests whether arrays are sorted and measures time. The important part is comparison(dif); This should be the function that compares all sorts. Note that i use this function in other sorts too.
void comparison(double time){
vector<int> all_times;
all_times.push_back(time);
}
So i was thinking make vector array and then sort it is good idea but I dont know how I always get some error.
Can u help me ?
Thanks
You aren't comparing to anything because your vector only has one element.
You should replace "comparison" with just an insertion into a vector that is declared globally. Then, at the top-level (wherever calls testyBubblesort), and perform your comparisons there.
A more robust method would be to make a vector, where MyStruct is declared as a double and a string, so that you store {time, "Bubble Sort"} (allowing you to associate the runtime with the sorting algorithm used. Then at the top-level, just use the built-in sort function (you will have to use the version that accepts a function to define how to order MyStruct) on the vector and grab the first object from the vector. Then just print out the string.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am having trouble figuring out how i can store new object into a vector, and be able to pull that information out.
What i am trying to do is, storing different data from files in a series of objects, then going through these objects and pulling out the information.
I am looking for something like this:
vector<myClass> list;
while( i < nFiles)
{
myClass *temp = new myClass;
list.push_back(temp);
temp->setSomething();
i++;
}
I want to have a different object for every nFile cycle, so i am able to later go through each object and pull the information out from each object.
I've tried pushing the temp to a vector but its giving me nothing but errors.
Is what i'm trying to do programatically correct? I can't get my head around this. Any sort of help would be much appreciated. Thank you.
First a bit of vocabulary: You don't want to store classes in the array (actually, vector), you want to store objects. Objects are instances of classes.
Second, you've got the syntax of the while loop wrong. Look it up in a C++ book. Better use a for loop.
Third, always write MyClass the same way. Don't change lower-/upper case.
And finally, learn about the difference between pointer to objects and objects. The element type you specify when you declare the vector doesn't match the things you put into it.
the syntax is while (...) not (while ...) AND you cant say i=1 in the while loop parameters. What you wanna do is:
either :
int i = 1;
while (i < nFiles){
//Do something
}
OR
for (int i = 1; i < nFiles; i++){
//Do something
}
Your vector should either be a vector of pointers to myClass, i.e.,
vector<myClass *> list;
Or your temp shouldn't be a pointer, i.e.,
myClass temp;
The latter means the whole temp object is copied when you do list.push_back (byte by byte).