How to iterate over a vector? - c++

I need to iterate over a vector strictly in the order the elements were pushed back into it. For my particular case it's better use iterators than iterating though the for-each loop as follows:
std::vector<int> vector;
for(int i = 0; i < vector.size(); i++)
//not good, but works
My question is if it's realiably to iterate over the vector through iterator like that:
std::vector<int> v;
for(typename std::vector<int>::iterator i = v.iterator(); i != v.end(); i++)
//good, but I'm not strictly sure about the iterating order.
So, can I use iterators safely with my requirements? Is it standartized?

If you have access to C++11 you can use range-based for loops
for (auto i : v)
Otherwise you should use begin() and end()
for (std::vector<int>::iterator i = v.begin(); i != v.end(); ++i)
You can also use std::begin and std::end (these require C++11 as well)
for (std::vector<int>::iterator i = std::begin(v); i != std::end(v); ++i)
begin will return an iterator to the first element in your vector. end will return an iterator to one element past the end of your vector. So the order in which you get the elements iterating this way is both safe and defined.

if you want to use iterators, your approach is fine
for(auto it = v.begin(); it != v.end(); ++it)
the iteration order depends in fact on the container and the actual used iterator.
for a std::vector this code iterates always over the elements in their order in the vector. if you'd use v.rbegin() or v.rend() instead, the order would be reversed.
for another container the order is different, for a std::set the very same code would iterate the elements in ascending order of their sorting criterion.

This is an overly complex solution.
First, we start with an index type. It can store anything that models iterator and/or integral (basically, supports + scalar, delta to scalar, copy, destruction and equality):
template<class T,
class Category=std::random_access_iterator_tag,
class Delta=decltype(std::declval<T>()-std::declval<T>())
>
struct index:
std::iterator<Category, T, Delta, T*, T>
{
T t;
T operator*()const{ return t; }
index& operator++(){++t; return *this;}
index operator++(int){index tmp = *this; ++t; return tmp;}
index& operator--(){--t; return *this;}
index operator--(int){index tmp = *this; --t; return tmp;}
T operator[](size_t i)const{return t+i;}
friend bool operator<(index const& lhs, index const& rhs) {
return rhs.t-lhs.t>0;
}
friend bool operator>(index const& lhs, index const& rhs) {
return rhs<lhs;
}
friend bool operator<=(index const& lhs, index const& rhs) {
return !(lhs>rhs);
}
friend bool operator>=(index const& lhs, index const& rhs) {
return !(lhs<rhs);
}
friend bool operator==(index const& lhs, index const& rhs) {
return lhs.t==rhs.t;
}
friend bool operator!=(index const& lhs, index const& rhs) {
return lhs.t!=rhs.t;
}
friend Delta operator-(index const& lhs, index const& rhs) {
return lhs.t-rhs.t;
}
friend index& operator+=(index& lhs, Delta rhs) {
lhs.t+=rhs;
return lhs;
}
friend index& operator-=(index& lhs, Delta rhs) {
lhs.t-=rhs;
return lhs;
}
friend index operator+(index idx, Delta scalar) {
idx+=scalar;
return idx;
}
friend index operator+(Delta scalar, index idx) {
idx+=scalar;
return idx;
}
friend index operator-(index idx, Delta scalar) {
idx-=scalar;
return idx;
}
};
most of which isn't needed, but I wanted to be complete. Note that this claims to be a random access iterator by default, but it lies, as its reference type is not a reference. I consider the lie worthwhile.
With index we can both create an iterator-over-integrals, and an iterator-over-iterators. Here is how we create an iterator-over-iterators:
using it_category=typename std::iterator_traits<It>::iterator_category;
template<class It, class Category=it_category<It>>
index<It, Category> meta_iterator( It it ) { return {it}; }
Next, we want to be able to take some iterators, and iterate over the range. This means we want a range type:
template<class It>
struct range {
It b, e;
range(It s, It f):b(s),e(f){}
range():b(),e(){}
It begin()const{return b;}
It end()const{return e;}
bool empty()const{return begin()==end();}
template<class R>
range(R&& r):range(std::begin(r),std::end(r)){}
};
This is a trait that takes an iterable range (not only a range, but also any container) and gets the iterator type out. Note that a superior ADL-enabled one would be a good idea:
template<class R>
using iterator=decltype(std::begin(std::declval<R&>()));
Random helpers:
template<class R,class It=iterator<R>>
range<It> make_range(R&&r){ return {std::forward<R>(r)}; }
template<class It
range<It> make_range(It s, It f){return {s,f};}
Here is a useful helper that solves our problem:
template<class R>
range<meta_iterator<iterator<R>> iterators_into( R&& r ){
return {meta_iterator(std::begin(r)), meta_iterator(std::end(r))};
}
and we are done:
std::vector<int> v;
for(auto it: iterators_into(v)) {
}
returns an iterator for each element of v.
For industrial quality, you'd want to ADL-improve things. Also, dealing with rvalue storage of input ranges lets you chain range-adaptors better in for(:) loops.

Related

Binary search a list of integers that are encoded with arbitary number of bytes

A list of sorted integers are encoded in a uint8_t vector.
The amount of bytes to encode these integers is arbitrary.
For example, if we use 3 bytes to encode each integer, then the first integer is encoded in the first 3 bytes, the second integer is encoded in the second 3 bytes and so on.
I would like to binary search an integer from this uint8_t vector.
My attempt so far:
std::bsearch seems what I want. In which, I can specify the size of each element in the array in bytes. However, to implement the comparator function, I need access to a variable that stores the size of each element in bytes. std::bsearch is a C function, so the compiler does not allow me to access a class member variable that stores the size of each element in bytes. Global variable works, but it is ugly to store it as a global variable...
std::binary_search takes an iterator.
I guess I need iterator to skip certain number of bytes.
I am not sure how to make this happen though.
The first thing that comes to mind for this is to define a custom iterator that wraps another iterator and operates on a sequence of N bytes at a time. This would allow the wrapped iterator to be easily used in std::binary_search without being stuck rewriting it.
Basically, the utility would have the following:
The iterator should be random access,
Each increment (operator++) operates on N bytes at a time,
Each decrement (operator--) operates on N bytes at a time,
Each addition (operator+) advances by N * i bytes at a time,
Each subtraction (operator-) reports a distance of d / N (to account for the N bytes, and
The value type of the iterator will be some large enough int to easily hold the arbitrary value lengths (e.g. std::int64_t or something)
Something like:
// Iterator that skips N entries over a byte type
template <std::size_t N, typename Iterator>
class byte_iterator
{
public:
// Ensure that the underlying type is 'char' (or some other 'byte' type, like std::byte)
static_assert(std::is_same<typename Iterator::value_type, unsigned char>::value, "");
using value_type = std::uint64_t;
using reference = std::uint64_t;
using pointer = value_type*;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using iterator_category = std::random_access_iterator_tag;
byte_iterator() = default;
explicit byte_iterator(Iterator underlying)
: m_it{underlying}
{
}
byte_iterator(const byte_iterator&) = default;
byte_iterator& operator=(const byte_iterator&) = default;
byte_iterator& operator++() {
std::advance(m_it, N);
return (*this);
}
byte_iterator operator++(int) {
auto copy = (*this);
std::advance(m_it, N);
return copy;
}
byte_iterator& operator--() {
std::advance(m_it, -static_cast<std::ptrdiff_t>(N));
return (*this);
}
byte_iterator operator--(int) {
auto copy = (*this);
std::advance(m_it, -static_cast<std::ptrdiff_t>(N));
return copy;
}
byte_iterator& operator+=(std::ptrdiff_t n) {
std::advance(m_it, static_cast<std::ptrdiff_t>(N) * n);
return (*this);
}
byte_iterator& operator-=(std::ptrdiff_t n) {
std::advance(m_it, -static_cast<std::ptrdiff_t>(N) * n);
return (*this);
}
value_type operator*() const {
// build your int here
// The question doesn't indicate endianness, so this is up to you
// this can just be a bunch of shifts / masks to create the int
}
bool operator==(const byte_iterator& other) const {
return m_it == other.m_it;
}
bool operator!=(const byte_iterator& other) const {
return m_it != other.m_it;
}
Iterator underlying() const { return m_it; }
private:
Iterator m_it;
};
template <typename N, typename Iter>
std::ptrdiff_t operator-(const byte_iterator<N, Iter>& lhs, const byte_iterator<N, Iter>& rhs) {
return (lhs.underlying() - rhs.underlying()) / 3;
}
template <typename N, typename Iter>
byte_iterator<N, Iter> operator+(const byte_iterator<N, Iter>& lhs, std::ptrdiff_t rhs) {
return byte_iterator{lhs} += rhs;
};
template <typename N, typename Iter>
byte_iterator<N, Iter> operator-(const byte_iterator<N, Iter>& lhs, std::ptrdiff_t rhs) {
return byte_iterator{lhs} -= rhs;
};
// other necessary operators...
template <std::size_t N, typename Iterator>
byte_iterator<N, std::decay_t<Iterator>> make_byte_iterator(Iterator it) {
return byte_iterator<n, std::decay_t<Iterator>>{it};
}
Note: N doesn't have to be fixed at compile time as a template argument, it could also be done at runtime as a constructor argument. Similarly Iterator doesn't have to be a templated type; I simply use this as an example so that it may work with any underlying iterator. Realistically you could simply make this a char* or something so that it only works on contiguous byte arrays.
All that needs to be implemented is the reconstruction of the int for the purposes of comparison, which can be done from a series of 8-bit left shifts and masks depending on the endianness.
With an iterator wrapper like this, we can use std::lower_bound for a simple binary search to find the iterator:
// Assuming 3-byte numbers:
const auto value = 42;
auto byte_numbers = std::vector<unsigned char>{...};
// ensure we have an increment of 3 bytes, otherwise the
// iterators will break
assert(byte_numbers.size() % 3 == 0);
auto result = std::lower_bound(
make_byte_iterator<3>(byte_numbers.begin()),
make_byte_iterator<3>(byte_numbers.end()),
value
);
The result iterator will by a byte_iterator that contains an underlying iterator to the start of the N-byte number you need to retrieve. If you need the underlying iterator, you can just call result.underlying()
Alternatively, this can be used in std::binary_search to detect existence of the element in general without finding the underlying iterator (as mentioned in the question).
Note: The above code is untested -- it may have a typo or two, but the process should work as described.
Edit: Also be aware that this will only work correctly if the underlying iterator range is a multiple of N! If it were not, then you will report the incorrect range, which will also cause advancing the iterator to potentially move past the end iterator, which would be undefined behavior. It's important that you check the boundaries first before wrapping an iterator in this way.
Edit 2: If the N-byte integers can exceed a large value like int64_t, but follow a simple heuristic, you can also make the value_type of the iterator be a custom arbitrary_int type that has a well-defined comparison operator. For example:
template <std::size_t N>
class arbitrary_int {
public:
arbitrary_int(const unsigned char* integer)
: m_int{integer}
{
}
// assuming we can lexicographically compare all bytes
bool operator==(const arbitrary_int<N>& rhs) const {
return std::equal(m_int, m_int + N, rhs.m_int, rhs.m_int + N);
}
bool operator!=(const arbitrary_int<N>& rhs) const {
return !(*this == rhs);
}
bool operator<(const arbitrary_int<N>& rhs) const {
return std::lexicographical_compare(m_int, m_int + N, rhs.m_int, rhs.m_int + N);
}
bool operator>(const arbitrary_int<N>& rhs) const {
return rhs < *this;
}
bool operator<=(const arbitrary_int<N>& rhs) const {
return !(rhs < *this);
}
bool operator>=(const arbitrary_int<N>& rhs) const {
return !(*this < *rhs);
}
private:
const unsigned char* m_int;
};
In this case, byte_iterator<N,Iterator>::operator*() would now return
return arbitrary_int<N>{m_it.operator->()}
Or if you're using c++20,
return std::to_address(m_it);
The object you want to compare is stored in several elements in the vector. So std::binary_search cannot be directly applied on the vector.
One approach is applying std::bsearch on the raw data of vector (vecter::data()) since std::bsearch can group the data by specified size. So it will seem like:
std::bsearch((void*)key_array,(void*)data_vector.data(),data_vector.size()/3,3*sizeof(uint8_t),
[](const void *a, const void *b){return decode((uint8_t*)a)-decode((uint8_t*)b)});

Elegant way to provide flatting iterator for vector of vectors

I have an adapter, whose goal is to provide forward iterator for pair values pair<FeatureVector, Label>. However in my internal representation I store data as vector<pair<vector<strings>, Label>>.
So during iterations, I need to flatten it and convert every single string, which is short sentence like "oil drops massively today", to FeatureVector
In raw variant I have something like:
{
{"Oil drops massively","OPEC surge oil produciton","Brent price goes up" -> "OIL_LABEL"},
{"France consume more vine", "vine production in Italy drops" -> "VINE_LABEL"}
}
and I need to convert it to:
{
vectorize("Oil drops massively") -> "OIL_LABEL",
vectorize("OPEC surge oil produciton") -> "OIL_LABEL", ... ,
vectorize("vine production in Italy drops") -> "VINE_LABEL"
}
vectorize() -> it's a conversion from sentence to sparse vector like this "Oil drops on NYSE" -> {0,1,0..0,1,0..0,1}
The simpliest way will be create new vector and initialize it with all data and than use it's iterators, but this is pretty resource havy operation, so ideally I want this kind of conversion to be done over each iteration. What is the most elegant way for such kind of conversion?
This is a simplified version of data structure for storing text corpus. Iterators later need to be used in classifier initialization, which require 2 iterators: begin and end which is logically similar to the same as in vector.
A simple range type:
template<class It>
struct range_t {
It b{},e{};
It begin() const {return b;}
It end() const {return e;}
bool empty() const {return begin()==end();}
friend bool operator==(range_t lhs, range_t rhs){
if (lhs.empty() && rhs.empty()) return true;
return lhs.begin() == rhs.begin() && lhs.end() == rhs.end();
}
friend bool operator!=(range_t lhs, range_t rhs){
return !(lhs==rhs);
}
range_t without_front( std::size_t N = 1 ) const {
return { std::next(begin(), N), end() };
}
range_t without_back( std::size_t N = 1 ) const {
return { begin(), std::prev(end(),N) };
}
decltype(auto) front() const {
return *begin();
}
decltype(auto) back() const {
return *std::prev(end());
}
};
template<class It>
range_t<It> range( It b, It e ) {
return {b,e};
}
Here is a non-compliant pseudo-iterator that does the cross product of two ranes:
template<class ItA, class ItB>
struct cross_iterator_t {
range_t<ItA> cur_a;
range_t<ItB> orig_b;
range_t<ItB> cur_b;
cross_iterator_t( range_t<ItA> a, range_t<ItB> b ):
cur_a(a), orig_b(b), cur_b(b)
{}
bool empty() const { return cur_a.empty() || cur_b.empty(); }
void operator++(){
cur_b = cur_b.without_front();
if (cur_b.empty()) {
cur_a = cur_a.without_front();
if (cur_a.empty()) return;
cur_b = orig_b;
}
}
auto operator*()const {
return std::make_pair( cur_a.front(), cur_b.front() );
}
friend bool operator==( cross_iterator_t lhs, cross_iterator_t rhs ) {
if (lhs.empty() && rhs.empty()) return true;
auto mytie=[](auto&& self){
return std::tie(self.cur_a, self.cur_b);
};
return mytie(lhs)==mytie(rhs);
}
friend bool operator!=( cross_iterator_t lhs, cross_iterator_t rhs ) {
return !(lhs==rhs);
}
};
template<class Lhs, class Rhs>
auto cross_iterator( range_t<Lhs> a, range_t<Rhs> b )
-> cross_iterator_t<Lhs, Rhs>
{
return {a,b};
}
From this you can take std::vector<A>, B and do:
template<class A, class B>
auto cross_one_element( A& range_a, B& b_element ) {
auto a = range( std::begin(range_a), std::end(range_a) );
auto b = range( &b_element, (&b_element) +1 );
auto s = cross_iterator(a, b);
decltype(s) f{};
return cross_iterator(s, f);
}
So that solves one of your problems. The above needs to be fixed to support true input iterator featurs, not just the above pseudo-iterator that works with for(:).
Then you have to write code that takes a vector of X and transorms it into a range of f(X) for some function f.
Then you have to write code that takes a range of ranges, and flattens it into a range.
Each of these steps is no harder than above.
There are libraries that do this for you. boost has some, Rangesv3 has some, as do a pile of other range-manipulation libraries.
Boost even lets you write an iterator by specifying what to do on * and on next and on ==. Getting what to do when one of your sub-vectors is empty remains tricky, so using more generic algorithms in this case is probably wise.
The code above is not tested, and is C++14. C++11 versions are merely more verbose.

Making a comparator from an ordered container

Given a list of objects, what is the cleanest way to create a functor object to act as a comparator, such that the comparator respects the ordering of the objects in the list. It is guaranteed that the objects in the list are unique, and the list contains the entire space of possible objects.
For example, suppose we have:
const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};
Now we want a function to act as a comparator, say for a map:
using Comparator = std::function<bool(const std::string&, const std::string&>;
using MyMap = std::map<std::string, int, Comparator>;
I have a solution, but it's not what I'd call pretty:
const auto cmp = [&ordering] (const auto& lhs, const auto& rhs)
{
const std::array<std::reference_wrapper<const std::decay_t<decltype(lhs)>, 2> values {lhs, rhs};
return *std::find_first_of(std::cbegin(ordering), std::cend(ordering),
std::cbegin(values), std::cend(values),
[] (const auto& lhs, const auto& rhs) {
return lhs == rhs.get();
}) == lhs;
};
Is there something a little less verbose?
You can use:
const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};
struct cmp
{
bool operator()(const std::string& lhs, const std::string& rhs)
{
return (std::find(ordering.begin(), ordering.end(), lhs) <
std::find(ordering.begin(), ordering.end(), rhs));
}
};
using MyMap = std::map<std::string, int, cmp>;
See it working at http://ideone.com/JzTNwt.
Just skip the algorithms and write a for-loop:
auto cmp = [&ordering](auto const& lhs, auto const& rhs) {
for (auto const& elem : ordering) {
// check rhs first in case the two are equal
if (elem == rhs) {
return false;
}
else if (elem == lhs) {
return true;
}
}
return false;
};
It might technically be longer than your solution, but I find it way easier to read.
Alternatively, depending on the size of the ordering, could throw both into a map:
std::unordered_map<std::string, int> as_map(std::vector<std::string> const& ordering)
{
std::unordered_map<std::string, int> m;
for (auto const& elem : ordering) {
m.emplace(elem, m.size());
}
return m;
}
auto cmp = [ordering_map = as_map(ordering)](auto const& lhs, auto const& rhs){
auto left = ordering_map.find(lhs);
auto right = ordering_map.find(rhs);
return left != ordering_map.end() && right != ordering_map.end() &&
left->second < right->second;
};
KISS. Build up your solution from reusable primitives with clear semantics.
order_by takes a projection A->B and returns an ordering on A using the ordering on B. It optionally takes an ordering on B (not used here):
template<class F, class Next=std::less<>>
auto order_by(F&& f, Next&& next = {}) {
return [f=std::forward<F>(f), next=std::forward<Next>(next)]
(auto&& lhs, auto&& rhs)->bool
{
return next(f(lhs), f(rhs));
};
}
index_in takes a container c and returns a function that takes an element, and determines its index in c:
template<class C>
auto index_in( C&& c ) {
return [c=std::forward<C>(c)](auto&& x){
using std::begin; using std::end;
return std::find( begin(c), end(c), x ) - begin(c);
};
}
template<class T>
auto index_in( std::initializer_list<T> il ) {
return [il](auto&& x){
using std::begin; using std::end;
return std::find( begin(il), end(il), x ) - begin(il);
};
}
We then compose them:
auto cmp = order_by( index_in(std::move(ordering) ) );
Each component can be independently tested and validated, and the composition "obviously" works. We can also rewrite index_in to use a faster lookup than linear, say a map from key to index, and we'd have two implementations that can unit test against each other.
I find order_by very often useful. index_in I've never had to use before.
This trick makes constructing the resulting map on one line, instead of storing cmp, practical, as the final description is short and clear.
template<class T>
using Comparator = std::function<bool(T const&, T const&>;
using MyMap = std::map<std::string, int, Comparator<std::string>>;
MyMap m = order_by( index_in({"dog", "cat", "mouse", "elephant"}) );
is also really pretty looking.
Here is a second approach.
We can move some of the work outside of the lambda.
template<class T0, class...Ts>
std::array< std::reference_wrapper<T0>, sizeof...(Ts)+1 >
make_ref_array( T0& t0, Ts&... ts ) {
return {std::ref(t0), std::ref(ts)...};
}
Then we can write the lambda from first principles instead of algorithms:
Comparator cmp = [&ordering] (const auto& lhs, const auto& rhs)
{
if (lhs==rhs) return false; // x is never less than x.
for (auto&& e:ordering)
for (auto&& z:make_ref_array(lhs, rhs))
if (e==z.get())
return std::addressof(z.get())==std::addressof(lhs);
return false;
};
The resulting lambda is a bit less verbose.
If you had ranged based algorithms it might also help.
In both my solutions, all elements not in the list are greater than any element in the list, and are equal to each other.
I suggest you make the key a structure type containing the key (std::string in this case) and the index in the array.
Something like
struct Key
{
std::string str;
size_t index;
};
using MyMap = std::map<Key, int, Comparator>;
struct Comparator
{
bool operator()(const Key &a, const Key &b) const
{
return a.index < b.index;
}
};
This is basically the same as R. Sahu's answer. But since I'd already typed it up... The primary thing I'm advocating here is keeping ordering internal to cmp, presuming that you don't need it externally.
const auto cmp = [ordering = vector<string>{ "dog", "cat", "mouse", "elephant" }](const auto& lhs, const auto& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); };
Live Example
Encapsulating the ordering within cmp makes the scope that a reader has to look at when he changes ordering much smaller. (Personally I wouldn't construct cmp as an Rvalue, I'd just dump it directly into the constructor for the same reason... Though it is becoming a bit of a redonculous one-liner:
map<string, int, function<bool(const string&, const string&)>> myMap([ordering = vector<string>{ "dog", "cat", "mouse", "elephant" }](const auto& lhs, const auto& rhs) { return find(cbegin(ordering), cend(ordering), lhs) < find(cbegin(ordering), cend(ordering), rhs); });
Live Example

Construction a vector from the concatenation of 2 vectors

Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)
For example:
const vector<int> first = {13};
const vector<int> second = {42};
const vector<int> concatenation = first + second;
I know that vector doesn't have an addition operator like string, but that's the behavior that I want. Such that concatenation would contain: 13 and 42.
I know that I can initialize concatenation like this, but it prevents me from making concatenation const:
vector<int> concatenation = first;
first.insert(concatenation.end(), second.cbegin(), second.cend());
No, it's not possible if you require that
no helper function is defined, and
the resulting vector can be declared const.
template<typename T>
std::vector<T> operator+(const std::vector<T>& v1, const std::vector<T>& v2){
std::vector<T> vr(std::begin(v1), std::end(v1));
vr.insert(std::end(vr), std::begin(v2), std::end(v2));
return vr;
}
This does require a helper "function", but at least it allows you to use it as
const vector<int> concatenation = first + second;
I think you have to write a help function. I'd write it as:
std::vector<int> concatenate(const std::vector<int>& lhs, const std::vector<int>& rhs)
{
auto result = lhs;
std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
return result;
}
The call it as:
const auto concatenation = concatenate(first, second);
If the vectors are likely to be very large (or contain elements that are expensive to copy), then you might need to do a reserve first to save reallocations:
std::vector<int> concatenate(const std::vector<int>& lhs, const std::vector<int>& rhs)
{
std::vector<int> result;
result.reserve( lhs.size() + rhs.size() );
std::copy( lhs.begin(), lhs.end(), std::back_inserter(result) );
std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
return result;
}
(Personally, I would only bother if there was evidence it was a bottleneck).
class Vector : public vector<int>
{
public:
Vector operator+(const Vector& vec);
};
Vector Vector::operator+(const Vector& vec)
{
for (int i = 0; i < vec.size(); i++)
{
this->push_back(vec[i]);
}
return *this;
}
Let me preface this by saying this is a hack, and will not give an answer to how to do this using a vector. Instead we'll depend on sizeof(int) == sizeof(char32_t) and use a u32string to contain our data.
This answer makes it exceedingly clear that only primitives can be used in a basic_string, and that any primitive larger than 32-bits would require writing a custom char_traits, but for an int we can just use u32string.
The qualification for this can be validated by doing:
static_assert(sizeof(int) == sizeof(char32_t));
Once size equality has been established, and with the knowledge that things like non-const data, and emplace or emplace_back cannot be used, u32string can be used like a vector<int>, with the notable inclusion of an addition opperator:
const vector<int> first = {13};
const vector<int> second = {42};
const u32string concatenation = u32string(first.cbegin(), first.cend()) + u32string(second.cbegin(), second.cend());
[Live Example]
I came across this question looking for the same thing, and hoping there was an easier way than the one I came up with... seems like there isn't.
So, some iterator trickery should do it if you don't mind a helper template class:
#include <vector>
#include <iostream>
template<class T>
class concat
{
public:
using value_type = typename std::vector<T>::const_iterator::value_type;
using difference_type = typename std::vector<T>::const_iterator::difference_type;
using reference = typename std::vector<T>::const_iterator::reference;
using pointer = typename std::vector<T>::const_iterator::pointer;
using iterator_category = std::forward_iterator_tag;
concat(
const std::vector<T>& first,
const std::vector<T>& last,
const typename std::vector<T>::const_iterator& iterator) :
mFirst{first},
mLast{last},
mIterator{iterator}{}
bool operator!= ( const concat& i ) const
{
return mIterator != i.mIterator;
}
concat& operator++()
{
++mIterator;
if(mIterator==mFirst.end())
{
mIterator = mLast.begin();
}
return *this;
}
reference operator*() const
{
return *mIterator;
}
private:
const std::vector<T>& mFirst;
const std::vector<T>& mLast;
typename std::vector<T>::const_iterator mIterator;
};
int main()
{
const std::vector<int> first{0,1,2,3,4};
const std::vector<int> last{5,6,7,8,9};
const std::vector<int> concatenated(
concat<int>(first,last,first.begin()),
concat<int>(first,last,last.end()));
for(auto i: concatenated)
{
std::cout << i << std::endl;
}
return 0;
}
You may have to implement operator++(int) or operator== depending on how your STL implements the InputIterator constructor, this is the minimal iterator code example I could come up with for MingW GCC.
Have Fun! :)

Overload make_heap?

I have a std::vector<t_Mont> v, t_Mont have {float val, int i and int j}
I want to do make_heap(v.begin(), v.end()) and pop_head(v.begin(), v.end()) but I get a lot of errors on console. I think this is because I'm passing a vector of type t_mont.
I want to make_heap on the value of the variable val of v.
What I have to do to compile me? I have to overload make_heap and pop_head? How I do it?
Thanks.
My code:
std::vector<t_Mont> v;
for (int i = 0; i < nCellsHeight; i++) {
for (int j = 0; j < nCellsWidth; j++) {
t_Mont aux;
aux.i = i;
aux.j = j;
aux.val = cellValues[i][j];
v.push_back(aux);
}
}
std::make_heap(v.begin(), v.end());
while (v.begin() != v.end()) {
std::cout << "Best of v = " << v[0].val << std::endl;
std::pop_heap(v.begin(), v.end());
v.pop_back();
std::make_heap(v.begin(), v.end());
}
make_heap and related functions will, by default, compare values using <. You need to either provide an overload of that operator for your type:
bool operator<(t_Mont const & lhs, t_Mont const & rhs) {
return lhs.val < rhs.val;
}
or provide a custom comparator when you call the functions:
auto comp = [](t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;};
std::make_heap(v.begin(), v.end(), comp);
If you're stuck with an ancient pre-lambda compiler, define a function type in full:
struct Comp {
bool operator()(t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;}
};
std::make_heap(v.begin(), v.end(), Comp());
t_Mont has to be comparable with operator< for this to work, or you have to use the other form of std::make_heap and pass a comparison functor alongside the iterators (if, for some reason, you don't want t_Mont to be generally sortable).
That is to say, you have to define
bool operator<(t_Mont const &lhs, t_Mont &rhs) {
// return true if lhs is less than rhs, false otherwise.
}
so that you get a total order (i.e., a < b means !(b < a), a < b and b < c mean a < c, and !(a < a)), or
struct t_Mont_compare {
bool operator()(t_Mont const &lhs, t_Mont &rhs) const{
// return true if lhs is less than rhs, false otherwise.
}
}
with the same conditions.
You have to define a function object for making comparisons between two t_Monts. The declaration of make_heap looks like this :
template <class RandomAccessIterator, class Compare>
void make_heap (RandomAccessIterator first, RandomAccessIterator last, Compare comp );
Or just create a function like this :
bool comp_tmonts(const t_Mont& a, const t_Mont& b)
{
/* Insert your comparison criteria for less than here.
Return a boolean value corresponding to whether a is less than b */
}
Then pass this to your make_heap function as the third argument :
make_heap(v1.begin(), v1.end(), comp_tmonts);