I would like to compare vector with an array. Elements in vector and in array are in different order, unsorted and can duplicated. E.g.
Below are the same:
vector<int> lvector = {5,7,3,1,2,7};
int larray[6] = {3,5,1,7,2,7}
Below, not the same:
vector<int> lvector = {5,7,3,1,2,7,5};
int larray[7] = {3,5,1,7,2,7,3}
And something like this is also not the same:
vector<int> lvector = {1,1,1,1,2,2};
int larray[6] = {1,1,1,1,1,2}
Now I need to check if vector and array have got the same elements. I can't modify the vector and the array, but I can create a new container and copy the element from vector and array to this new container and then copare them. I am asking about this, because I would like to do this in en efficient way. Thanks.
Vector is a sequential container to store elements and not index based. Array stores a fixed-size sequential collection of elements of the same type and it is index based. Vector is dynamic in nature so, size increases with insertion of elements. As array is fixed size, once initialized can't be resized.
Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.
A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.
A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.
That's a variant of what proposed by soon:
#include <iostream>
#include <unordered_set>
#include <vector>
int main()
{
std::vector<int> v{5, 7, 3, 1, 2, 7};
int arr[] = {3, 5, 1, 7, 2, 7};
std::vector<int> mv(std::begin(v), std::end(v));
std::vector<int> ma(std::begin(arr), std::end(arr));
std::sort(mv.begin(), mv.end()) ;
std::sort(ma.begin(), ma.end()) ;
std::cout << "Are equal? " << (mv == ma) << std::endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With