Error using Max_Element with String Vector - c++11

I'm implementing an algorithm to return a vector string array with only the largest elements in the vector string array of entrance:
vector<string> solution(vector<string> inputArray) {
vector<string> s;
auto m = *max_element(inputArray.begin(),inputArray.end());
for(int i=0;i<inputArray.size();i++){
if(inputArray[i].size() == m.size())
{
s.push_back(inputArray[i]);
}
}
return s;
It works for every test case except in the case the entry string vector is {"enyky", "benyky","yely","varennyky"}. 'm' should return a pointer to "varennyky", but it returns a pointer to "yely" instead.
I digged in to the documentation for max_element, but cant find what I'm doing wrong. Can anybody help me?

Your function is comparing the strings lexicographically, which is the default comparison in case of strings.
To illustrate, consider the following example:
#include <algorithm>
#include <string>
#include <vector>
// Print a vector of strings
void print_vec(std::vector<std::string> vec)
{
for (const auto& el : vec) {
std::cout << el << " ";
}
std::cout << std::endl;
}
// Compares strings by length
bool less_length(const std::string& s1, const std::string& s2)
{
return s1.length() < s2.length();
}
int main()
{
std::vector<std::string> test_0 = {"enyky", "benyky","yely","varennyky"};
// Default sort and max element
std::sort(test_0.begin(), test_0.end());
print_vec(test_0);
const auto largest_0 = *std::max_element(test_0.begin(), test_0.end());
std::cout << "Largest member (lexicographically): " << largest_0 << '\n' << std::endl;
// Sort and max element by string size
std::sort(test_0.begin(), test_0.end(), less_length);
print_vec(test_0);
const auto largest_1 = *std::max_element(test_0.begin(), test_0.end(), less_length);
std::cout << "Largest member (by string length): " << largest_1 << std::endl;
}
The first part of the program runs what you are doing in your function: it finds the maximum element based on lexicographic ordering. According to that ordering, the largest string is yely, you can see that by the output from sort.
The second part uses a custom comparison function, borrowed directly from this book. It uses string length to determine the order in the max_element call and the result is what you were looking for. Again, the sorted vector is also printed for clarity.

Related

How do i assign values to my fraction objecct using make_unique()?

#include <memory> // for std::unique_ptr and std::make_unique
#include <iostream>
class Fraction
{
private:
int m_numerator;
int m_denominator;
public:
Fraction(int numerator, int denominator) :
m_numerator{ numerator }, m_denominator{ denominator }
{
}
friend std::ostream& operator<<(std::ostream& out, const Fraction &f1)
{
out << f1.m_numerator << "/" << f1.m_denominator;
return out;
}
friend operator=(const Fraction &f1,const int numerator,const int denominator){
f1.m_numerator=numerator;
f1.m_denominator=denominator;
}
};
int main()
{
// Create a single dynamically allocated Fraction with numerator 3 and denominator 5
std::unique_ptr<Fraction> f1{ std::make_unique<Fraction>(3, 5) };
std::cout << *f1 << '\n';
// Create a dynamically allocated array of Fractions of length 4
// We can also use automatic type deduction to good effect here
auto f2{ std::make_unique<Fraction[]>(4) };
f2[0]=(3,5);
f2[1]=(67,82,5,543345);
std::cout << f2[0] << '\n';
std::cout << f2[1] << '\n';
return 0;
}
First, operator= can be implemented only as member function, not free function. So your approach is just wrong. Second, overloaded operator= can accept only one parameter. The closest thing you want, can be achived by passing initializer_list as this parameter:
Fraction& operator=(std::initializer_list<int> il){
// some code validating size of il here
this->m_numerator=*il.begin();
this->m_denominator = *(il.begin()+1);
return *this;
}
the use looks like:
f2[0]={3,5};
f2[1]={67,84};
Full demo

remove_if from vector of strings

I need to remove some elements from a vector of strings if any of the strings contain a certain word.
How can I write the unary predicate for remove_if?
Here is code sample:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool remove_if_found(string word)
{
// ???
}
int main()
{
vector<string> data {
{ "the guitar has six strings" },
{ "the violin has four strings" },
{ "the the violin is more difficult to learn" },
{ "saxophones are a family of instruments" },
{ "the drum is a set of percussions" },
{ "the trumpet is a brass" }
};
cout << data.size() << endl; // output: 6
remove_if(data.begin(), data.end(), remove_if_found("violin")); // error
cout << data.size() << endl; // output should be: 4
return 0;
}
The problem is that the expression remove_if_found("violin") returns a bool which cannot be passed to std::remove_if.
The easiest solution for you would be to change remove_if_found as such:
void remove_if_found(vector<string>& vec, const string& word)
{
vec.erase(remove_if(vec.begin(), vec.end(), [&word](const string& el) {
// check if the word is contained within the string
return el.find(word) != std::string::npos;
}), vec.end());
}
which takes a reference to the vector as well as the string to look for and does the removal as normal.
Then in main you just call it as such:
remove_if_found(data, "violin");
The reason for the erase+remove usage in the remove_if_function is important. std::remove_if merely moves the elements you wish to remove to the end of the vector and returns an iterator to the first of those (re)moved elements. On the other hand std::vector::erase takes two iterators - the returned one from std::remove_if iterator and vec.end() and actually erases them from the vector.

Remove All Elements from unordered_set

I already went through this post Deleting elements from STL set while iterating
Still, I want to understand why the code below produces the wrong result.
int main() {
unordered_set<int> adjacency;
adjacency.insert(1);
adjacency.insert(2);
for (const auto& n : adjacency) {
adjacency.erase(n);
}
cout <<"After removing all elements: " << endl;
for (const auto& n : adjacency) {
cout << n << " ";
}
cout << endl;
return 0;
}
The adjacency contains 1 and 2. After erasing all elements through for-loop, it still contains element 1. Why?
I am using version (2) erase function below, so the rule "Versions (1) and (3) return an iterator pointing to the position immediately following the last of the elements erased." does not apply?
UPDATE: the reason of not using clear() is that it requires removing the element one by one to do some other processing.
by position (1)
iterator erase ( const_iterator position );
by key (2)
size_type erase ( const key_type& k );
range (3)
iterator erase ( const_iterator first, const_iterator last );
Version (2) returns the number of elements erased, which in unordered_set containers (that have unique values), this is 1 if an element with a value of k existed (and thus was subsequently erased), and zero otherwise.
Versions (1) and (3) return an iterator pointing to the position immediately following the last of the elements erased.
Thanks!
Range-based for-loops use iterators under the hood,
so what you wrote leads to undefined behaviour.
If you need to process all elements, and then remove some
of them based on some criteria, there is a way to do that
that works on all containers:
for(auto it = adjacency.begin(); it != adjacency.end();)
{
Process(*it);
if (Condition(*it))
it = adjacency.erase(it);
else
++it;
}
If you need to process all items, and then remove all, then do that:
std::for_each(adjacency.begin(), adjacency.end(), &Process);
adjacency.clear();
You are pulling the rug out from underneath your own feet, as Raymond pointed out.
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
typedef unordered_set<int> adjacency_t;
typedef adjacency_t::iterator adjacencyIt_t;
adjacency_t adjacency;
adjacency.insert(1);
adjacency.insert(2);
cout <<"Before: " << endl;
for (const auto& n : adjacency) {
cout << n << " ";
}
cout << endl;
for (adjacencyIt_t i = adjacency.begin(); i!=adjacency.end(); /*empty*/)
{
// Do some processing on *i here.
adjacency.erase(i++); // Don't erase the old iterator before using it to move to the next in line.
}
cout <<"After removing all elements: " << endl;
for (const auto& n : adjacency) {
cout << n << " ";
}
cout << endl;
return 0;
}

Reading in from file with modern c++ - data is not stored

maybe I get something wrong with shared_pointers or there is some basic shortcoming of mine but I couldn't get this right. So I want to read in some data from a file. There are position and momentum data on each line of the data file and the first line stores the number of data points.
I need to read this in to my data structure and for some reason my graph would not fill, although the data reads in correctly.
const int dim = 3; // dimension of problem
template <typename T, typename G>
// T is the type of the inputted locations and G is the type of the
// distance between them
// for example: int point with float/double distance
struct Node{
std::pair< std::array<T, dim>,std::pair< std::array<T, dim>, G > > pos; // position
std::pair< std::array<T, dim>,std::pair< std::array<T, dim>, G > > mom; // momentum
// a pair indexed by a position in space and has a pair of position
// and the distance between these points
};
template <typename T, typename G>
struct Graph{
int numOfNodes;
std::vector< Node<T,G> > nodes;
};
This is the data structure and here's my read function (std::cout-s are only for testing):
template <typename T, typename G>
std::istream& operator>>(std::istream& is, std::shared_ptr< Graph<T,G> >& graph){
is >> graph->numOfNodes; // there's the number of nodes on the first line of the data file
std::cout << graph->numOfNodes << "\n";
for(int k=0; k<graph->numOfNodes; k++){
Node<T,G> temp;
for(auto i : temp.pos.first){
is >> i;
std::cout << i << "\t";
}
std::cout << "\t";
for(auto i : temp.mom.first){
is >> i;
std::cout << i << "\t";
}
std::cout << "\n";
graph->nodes.push_back(temp);
}
return is;
}
I have an output function as well. So if I output the graph which I intended to fill during read-in is zeroed out. Number of nodes os correct however positions and momente are all zeroed out. What did I do wrong? Thanks in advance.
for(auto i : temp.pos.first){
is >> i;
std::cout << i << "\t";
}
Think of this as similar to a function. If you have something like:
void doX(int i) { i = 42; }
int main() {
int j=5;
doX(j);
return j;
}
Running this code, you'll see the program returns the value 5. This is because the function doX takes i by value; it basically takes a copy of the variable.
If you replace doX's signature with
void doX(int &i)
and run the code, you'll see it returns 42. This is because the function is now taking the argument by reference, and so can modify it.
Your loops will behave similarly. As you have it now, they take a copy of the values in the arrays in turn, but are not by reference.
As with the function, you can change your loops to look like
for(auto &i : temp.pos.first){
is >> i;
std::cout << i << "\t";
}
This should then let you change the values stored in the arrays.

Boost Mem_fn and accessing member function of derived class

I made a simple example to test boost bind's interaction with derived classes.
I created two subclasses with different getarea functions. I expected
g1 = boost::bind(boost::mem_fn(&Shape::getarea), Rec)
to print the area of Rectangle(10,20) but instead it printed '1'. I get the same when I instead write Rectangle::getarea. It prints the same even when I input other functions eg. member of Rectangle
double sum(double h,double w){return h+w; }
and use
g1 = boost::bind(boost::mem_fn(&Rectangle::sum), Rec,2,3)
Question 1: Why does it return '1'?Is that a default response for error?
My second problem is to do the same of printing g2 but now Rec is replaced by **iter, i.e. an object of some derived class type from a list of objects. Since getarea is a virtual fcn, once I get the above working it should be fine to just write:
g2= boost::bind(boost::mem_fn(& Shape::getarea , &(**iter));
Question 2: However, I was wondering if there is a way to return the classtype of **iter eg. classof(**iter) and then put it in g2 i.e.
g2= boost::bind(boost::mem_fn(& classof(**iter)::getarea , &(**iter));
When I ran g2 by writing Shape::getarea, I got '1' again for all iter.
#include <memory>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <boost/bind.hpp>
using namespace std;
class Shape {
public:
Shape(double h, double w) :height(h), width(w) {};
virtual double getarea() = 0;
double height;
double width; };
class Rectangle: public Shape {
public:
Rectangle(double h, double w): Shape(h,w) {};
double getarea() override { return height*width; } };
class Triangle : public Shape {
public:
Triangle(double h, double w) :Shape(h,w) {};
double getarea() { return height*width*0.5; }};
int main() {
//create objects
Rectangle Rec(10, 20);
Triangle Tri(2, 3);
//create boost bind function
boost::function<double(double, double)> g1;
g1 = boost::bind(boost::mem_fn(&Shape::getarea), Rec);
//print area and g
cout << Rec.getarea()<<" should be equal to " << g1<< '\n';
//create list
vector<shared_ptr<Shape>> Plist;
Plist.push_back(make_shared<Rectangle>(Rec));
Plist.push_back(make_shared<Triangle>(Tri));
//print each element from the vector list
for (auto iter = Plist.begin(); iter != Plist.end(); iter ++ ) {
boost::function<double(double, double)> g2;
g2= boost::bind(boost::mem_fn(& .... , &(**iter));
//where in dots we need Classtype_of_**iter::getarea
cout << (**iter).getarea()<<"should be equal to " << g2<< '\n';
}
}
You... forget to invoke the functions...
for (auto iter = Plist.begin(); iter != Plist.end(); iter++) {
boost::function<double()> g2;
g2 = boost::bind(&Shape::getarea, iter->get());
cout << (*iter)->getarea() << " should be equal to " << g2() << '\n';
}
What you saw what the implicit conversion to bool (http://www.boost.org/doc/libs/1_60_0/doc/html/boost/function.html#idm45507164686720-bb)
Note also I fixed the signature of g1 and g2: Live On Coliru.
Some further improvements (remove the need for the g2 in the loop?):
auto getarea = boost::mem_fn(&Shape::getarea);
for (auto iter = Plist.begin(); iter != Plist.end(); iter++) {
cout << (*iter)->getarea() << " should be equal to " << getarea(**iter) << '\n';
}
Or, indeed in c++11:
for (auto& s : Plist)
cout << s->getarea() << " should be equal to " << getarea(*s) << '\n';
By this time, you'd wonder why you have this accessor when you can just use the member.

Resources