I'm trying to do an ordered insertion in a vector, but the compiler keeps giving me errors.
What I'm trying to do is based here:
how do you insert the value in a sorted vector?
I've run a code like this:
#include <utility>
// TIMESTAMP is more complex than this, but just for simplicity...
typedef TIMESTAMP double
int main() {
const std::vector<std::pair<TIMESTAMP, double>> myVec;
std::pair<TIMESTAMP, double> pairdata = std::make_pair(4, 4);
/* adds some ORDERED values here... */
/* ... */
/* Tries to insert a new ordered value with 4,4 */
auto upper =
std::upper_bound(myVec.begin(), myVec.end(), pairdata,
[](const std::pair<TIMESTAMP, double> &a, const std::pair<TIMESTAMP, double> &b) -> bool {
return a.first < b.first;
}
);
myVec.insert(upper, pairdata);
/** DO MORE STUFF **/
return 0;
}
But I keep getting:
error: cannot bind rvalue reference of type ‘std::vector<std::pair<TIMESTAMP, double> >::value_type&& {aka std::pair<TIMESTAMP, double>&&}’ to lvalue of type ‘std::pair<TIMESTAMP, double>’
myVec.insert(upper, pairdata);
What an I doing wrong? I also tried to std::move pairdata, without success:
error: no matching function for call to ‘std::vector<std::pair<TIMESTAMP, double> >::insert(__gnu_cxx::__normal_iterator<const std::pair<TIMESTAMP, double>*, std::vector<std::pair<TIMESTAMP, double> > >&, std::remove_reference<std::pair<TIMESTAMP, double>&>::type) const’
myVec.insert(upper, std::move(pairdata));
And I also tried to use insert_sorted, as given on mentioned link:
template<typename T>
typename std::vector<T>::iterator insert_sorted( std::vector<T> &vec, T const& item, std::function<bool(const T&, const T&)> pred )
{
return vec.insert (
std::upper_bound( vec.begin(), vec.end(), item, pred ),
item
);
}
/** calling **/
std::function<bool(const std::pair<TIMESTAMP, double>&, const std::pair<TIMESTAMP, double>&)> f =
[](const std::pair<TIMESTAMP, double> &a, const std::pair<TIMESTAMP, double> &b) -> bool {
return a.first < b.first;
};
insert_sorted(
myVec, pairdata, f);
@EDIT On my original post, I did not have "const" on myVec. That's was actually my problem. In my code "myVec" was a const reference, so it could not insert. So, my problem is solved :)
Aucun commentaire:
Enregistrer un commentaire