Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is the code that I have written
I am getting an error when trying to print out the vector values and I can not figure out why.
I passed the array to the function print(&v1).
Can someone help me figure out why this error is occurring and if there is a better alternative way to print out the vector elements in my function.
You correctly used -> in print1 instead of . (like in print) to operate on the pointer to the vector. This works because x->y is equivalent to (*x).y, meaning you correctly dereferenced the pointer to the vector before accessing it.
Except for []. Here you also have to dereference the pointer before using []. So:
cout << (*v)[x] << endl;
There is no abbreviation (also called "syntactic sugar") for (*x)[] like there is for (*x).y, so you must do it manually.
The error message is confusing because using [] on a pointer is valid - x[y] is equivalent to *(x+y), which means you are doing pointer arithmetics: You use v as if it was a (C-style) array of vectors, and you try to get the xth element from this array of vectors. Lucky for you, the compiler doesn't know how to << a Vector with cout - but if it could, the code would compile and do something you (probably) did not intend.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have the following set and list declarations:
set<mystruct> my_entries;
unordered_map<string, list<_Rb_tree_const_iterator<mystruct>>> mylist;
What I am trying to do is basically insert some specific nodes of the set to the list as well after inserting it into the set.
auto inserted = my_entries.insert(entry);
mylist[name].push_back(*inserted.first);
I get the following error:
error: no matching function for call to
'std::list<std::_Rb_tree_const_iterator<mystruct> >::push_back(const
mystruct&)’
mylist[name].push_back(*inserted.first);
note: no known conversion for argument 1 from 'const mylist’ to
'std::list<std::_Rb_tree_const_iterator<mylist> >::value_type&& {aka
std::_Rb_tree_const_iterator<mylist>&&}'
Any ideas whats gone wrong?
Thanks.
As the comments describe, you should not be attempting to use internal types from the standard library. You can store the iterator as follows:
set<mystruct> my_entries;
unordered_map<string, list<set<mystruct>::const_iterator>> mylist;
// ...
mylist[name].push_back(inserted.first);
Whenever storing iterators, it's important to understand the rules governing when such iterators can become invalid. In the case of std::set::insert you are guaranteed:
No iterators or references are invalidated.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a vector of the following data structure
struct Rule {
int m_id = -1;
std::wstring name;
double angle;
};
std::vector<Rule>& topPriorityRules;
and I am erasing the first element of the vector using
topPriorityRules.erase(topPriorityRules.begin());
Is there any other good alternative for removing elements from the front of a std::vecor?
Given
std::vector<Rule>& topPriorityRules;
The correct way to remove the first element of the referenced vector is
topPriorityRules.erase(topPriorityRules.begin());
which is exactly what you suggested.
Looks like i need to do iterator overloading.
There is no need to overload an iterator in order to erase first element of std::vector.
P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.
Three suggestions:
Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;
Use std::vector::erase() (see Caleth's comment below).
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 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).