Is there an std/boost algorithm to verify that all vectors within a vector have the same sizes? And by extension, that a property of all elements is the same?
In the below examples, I use the hypothetical std::all_equal
that I am looking for:
typedef std::vector<int> Line;
std::vector<Line> lines;
lines.push(Line(10));
lines.push(Line(11));
auto equalLengths = std::all_equal(lines.begin(), lines.end(),
[](const Line& x){ return x.size(); });
(And by extension:
std::vector<MyClass> vec;
auto equal = std::all_equal(std::begin(vec), std::end(vec),
[](const MyClass& x) { return x.property(); });
)
Method 2: Using length() and unique() function By using unique function if all the elements are the same then the length is 1 so by this way if the length is 1, we can say all elements in a vector are equal.
C++ Vector Library - operator== Function The C++ function std::vector::operator== tests whether two vectors are equal or not. Operator == first checks the size of both container, if sizes are same then it compares elements sequentially and comparison stops at first mismatch.
1) std::vector is a sequence container that encapsulates dynamic size arrays. 2) std::pmr::vector is an alias template that uses a polymorphic allocator. The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements.
Vectors are similar to arrays but their size can grow dynamically. Vectors can expand or shrink dynamically during the insertion and deletion of elements. It stores the elements in contiguous memory locations. Hence the size of the vector changes during the execution of the program according to the requirements.
How about
#include <algorithm> // for std::all_of
auto const required_size = lines.front().size();
std::all_of(begin(lines), end(lines),
[required_size](const Line& x){ return x.size() == required_size; });
Won't work for empty lists, unfortunately and you have to get the required size into the predicate somehow.
I like @ComicSansMS's answer, but if you want a slightly less-clear approach that also works on empty vectors, you could use std::adjacent_find
with a custom predicate:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<std::vector<int>> vv{{3, 1}, {4, 1}, {5, 9}};
bool all_same_size = std::adjacent_find(
vv.cbegin(),
vv.cend(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a.size() != b.size(); // Look for two adjacent elements that
// have different sizes
}) == vv.cend();
std::cout << "all same size: " << all_same_size << '\n';
}
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