Why do we use pointer in C++? [duplicate] - c++

This question already has answers here:
Why use pointers? [closed]
(17 answers)
Closed 4 years ago.
As someone new to programing (C++) , I came across pointer which gave me a headache doing it as I never seen the point of using it. I tried to look at other answer on stack overflow but it was a bit confusing.It would be great if someone could explain why we use pointers and in a way to make it easier to understand.

One reason is so that we can directly manipulate the content the pointer address is holding.

There are a number of uses for pointers. They represent a way for code to manipulate memory directly primarily, but can also be used for things like arrays. In modern C and C++, you would usually use pointers for accessing hardware to control it through custom structs, for example.
However, for some other complex and for recursive types, pointers are still the easiest and only way to model them. A linked list, for example, could have any number of items, but there's no really good way to refer to the next (or previous) item in C or C++ without using a pointer to it.
Allocating larger data structures will also usually require a pointer to refer to it as well, since these large allocations won't fit on the stack.

Related

Vectors vs Array in C++ [duplicate]

This question already has answers here:
Using arrays or std::vectors in C++, what's the performance gap?
(21 answers)
Closed 3 years ago.
I am working on a Project in which the I am using vectors since the size of array is unknown initially. Does using arrays instead of vectors reduce the run time of code?If Yes, Then How can i initialize/declare the array of unknown size i.e. Size of array is variable(based on input)? "OR" Is it better to use vectors only?
Note :- I want to know Which better reduces the Execution time of Program.
In programming as in life there is no free meal... Keep that in mind all the time. If you want nice and convenient features you have to pay a price.
std::vector will add some complexity to your code you don't see. Adding items to your std::vector does more, then just writing a value. It may allocate new memory and copy the old values to it. And several more things you won't really see.
Switching to std::array won't give you the boost you might looking for. It is a bit simpler then std::vector. It is the way to got, when you are looking for an supplement of an plain c array. But still, it will add complexity too.
So my advice is and you will find similar once in good books. Try to optimize your code on algorithm base and not on the implementation. There is much more potential in possible flawed algorithms or there may be much better once. The implementation won't give you the ground braking boost.

How to handle fast insert-erase operations in this c++ data structure? [closed]

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 7 years ago.
Improve this question
Fact: my code is in c++
Question:
I have a list of unsigned long long, which I use as reppresentation for some objects and the position in the list is the ID for the object.
Each unsigned long long is a sort of lis that mark if an object has the component j, so let say that I have
OBJ=1 | (1<<3)
that means that the object has the components 1 and 3.
I want to be fast when I insert, erease and when I retrieve objects from the list.
The retrieve usually is performed by components so I will look for objects with the same components.
I was using std::vector but as soon I started thinking about performance it seems to me not to be the best choice, since each time I have to delete an object from the list it will relocate all the object ( erease can be really frequent ) plus as soon as the underlying array is full vector will create a new bigger array and will copy all the elements on it.
I was thinking to have an "efficientArray" wich is a simple array but each time an element is removed I will "mark" the position as free an I will store that position inside a list of available positions, and anytime I have to add a new element I will store it in the first available position.
In this way all the elements will be stored in contiguos area, as using vector, but I avoid the "erease" problem.
In this way I'm not avoiding the "resize" problem (maybe I can't) plus the objects with the same components will not be closer (maybe).
Are there other ideas/structures wich I can use in order to have better performance?
Am I wrong when I say that I want "similar" object to be closer?
Thanks!
EDIT
Sorry maybe the title and the question was not write in a good way. I know vector is efficient and I don't want to write a better vector. Since I'm learning I would like to understand if vector IN THIS CASE is good or bad and why, if I'm wrong and if what I was thinking is bad and why, if there are better solutions and data structures (tree? map?), if yes why. I asked even if it is convinient to keep "similar" objects closer and if that MAYBE can influence things like branch prediction or something else (no answer about that) or if it is just nonsence. I just want to learn, even "wrong" answer can be useful for me and for others to learn something, but seems it was a bad idea like I asked *"my compiler works even if I write char ** which is wrong"* and I didn't understand why.
I recommend using either std::set or std::map. You want to know if an item exists in a container and both std::set and std::map have good performance for searches and "lookups".
You could use std::bitset and assign each object an ID that is a power of 2.
In any case, you need to profile. Profile your code without changes. Profile your code using different data structures. Choose the data structure with the best performance.
Some timing for different structures can be read here.
The problem with lists are that your always hunting after the link, where each link potentially is a cache miss (and maybe a TLB miss in addition).
The vector on the other hand will enjoy few cache misses and the hardware prefetcher will work optimally for this data structure.
If the data was much larger the results are not so clearcut.

which is faster, a single array of object, or multiple array of data attributes? [closed]

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 8 years ago.
Improve this question
Here is a simplified example. Note that I chose simple types, but in an application I might have many more attribute
struct object
{
float a, b;
int c;
};
vector<object> objects;
or
vector<float> a, b;
vector<int> c;
In a game application where you access each attribute at least once, performance might vary. The game loop will run through the whole index, no matter what.
I know the first example is much more convenient (much easier to organize code with one single struct) and that it might depend on what the application is really doing, but isn't the second example more cache friendly ?
I know it's not the proper way to make an application at first with the Knuth premature optimization thing, but I'd just like to know... I've read this in a gamedev slide once and I'm wonder if it's true or not, and why.
"It depends!"
Really, there is not only one best data distribution for all the problems, otherwise the compilers and the programming languages would be built around it.
It depends on the algorithm where most of the time is spend in computations.
So, array-of-structs is more cache-friendly/page-miss-friendly; struct-of-arrays is better suited for SSE/AVX SIMD optimization, have better memory channel utilization (that's evident with CUDA for example).
My preferred approach is to start using array-of-objects, and using interfaces only (getter/setters). Than trying to optimize making the objects be an interface to the underlying arrays, in case I have the evidence that I am missing some important optimization by profiling.
and remember... "early optimization is evil of all programming" ;)
In my opinion it is better to have only one vector of class objects than three vectors of its data members. In the last case all operations are duplicated three times including memory allocation/deallocation.
Mpreover in the last case there is a logical inconsistence because these three vectors are not connected with objects. You will be unable to find an object that contains these attributes.
One vector of objects will probably perform better due to data locality and being more cache friendly, but it's always better to be sure by actually profiling your use scenario, which especially depends on your access pattern.
If a, b, c are related and will likely be read together then the struct is more cache friendly.
But packing that puts all the same datatypes together sequentially in memory has the advantage of possibly been (auto) vectorizable.
Anyway some related questions to delve deeper into the matter are:
Which is most cache friendly?
Structure of arrays and array of structures - performance difference
Layout in memory of a struct. struct of arrays and array of structs in C/C++
Structure of Arrays vs Array of Structures in cuda

Strategy of passing and returning values (any kind, including array or more complex data structure)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I used to use PHP, and I like the way PHP passes and returns values, very straightforward.
Now I've turned to C++ to gain more performance, but find it difficult to pass and return 2d array, not to mention some more complex data structures.
I once thought JSON may be a choice, but this way you have to encode and decode every time, not practical.
Currently I am using pointers, but it's not very convenient.
Then I tried STL vector, still not satisfied,the STL vector is a little safer and comfortable to use, but still, you have to manually iterate the array, what I want is a more flexible strategy to deal with these kind of tasks
I tried to use class/struct to hold the data, then pass and return, but I have to define a new struct whenever to pass a different kind of data structures.
So, what's the best choice for data exchanging between functions?
Professionals, any suggestions?
edit:
As an example:
string function(string data){
//do something
return result;
}
If this result is like:
{
"key1"=>{"key11"=>"value1"},
"key2"=>{"key21"=>"value2"},
"key3"=>{"key31"=>"value3","key32"=>"value32"}
}
it would be too complicated to pass this with pointers, wouldn't it?
With php, you can use several foreach statements to process the nest array easily.
edit2:
To put it simply, how to exchange a nested array with unknown length and dimension?
edit3:
I am trying to find the cpp way of dealing with common programming tasks. And exchange data between functions is very important.
In php, I can easily process the nested array with several foreach and return array easily.
But with cpp
I have to return the result array pointer or directly operate the referred vector
i need to pass the array length to functions
when data structure is complicated, get values from the array is difficult.
The whole "Any kind" thing is really not C++. The language is not intended to support this. Each individual function can only return one kind of thing. You can use something like boost::variant, which can be one of a number of types, or boost::any, which can be any type but it's not very convenient to use. Of course, if you turned to C++ for performance, this isn't going to help that matter- the knowledge of the kinds in advance is one of the key factors improving C++ performance.
So I would suggest that instead, you simply learn to deal with strong static typing.
map<string, map<string, string>> magic;
magic["key1"]["key11"] = "value1";
magic["key2"]["key21"] = "value2";
magic["key3"]["key31"] = "value3";
magic["key3"]["key32"] = "value32";

C++ use array pointer vs vector? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using arrays or std::vectors in C++, what's the performance gap?
I just wanna know which of them are the faster and use less resources? I think that vector is more reliable and secure but a pointer to an array is faster. I want to re-size the array (add new elements, so increment it by 1 or remove elements from it). A vector has its functions for that while a pointer needs one created by me.
I don't know which one to choose. What do you advise me? Thanks!
According to Bjarne Stroustrup, you should use vector over Array unless you have a really good reason to use an array.
The c++ standard libaries have been optimized to be as fast as possible all the while providing necessary functions so that you do not have to implement them. Save yourself the time and worry and just use a vector.
If there are any discrepancies on speed they will be negiligble in the big picture :)