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).
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 2 years ago.
Improve this question
In a technical interview, the guy asked me that "he wants to pre-allocate memory for a linked list just like we can do for array", so how would he do that?
I have never felt the need to, neither came across this thought! I mostly code in C++, and I answered something like "just like we use the new command in C++ for memory allocation, example int *p = new int[10] ,where I can allocate 40 bytes of memory, I'd do something same for my Linked List, like Node *p = new Node()[10] , where Node is my Linked List class name, which is like this:
class Node{
public:
int data;
Node *next;
};
".
Then he further followed it up with how would you go about implementing this and would it really save time, considering space is not an issue? I mainly fumbled my way through the answer and he moved on the next question.
But I'd really like to know now if I was correct and a small example of it's working/operation would really help. Thank you.
Interview questions are generally asked not to be answered directly, and it is expected that you narrow down the use-case and requirements.
he wants to pre-allocate memory for a linked list just like we can do for array
If that is actually the question, then the interviewer either intentionally asked it wrong or misleading. And array (std::array or c-style array) will not only allocate the memory for the types they store but also construct them (at least for non-primitives) so it is important to know if it is a general-purpose list or a specialist list for certain types. A std::vector, on the other hand, actually pre-allocates memory.
You generally want to minimize the number of individual memory allocations because those can be expensive.
I'd do something same for my Linked List, like Node *p = new Node()[10]
You don't want to do that because this would already construct the type managed by the list for each node. In the case of primitives, this won't be much of a problem, but would horribly fail for a general-purpose list like std::list.
Then he further followed it up with how would you go about implementing this and would it really save time, considering space is not an issue?
You would allocate a larger chunk of memory (similar to what std::vector does), and when an element is stored in the list, you will use placment new, to construct the node in the already pre-allocated space.
If space is not a problem and a list would pre-allocate space for, e.g. 100 elements, it would save 99 memory allocations per 100 stored objects. You surely need to add some cost for manually keeping track of which parts of the pre-allocated spaces are free and which one is not, but that is likely to be cheaper than allocating memory.
This is just a rough idea about pre-allocating memory for a list. But the question is missing too many pieces of information to answer it in a meaningful full way.
how would you go about implementing this
We sure can create nodes without actually storing data in it. We can use a constructor (of the linked list) to get it done.
class LinkedList {
public:
LinkedList(int n)
{
pRootNode = new Node();
Node* pTraveler = pRootNode;
for(int i = 0; i < n; i++)
{
pTraveler->next = new Node();
pTraveler = pTraveler->next;
}
}
I'd do something same for my Linked List, like Node *p = new Node()[10]
This will give you an array of nodes. You further need to process it so that the previous node contains the pointer to the next.
would it really save time
A linked list like this will improve insertions as we don't need to allocate new nodes (until a new node is needed) when inserting a new entry. But instantiation of the linked list will take a small time (comparatively) as we are allocating nodes in the constructor.
Linked lists are said to have O(1) insertions and deletions with a worst case of O(n) access/ lookup time. So in my opinion, pre-allocating will have little effect because you'll anyway spend an equal amount of time allocating nodes.
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 4 years ago.
Improve this question
EDIT: apparently I asked this question wrong. Before voting to close, please allow me to know what the question is missing. I promise you, this is not an unanswerable question. You can always come back and vote to close it later.
I'm currently working in C++, but I think this question applies to most compiled languages.
In my project, I have an array of values which are calculated individually, one at a time, as late as possible based off a single variable. These values are not all calculated at once, they are calculated if and only if they need to be. As is normally the case when using "dirty", the objective is to label certain things as being in need of update, without updating it preemptively. These values are cycled through over and over, so I'd like to cache the computation if possible. Whenever the single variable changes, all the values should be marked dirty so the cycle knows to recalculate before storing and moving on.
I can think of a few ways of achieving this, but I'm not sure what is most efficient:
Have two arrays, one of booleans and one of values. Mark all booleans to false if dirty, and true when clean.
Have a clean start point. Consider everything dirty until passing that cycle point again. Has the drawback of not allowing skipping of cycle entries.
Brand new array. Just create a new array, if any of the items are unset, set them. This one seems like it would have tons of problems, but it's a thought.
Perhaps use some built in class meant for this stuff?
The above are just the first things that came to mind for me, but I'm kind of new to c++ and would like to have some idea of normal or special solutions to marking an array dirty.
How can I dirty an array efficiently?
In order to show an example of code, I will show js which I'm more used to:
const numbers = [];
const clean = [];
let length = 1000;
let variable;
const setVariable(num) => {
variable = num;
for (let i = 0; i < length; i++) { clean[i] = false; }
}
setVariable(42);
let pos = 0;
while (true) {
if (clean[pos] == false) {
clean[pos] = true;
numbers[pos] = someIntensiveMath(pos, variable);
}
doSomethingWithNumbers(numbers[pos]);
pos++;
if (pos >= length) pos = 0;
// wait a bit;
}
in js you could also do
const setVariable(num) => {
variable = num;
numbers = [];
}
const isDirt = numbers[pos] === undefined;
With js the latter would probably be faster due to the native implementation of the script, but I don't think that's the case with compiled languages. I think you guys do things differently.
I've found elsewhere that the typical way to label entries of an array "dirty" is by having a parallel array of booleans.
#stark mentioned in the comments the idea of using a map, and speed comparisons of the two appear to be pretty decent, but it was advised in the following answer to use an array for indexed items.
performance of array vs. map
Whether or not changes in modern coding have led to a new defacto way of labeling items or parts of an array (or linear collection of items) as "dirty" is unknown. But in the very least, as an answer, the most straight forward nooby way is to have a parallel array of booleans.
Further, depending on the way you are iterating through the "array" it may make sense to use vector or map. In the case of either of those, the form of dirtying would probably be best done by clearing the map or removing vector entries(??).
So, to give my best answer, it would seem one should first find the storage method that best fits their needs, and then use whichever method is most normal for that.
For arrays, as this question was specified towards, parallel arrays appears to be the answer.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Ive got an exercise due to tommorow and Ive got completely no idea how to do it, even though I know how to add to list, delete an element from list ( last or first ), or display a list, maybe its because I only know how to do it with one variable in struct.
sorry if my translation is not the best but Im translating the exercise from polish.
1.We have a structure
struct point {
double x, y;
};
Create a function that creats lists of consisting of n points
Then after it
Using the list created in previous exercise, create a function that prints on the screen coordinates of points lying inside the given circle. Pointer for the beginning of the list and defining values transfer as function parameters.
I was trying to do it alone but as of now Ive got completely no idea how to approach this. I think as for the first one, I should create a list, head and tail and next,then constructor that sets head and tail to NULL, then function that adds elements to list, then in main ask user for the 'n' value and create for loop with that function.
After that, Ive got completely no idea what to do next. I may have been wrong even until now.
Sorry if I waste your time reading this, I just hope someone can help me and explain me what to do.
Sorry if its also not the place to ask for that kind of help, Im kinda new to all of this.
You should separate the concept of data from the links.
struct Node
{
Point data;
Node * p_previous;
Node * p_next;
};
Later on you may want to make the list into a template so that you can pass any type for the data field.
To get the coordinates from a Node:
Point coordinate = p_node->data;
double x_ordinate = coordinate.x;
double y_ordinate = coordinate.y;
Off-topic: screen coordinates should be integers, not floating point. Usually, pixels are hole element, I haven't heard of real partial pixels.
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.
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.