One way swap for vectors, is it possible? [closed] - c++

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 6 years ago.
Improve this question
In C++98, this is what I want to do (this does not work as _M_start, etc are private members):
void vectormove(std::vector<int>& a, std::vector<int>& b)
{
a._M_impl._M_start = b._M_impl._M_start;
a._M_impl._M_finish = b._M_impl._M_finish;
a._M_impl._M_end_of_storage = b._M_impl._M_end_of_storage;
}
This is how I want to call
//vectors are predefined already
std::vector<int> a;
std::vector<int> b(10000000,20);
//in later part of code
//a=b; //expensive copy
//std::swap(a,b); //inexpensive swap
vectormove(a,b); //i need an inexpensive one way swap instead
I may have butchered terminology by using copy, move and swap loosely, but I dont have a better grasp on this subject. I hope I was able to convey my intent.

It looks like you just want a to refer to b's internals. The way to do that is just:
std::vector<int>& a = b;
if you want a to take over b's internals, that's:
std::vector<int> a = std::move(b);
which in C++03 could be implemented as a swap with an empty vector:
std::vector<int> a;
using std::swap;
swap(a, b);

If your question is how to write a compilable implementation of your vectormove(), it's like this:
// NOT USEFUL CODE
void vectormove(std::vector<int>& a, std::vector<int>& b)
{
memcpy(&b, &a, sizeof(std::vector<int>));
}
But this is not useful, because once you've done this you are on the path to undefined behavior. Perhaps double-free, perhaps use-after-free, etc.
It seems like you would be best served either by the regular a.swap(b) or by storing a as type int* instead, like this:
std::vector<int> b(10000000,20);
std::pair<int*, int*> a(&b[0], &b[b.size()]);
Now you have an a which can be passed around cheaply and refers to the original vector. Just make sure you don't invalidate a by modifying b afterwards.

Related

Is there a reason why std::priority_queue as MinHeap requires greater than comparer; MaxHeap, less than comparer? [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 2 years ago.
Improve this question
When I use std::priority_queue as a Min Heap for example, I'd need to do something like this:
struct MyType{
...
int data;
};
auto greaterThanCmp = [](const MyType& a, const MyType& b){ return a > b; };
std::priority_queue<MyType, std::vector<MyType>, greaterThanCmp> minHeap;
My question is: is there an advantage to providing the greaterThanCmp for a Min Heap or would a less than comparer works just as well, had the committee/implementer gone that route.
Or in other words, why did the standard choose one over the other?
I have tried implementing my MinHeap class with a lessThanCmp just for the heck of it. I tested my code, it works fine.
Thank you very much for your response in advance!
Once you have a greater object, you can easily make a less object out of it:
less ::operator() (a, b) { return greater (b, a) }. So the less requirement is not limiting.

I have used a vector to create a list of class objects. How can I call the constructor with parameters when I initialize the vector? [closed]

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
I have a class Random. The constructor has a parameter "int range" if I say
class Random
{
private:
int r;
public:
Random(int range)
{
r = range
}
}
I want to create a vector of objects of class Random. How do i pass the range parameter in that case
vector<Random> v;
Where does the parameter go? Bit confused.
There's no great way to do what you want.
Since Random is cheap to copy, you can do this:
vector<Random> v{Random(1), Random(2), Random(3)};
but if it wasn't cheap to copy (or not copyable at all), then you would do this instead:
vector<Random> v;
v.reserve(3);
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);

Copy structure to a different structure [closed]

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
I was wondering if there was an elegant way to copy a structure to a different structure, where the second structure is essentially the same as the original one, except without the last field(s).
For example,
struct A {
int a;
int b;
int c;
};
struct B {
int a;
};
struct A v1;
struct B v2;
Would,
memcpy(&v2, &v1, sizeof(v2));
Achieve the functionality I wish?
Where v2 has the "a" value that was originally found in v1?
Thank you
If instead of copying all bytes in A, you only copy the number of bytes that B expects, you will achieve your desired result:
memcpy(&v2, &v1, sizeof(v2)); // remember that the first argument is the destination
However, this is not good coding style. With this minimal code example, it is hard to tell, but you would probably want A to inherit from B so that you can convert the two without having to physically copy memory.
Otherwise, this would be easier and cleaner:
b2.a = v1.a;

Performance Lack in my C++ Code [closed]

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
At the moment i'm trying to optimize my c++ code to get better performance, because I have a strong java/c# background.
I've tested simple examples like getter/setter between classes and realized using them with references like this:
vector<string>& MyClass::getNum()
{
return num;
}
void MyClass::setNum(vector<string> &num)
{
this->num = num;
}
(let say 15+ Strings are in the Vector)
is faster 2x faster than without. (no difference when using simple/small parameter, but huge diff. when using Vectors etc.)
I also tried the same example in Java, but somehow my Java code is still faster than in C++.
Someone can help me?
In java, everything is pointer, so when you do this in java:
void function (ArrayList <Integer> myList);
It's almost equivalent in C++ to:
void function (std::vector <int> & myList);
void function (std::vector <int> * myList);
This answer your question on why Java is faster when not using reference in C++, because references are faster in most cases. Then, why does it improve performance?
Well, imagine you have a vector of int, if you pass it to a function without reference, you have to make a copy of the object (call the copy constructor), which take (in general) a huge amount of time since you have to allocate a new array, etc. Another example with a struct:
struct X {
int a[100] ;
int b[100] ;
} ;
This struct take something like 2 * 100 * 4 = 800 bytes on a modern machine (may vary of course), so if you pass it to a function like that:
void function (X x) ;
When you call the function, you need to make a copy, so a copy of 800 bytes, if you do:
void function (X const& x) ;
You only pass a reference to the object, i.e. something pointing to the object, which will take (on a x64 architecture), 8 bytes.
this->num = num; : this line copies the vector you passed by reference. If your goal is to give the vector to MyClass and then forget about it, consider passing it by rvalue reference and moving it.

Using algorithms with integer ranges [closed]

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
Is it any nice way to call STL algorithms on an integer range?
For example I have a collection "col" with access to it's elements only via GetElement(int) method. Is it possible to use find_if function to find something in that collection?
I would like to call something like that:
auto element =
find_if(0, col.Size(), [&col] (int i) {
return predicate(col.GetElement(i));
});
I'm looking for an STL or any other library solution.
With standard C++? Yes, if you write a custom element iterator. Then, your code is easily simplified to:
auto element = find_if(col.begin(), col.end(), predicate);
It's not possible to do something closer to what you had in mind with the standard library, but it is with Boost, which is an incredible C++ library that you really ought to have. Boost has a counting iterator: http://www.boost.org/doc/libs/1_55_0/libs/iterator/doc/counting_iterator.html
How would you fill up a vector with the numbers zero through one hundred using std::copy()? The only iterator operation missing from builtin integer types is an operator*() that returns the current value of the integer. The counting iterator adaptor adds this crucial piece of functionality to whatever type it wraps. One can use the counting iterator adaptor not only with integer types, but with any incrementable type.
#include <boost\counting_iterator.hpp> //or something, not sure of exact header
int main() {
boost::counting_iterator<int> first(0);
boost::counting_iterator<int> last(col.Size());
auto element = find_if(first, last, [&col](int i) {return predicate(col.GetElement(i);});
}
Additionally, boost also has ranges. They don't really help you much in this exact situation, but it's related, so I'll mention it:
#include <boost\range\irange.hpp>
int main() {
for (int index: boost::range::irange<int>(0, col.Size()) )
{
std::cout << element; //counts from 0 to col.Size()
}
}