Stroustrup's Header error working with FLTK - c++
I have successfully installed FLTK in VS 2015 Community Edition. I am dealing with other headers, part of Stroustrup's book, to build graphs and to create custom windows where to attach them. My problem is that when I am trying to compile I receive 4 error messagges (plus 23 Warnings):
(active) IntelliSense namespace "std" has no member
"Vector" Win32Project1 c:\Users\Leonardo\Documents\Visual Studio
2015\Projects\Win32Project1\Win32Project1\Window.h 17
Error C2873 Build 'Vector': symbol cannot be used in a
using-declaration Win32Project1 c:\users\leonardo\documents\visual
studio 2015\projects\win32project1\win32project1\Window.h 17
Error C2039 Build 'Vector': is not a member of
'std' Win32Project1 c:\users\leonardo\documents\visual studio
2015\projects\win32project1\win32project1\Window.h 17
Error C2440 Build 'return': cannot convert from 'std::ifstream' to
'bool' Win32Project1 C:\Users\Leonardo\Documents\Visual Studio
2015\Projects\Win32Project1\Win32Project1\Graph.cpp 371
I have set a Win32Project (not a Console Project), following the steps of this site: http://www.c-jump.com/bcc/common/Talk2/Cxx/FltkInstallVC/FltkInstallVC.html.
If I run the test example it perfectly works so, I guess, to have correctly installed the additional library.
Furthermore, I have added every header or source file provided by the author in the project.
main.cpp:
#include "std_lib_facilities.h"
#include "Graph.h"
#include "Simple_window.h"
int main()
{
using namespace Graph_lib;
Point tl{ 100,100 };
Simple_window win{ tl,600,400,"My Window" };
win.wait_for_button();
}
All headers and source file can be reached at: http://www.stroustrup.com/Programming/Programming-code.zip
Here Windows.h
//
// This is a GUI support code to the chapters 12-16 of the book
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#ifndef WINDOW_GUARD
#define WINDOW_GUARD
#include <string>
#include <vector>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include "Point.h"
using std::string;
using std::vector;
namespace Graph_lib
{
class Shape; // "forward declare" Shape
class Widget;
//------------------------------------------------------------------------------
class Window : public Fl_Window {
public:
// let the system pick the location:
Window(int w, int h, const string& title);
// top left corner in xy
Window(Point xy, int w, int h, const string& title);
virtual ~Window() { }
int x_max() const { return w; }
int y_max() const { return h; }
void resize(int ww, int hh) { w=ww, h=hh; size(ww,hh); }
void set_label(const string& s) { copy_label(s.c_str()); }
void attach(Shape& s) { shapes.push_back(&s); }
void attach(Widget&);
void detach(Shape& s); // remove s from shapes
void detach(Widget& w); // remove w from window (deactivates callbacks)
void put_on_top(Shape& p); // put p on top of other shapes
protected:
void draw();
private:
vector<Shape*> shapes; // shapes attached to window
int w,h; // window size
void init();
};
and Graph.cpp
//
// This is a GUI support code to the chapters 12-16 of the book
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#include <FL/Fl_GIF_Image.H>
#include <FL/Fl_JPEG_Image.H>
#include "Graph.h"
//------------------------------------------------------------------------------
namespace Graph_lib {
//------------------------------------------------------------------------------
Shape::Shape() :
lcolor(fl_color()), // default color for lines and characters
ls(0), // default style
fcolor(Color::invisible) // no fill
{}
//------------------------------------------------------------------------------
void Shape::add(Point p) // protected
{
points.push_back(p);
}
//------------------------------------------------------------------------------
void Shape::set_point(int i,Point p) // not used; not necessary so far
{
points[i] = p;
}
//------------------------------------------------------------------------------
void Shape::draw_lines() const
{
if (color().visibility() && 1<points.size()) // draw sole pixel?
for (unsigned int i=1; i<points.size(); ++i)
fl_line(points[i-1].x,points[i-1].y,points[i].x,points[i].y);
}
//------------------------------------------------------------------------------
void Shape::draw() const
{
Fl_Color oldc = fl_color();
// there is no good portable way of retrieving the current style
fl_color(lcolor.as_int()); // set color
fl_line_style(ls.style(),ls.width()); // set style
draw_lines();
fl_color(oldc); // reset color (to previous)
fl_line_style(0); // reset line style to default
}
//------------------------------------------------------------------------------
void Shape::move(int dx, int dy) // move the shape +=dx and +=dy
{
for (int i = 0; i<points.size(); ++i) {
points[i].x+=dx;
points[i].y+=dy;
}
}
//------------------------------------------------------------------------------
Line::Line(Point p1, Point p2) // construct a line from two points
{
add(p1); // add p1 to this shape
add(p2); // add p2 to this shape
}
//------------------------------------------------------------------------------
void Lines::add(Point p1, Point p2)
{
Shape::add(p1);
Shape::add(p2);
}
//------------------------------------------------------------------------------
// draw lines connecting pairs of points
void Lines::draw_lines() const
{
if (color().visibility())
for (int i=1; i<number_of_points(); i+=2)
fl_line(point(i-1).x,point(i-1).y,point(i).x,point(i).y);
}
//------------------------------------------------------------------------------
// does two lines (p1,p2) and (p3,p4) intersect?
// if se return the distance of the intersect point as distances from p1
inline pair<double,double> line_intersect(Point p1, Point p2, Point p3, Point p4, bool& parallel)
{
double x1 = p1.x;
double x2 = p2.x;
double x3 = p3.x;
double x4 = p4.x;
double y1 = p1.y;
double y2 = p2.y;
double y3 = p3.y;
double y4 = p4.y;
double denom = ((y4 - y3)*(x2-x1) - (x4-x3)*(y2-y1));
if (denom == 0){
parallel= true;
return pair<double,double>(0,0);
}
parallel = false;
return pair<double,double>( ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3))/denom,
((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3))/denom);
}
//------------------------------------------------------------------------------
//intersection between two line segments
//Returns true if the two segments intersect,
//in which case intersection is set to the point of intersection
bool line_segment_intersect(Point p1, Point p2, Point p3, Point p4, Point& intersection){
bool parallel;
pair<double,double> u = line_intersect(p1,p2,p3,p4,parallel);
if (parallel || u.first < 0 || u.first > 1 || u.second < 0 || u.second > 1) return false;
intersection.x = p1.x + u.first*(p2.x - p1.x);
intersection.y = p1.y + u.first*(p2.y - p1.y);
return true;
}
//------------------------------------------------------------------------------
void Polygon::add(Point p)
{
int np = number_of_points();
if (1<np) { // check that thenew line isn't parallel to the previous one
if (p==point(np-1)) error("polygon point equal to previous point");
bool parallel;
line_intersect(point(np-1),p,point(np-2),point(np-1),parallel);
if (parallel)
error("two polygon points lie in a straight line");
}
for (int i = 1; i<np-1; ++i) { // check that new segment doesn't interset and old point
Point ignore(0,0);
if (line_segment_intersect(point(np-1),p,point(i-1),point(i),ignore))
error("intersect in polygon");
}
Closed_polyline::add(p);
}
//------------------------------------------------------------------------------
void Polygon::draw_lines() const
{
if (number_of_points() < 3) error("less than 3 points in a Polygon");
Closed_polyline::draw_lines();
}
//------------------------------------------------------------------------------
void Open_polyline::draw_lines() const
{
if (fill_color().visibility()) {
fl_color(fill_color().as_int());
fl_begin_complex_polygon();
for(int i=0; i<number_of_points(); ++i){
fl_vertex(point(i).x, point(i).y);
}
fl_end_complex_polygon();
fl_color(color().as_int()); // reset color
}
if (color().visibility())
Shape::draw_lines();
}
//------------------------------------------------------------------------------
void Closed_polyline::draw_lines() const
{
Open_polyline::draw_lines(); // first draw the "open poly line part"
// then draw closing line:
if (color().visibility())
fl_line(point(number_of_points()-1).x,
point(number_of_points()-1).y,
point(0).x,
point(0).y);
}
//------------------------------------------------------------------------------
void draw_mark(Point xy, char c)
{
static const int dx = 4;
static const int dy = 4;
string m(1,c);
fl_draw(m.c_str(),xy.x-dx,xy.y+dy);
}
//------------------------------------------------------------------------------
void Marked_polyline::draw_lines() const
{
Open_polyline::draw_lines();
for (int i=0; i<number_of_points(); ++i)
draw_mark(point(i),mark[i%mark.size()]);
}
//------------------------------------------------------------------------------
void Rectangle::draw_lines() const
{
if (fill_color().visibility()) { // fill
fl_color(fill_color().as_int());
fl_rectf(point(0).x,point(0).y,w,h);
}
if (color().visibility()) { // lines on top of fill
fl_color(color().as_int());
fl_rect(point(0).x,point(0).y,w,h);
}
}
//------------------------------------------------------------------------------
Circle::Circle(Point p, int rr) // center and radius
:r(rr)
{
add(Point(p.x-r,p.y-r)); // store top-left corner
}
//------------------------------------------------------------------------------
Point Circle::center() const
{
return Point(point(0).x+r, point(0).y+r);
}
//------------------------------------------------------------------------------
void Circle::draw_lines() const
{
if (color().visibility())
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
}
//------------------------------------------------------------------------------
void Ellipse::draw_lines() const
{
if (color().visibility())
fl_arc(point(0).x,point(0).y,w+w,h+h,0,360);
}
//------------------------------------------------------------------------------
void Text::draw_lines() const
{
int ofnt = fl_font();
int osz = fl_size();
fl_font(fnt.as_int(),fnt_sz);
fl_draw(lab.c_str(),point(0).x,point(0).y);
fl_font(ofnt,osz);
}
//------------------------------------------------------------------------------
Axis::Axis(Orientation d, Point xy, int length, int n, string lab) :
label(Point(0,0),lab)
{
if (length<0) error("bad axis length");
switch (d){
case Axis::x:
{
Shape::add(xy); // axis line
Shape::add(Point(xy.x+length,xy.y));
if (1<n) { // add notches
int dist = length/n;
int x = xy.x+dist;
for (int i = 0; i<n; ++i) {
notches.add(Point(x,xy.y),Point(x,xy.y-5));
x += dist;
}
}
// label under the line
label.move(length/3,xy.y+20);
break;
}
case Axis::y:
{
Shape::add(xy); // a y-axis goes up
Shape::add(Point(xy.x,xy.y-length));
if (1<n) { // add notches
int dist = length/n;
int y = xy.y-dist;
for (int i = 0; i<n; ++i) {
notches.add(Point(xy.x,y),Point(xy.x+5,y));
y -= dist;
}
}
// label at top
label.move(xy.x-10,xy.y-length-10);
break;
}
case Axis::z:
error("z axis not implemented");
}
}
//------------------------------------------------------------------------------
void Axis::draw_lines() const
{
Shape::draw_lines();
notches.draw(); // the notches may have a different color from the line
label.draw(); // the label may have a different color from the line
}
//------------------------------------------------------------------------------
void Axis::set_color(Color c)
{
Shape::set_color(c);
notches.set_color(c);
label.set_color(c);
}
//------------------------------------------------------------------------------
void Axis::move(int dx, int dy)
{
Shape::move(dx,dy);
notches.move(dx,dy);
label.move(dx,dy);
}
//------------------------------------------------------------------------------
Function::Function(Fct f, double r1, double r2, Point xy,
int count, double xscale, double yscale)
// graph f(x) for x in [r1:r2) using count line segments with (0,0) displayed at xy
// x coordinates are scaled by xscale and y coordinates scaled by yscale
{
if (r2-r1<=0) error("bad graphing range");
if (count <=0) error("non-positive graphing count");
double dist = (r2-r1)/count;
double r = r1;
for (int i = 0; i<count; ++i) {
add(Point(xy.x+int(r*xscale),xy.y-int(f(r)*yscale)));
r += dist;
}
}
//------------------------------------------------------------------------------
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return ff;
}
//------------------------------------------------------------------------------
#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))
Suffix::Encoding get_encoding(const string& s)
{
struct SuffixMap
{
const char* extension;
Suffix::Encoding suffix;
};
static SuffixMap smap[] = {
{".jpg", Suffix::jpg},
{".jpeg", Suffix::jpg},
{".gif", Suffix::gif},
};
for (int i = 0, n = ARRAY_SIZE(smap); i < n; i++)
{
int len = strlen(smap[i].extension);
if (s.length() >= len && s.substr(s.length()-len, len) == smap[i].extension)
return smap[i].suffix;
}
return Suffix::none;
}
//------------------------------------------------------------------------------
// somewhat over-elaborate constructor
// because errors related to image files can be such a pain to debug
Image::Image(Point xy, string s, Suffix::Encoding e)
:w(0), h(0), fn(xy,"")
{
add(xy);
if (!can_open(s)) { // can we open s?
fn.set_label("cannot open \""+s+'\"');
p = new Bad_image(30,20); // the "error image"
return;
}
if (e == Suffix::none) e = get_encoding(s);
switch(e) { // check if it is a known encoding
case Suffix::jpg:
p = new Fl_JPEG_Image(s.c_str());
break;
case Suffix::gif:
p = new Fl_GIF_Image(s.c_str());
break;
default: // Unsupported image encoding
fn.set_label("unsupported file type \""+s+'\"');
p = new Bad_image(30,20); // the "error image"
}
}
//------------------------------------------------------------------------------
void Image::draw_lines() const
{
if (fn.label()!="") fn.draw_lines();
if (w&&h)
p->draw(point(0).x,point(0).y,w,h,cx,cy);
else
p->draw(point(0).x,point(0).y);
}
//------------------------------------------------------------------------------
} // of namespace Graph_lib
I hope someone could help me.
EDIT
/*
std_lib_facilities.h
*/
/*
simple "Programming: Principles and Practice using C++ (second edition)" course header to
be used for the first few weeks.
It provides the most common standard headers (in the global namespace)
and minimal exception/error support.
Students: please don't try to understand the details of headers just yet.
All will be explained. This header is primarily used so that you don't have
to understand every concept all at once.
By Chapter 10, you don't need this file and after Chapter 21, you'll understand it
Revised April 25, 2010: simple_error() added
Revised November 25 2013: remove support for pre-C++11 compilers, use C++11: <chrono>
Revised November 28 2013: add a few container algorithms
Revised June 8 2014: added #ifndef to workaround Microsoft C++11 weakness
*/
#ifndef H112
#define H112 251113L
#include<iostream>
#include<iomanip>
#include<fstream>
#include<sstream>
#include<cmath>
#include<cstdlib>
#include<string>
#include<list>
#include <forward_list>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include <array>
#include <regex>
#include<random>
#include<stdexcept>
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
typedef long Unicode;
//------------------------------------------------------------------------------
using namespace std;
template<class T> string to_string(const T& t)
{
ostringstream os;
os << t;
return os.str();
}
struct Range_error : out_of_range { // enhanced vector range error reporting
int index;
Range_error(int i) :out_of_range("Range error: "+to_string(i)), index(i) { }
};
// trivially range-checked vector (no iterator checking):
template< class T> struct Vector : public std::vector<T> {
using size_type = typename std::vector<T>::size_type;
#ifdef _MSC_VER
// microsoft doesn't yet support C++11 inheriting constructors
Vector() { }
explicit Vector(size_type n) :std::vector<T>(n) {}
Vector(size_type n, const T& v) :std::vector<T>(n,v) {}
template <class I>
Vector(I first, I last) : std::vector<T>(first, last) {}
Vector(initializer_list<T> list) : std::vector<T>(list) {}
#else
using std::vector<T>::vector; // inheriting constructor
#endif
T& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
const T& operator[](unsigned int i) const
{
if (i<0||this->size()<=i) throw Range_error(i);
return std::vector<T>::operator[](i);
}
};
// disgusting macro hack to get a range checked vector:
#define vector Vector
// trivially range-checked string (no iterator checking):
struct String : std::string {
using size_type = std::string::size_type;
// using string::string;
char& operator[](unsigned int i) // rather than return at(i);
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
const char& operator[](unsigned int i) const
{
if (i<0||size()<=i) throw Range_error(i);
return std::string::operator[](i);
}
};
namespace std {
template<> struct hash<String>
{
size_t operator()(const String& s) const
{
return hash<std::string>()(s);
}
};
} // of namespace std
struct Exit : runtime_error {
Exit(): runtime_error("Exit") {}
};
// error() simply disguises throws:
inline void error(const string& s)
{
throw runtime_error(s);
}
inline void error(const string& s, const string& s2)
{
error(s+s2);
}
inline void error(const string& s, int i)
{
ostringstream os;
os << s <<": " << i;
error(os.str());
}
template<class T> char* as_bytes(T& i) // needed for binary I/O
{
void* addr = &i; // get the address of the first byte
// of memory used to store the object
return static_cast<char*>(addr); // treat that memory as bytes
}
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
inline void keep_window_open(string s)
{
if (s=="") return;
cin.clear();
cin.ignore(120,'\n');
for (;;) {
cout << "Please enter " << s << " to exit\n";
string ss;
while (cin >> ss && ss!=s)
cout << "Please enter " << s << " to exit\n";
return;
}
}
// error function to be used (only) until error() is introduced in Chapter 5:
inline void simple_error(string s) // write ``error: s and exit program
{
cerr << "error: " << s << '\n';
keep_window_open(); // for some Windows environments
exit(1);
}
// make std::min() and std::max() accessible on systems with antisocial macros:
#undef min
#undef max
// run-time checked narrowing cast (type conversion). See ???.
template<class R, class A> R narrow_cast(const A& a)
{
R r = R(a);
if (A(r)!=a) error(string("info loss"));
return r;
}
// random number generators. See 24.7.
inline int randint(int min, int max) { static default_random_engine ran; return uniform_int_distribution<>{min, max}(ran); }
inline int randint(int max) { return randint(0, max); }
//inline double sqrt(int x) { return sqrt(double(x)); } // to match C++0x
// container algorithms. See 21.9.
template<typename C>
using Value_type = typename C::value_type;
template<typename C>
using Iterator = typename C::iterator;
template<typename C>
// requires Container<C>()
void sort(C& c)
{
std::sort(c.begin(), c.end());
}
template<typename C, typename Pred>
// requires Container<C>() && Binary_Predicate<Value_type<C>>()
void sort(C& c, Pred p)
{
std::sort(c.begin(), c.end(), p);
}
template<typename C, typename Val>
// requires Container<C>() && Equality_comparable<C,Val>()
Iterator<C> find(C& c, Val v)
{
return std::find(c.begin(), c.end(), v);
}
template<typename C, typename Pred>
// requires Container<C>() && Predicate<Pred,Value_type<C>>()
Iterator<C> find_if(C& c, Pred p)
{
return std::find_if(c.begin(), c.end(), p);
}
#endif //H112
Error C2440 Build 'return': cannot convert from 'std::ifstream' to 'bool' Win32Project1 C:\Users\Leonardo\Documents\Visual Studio 2015\Projects\Win32Project1\Win32Project1\Graph.cpp 371
I suspect you're running into a breaking change introduced by C++11. The code appears to be this:
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return ff;
}
The code used to work by using operator void * to cast ff from an istream to a void * which could then be cast to a bool. If the ifstream was bad the cast to void * would result in a null pointer which in turn would be treated as bool false.
But C++11 introduces an explicit operator bool() for streams (and gets rid of the void * operator?). Since the bool operator is explicit the operator won't be used for an implicit cast.
To get can_open to compile with the C++11 version of streams you need to make the cast explicit:
bool can_open(const string& s)
// check if a file named s exists and can be opened for reading
{
ifstream ff(s.c_str());
return (bool)ff;
}
However that change will break the code if it is compiled with a pre-C++11 version of streams.
Related
no instance of overloaded function "search" matches the argument list
I have the following problem with my search function. It expects 3 parameters, and one of them is something like const rational_t* v. I want to pass a vector through that parameter but it doesnt seems to work.. Code: #include <iostream> #include <cmath> #include <vector> #include "rational_t.hpp" using namespace std; bool search(const rational_t* v, const int n, const rational_t& x) { for(int i = 0; i < n; i++) { if(v[i].value() == x.value()) { return true; } else { return false; } } }; int main() { rational_t a(1, 2), b(3), c, d(1, 2); vector<rational_t> v; v.push_back(a); v.push_back(b); v.push_back(c); cout << "a.value()= " << a.value() << endl; cout << "b.value()= " << b.value() << endl; cout << "c.value()= " << c.value() << endl; cout << search(v, v.size(), d); // Problem here return 0; } I´ve also tried cout << search(v&, v.size(), d); with the reference &. Any ideas? Thank You. The class : #pragma once #include <iostream> #include <cassert> #include <cmath> #define EPSILON 1e-6 using namespace std; class rational_t { int num_, den_; public: rational_t(const int = 0, const int = 1); ~rational_t() {} int get_num() const { return num_; } int get_den() const { return den_; } void set_num(const int n) { num_ = n; } void set_den(const int d) { assert(d != 0), den_ = d; } double value(void) const; rational_t opposite(void) const; rational_t reciprocal(void) const; bool equal(const rational_t &r, const double precision = EPSILON) const; bool greater(const rational_t &r, const double precision = EPSILON) const; bool less(const rational_t &r, const double precision = EPSILON) const; bool cero_equal(const double precision) const; void write(ostream &os = cout) const; void read(istream &is = cin); };
The first argument of search should be a rational_t* but you're passing a vector<rational_t>. You want search(v.data(), v.size(), d) instead of search(v, v.size(), d) But I'd write this like this which is cleaner IMO: bool search(vector<rational_t> & v, const rational_t& x) { for (int i = 0; i < v.size(); i++) { if (v[i].value() == x.value()) { return true; } else { return false; } } } ... cout << search(v, d);
Issues creating a vector of class object in c++
I created the following class #include "cliques.h" #include "vector" #include <iostream> using namespace std; cliques::cliques(){ } cliques::cliques(int i) { clique.push_back(i); clique_prob = 1; mclique_prob = 1; } cliques::cliques(const cliques& orig) { } cliques::~cliques() { } void cliques::addvertex(int i) { clique.push_back(i); } double cliques::getclique_prob() const { return clique_prob; } double cliques::getMaxclique_prob() const { return mclique_prob; } void cliques::showVertices() { for (vector<int>::const_iterator i = clique.begin(); i !=clique.end(); ++i) cout << *i << ' '; cout << endl; } vector<int> cliques::returnVector() { return clique; } void cliques::setclique_prob(double i) { clique_prob = i; } void cliques::setMaxclique_prob(double i) { mclique_prob = i; } Here's the header file #include "vector" #ifndef CLIQUES_H #define CLIQUES_H class cliques { public: void addvertex(int i); cliques(); cliques(int i); cliques(const cliques& orig); virtual ~cliques(); double getclique_prob() const; double getMaxclique_prob() const; void showVertices(); std::vector<int> returnVector(); void setclique_prob(double i); void setMaxclique_prob(double i); private: float clique_prob; float mclique_prob; std::vector <int> clique; }; #endif /* CLIQUES_H */ I want to create a vector of these objects in order to implement a heap int main(int argc, char** argv) { cliques temp(1); cliques temp1(2); temp.setclique_prob(0.32); temp.setclique_prob(0.852); temp.showVertices(); temp1.showVertices(); vector <cliques> max_heap; max_heap.push_back(temp); max_heap.push_back(temp1); double x =max_heap.front().getclique_prob(); cout<<"prob "<<x<<endl; cliques y = max_heap.front(); y.showVertices(); //make_heap (max_heap.begin(),max_heap.end(),max_iterator()); //sort_heap (max_heap.begin(),max_heap.end(),max_iterator()); return 0; } For reasons unknown to me none of my class functions work properly after i create my vector, meaning that while the following function works as intended temp.showVertices() the next one doesn't, y.showVertices()
You miss implementation for cliques::cliques(const cliques& orig) { } STL vector uses copy constructor inside when you add values to it. As your cliques class does not allocate any memory, you can just remove the copy constructor from the code and compiler will generate one for you.
Using a shader in The Foundry Nuke
Is there a way to apply the shader in plugin? I'm trying to implement anti-aliasing, but all my attempts failed :\
Use this simple: #include <fstream> #include <sstream> #include "DDImage/Knobs.h" #include "DDImage/DDMath.h" #include "DDImage/ViewerContext.h" #include "DDImage/Iop.h" #include "DDImage/PixelIop.h" #include "DDImage/Row.h" using namespace DD::Image; //////////////////////////////////////////////////////////////// /// GPU File Shader Op. class GPUFileShader : public DD::Image::PixelIop { const char* shaderFile_; std::string currShaderFile_; std::string shader_; int version_; int currVersion_; const char* gpuEngine_body() const { return shader_.c_str(); } void pixel_engine(const Row& in, int y, int x, int r, ChannelMask channels, Row& out) { foreach(z, channels) { const float* inptr = in[z] + x; const float* END = inptr + (r - x); float* outptr = out.writable(z) + x; while (inptr < END) *outptr++ = *inptr++; } } void in_channels(int, DD::Image::ChannelSet& c) const { } // return c unchanged public: GPUFileShader(Node* node) : PixelIop(node) , shaderFile_(0) , version_(0) , currVersion_(0) { } void knobs(Knob_Callback f) { File_knob(f, &shaderFile_, "shader_file", "OpenGL Shading Language file"); } void _validate(bool) { if (!shaderFile_) return; if (version_ != currVersion_ || currShaderFile_ != std::string(shaderFile_)) { std::ifstream ifs(shaderFile_); if (!ifs) { Iop::error("Error reading shader file."); return; } std::stringstream str; std::copy(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(str)); shader_ = str.str(); currVersion_ = version_; currShaderFile_.assign(shaderFile_); } copy_info(0); } static const DD::Image::Op::Description d; const char* Class() const { return d.name; } const char* node_help() const { return "GPU Op which gets initialised from a file. Customise for proprietary formats. Default assumes OpenGL shading language code."; } }; static Op* GPUFileShader_c(Node* node) { return new GPUFileShader(node); } const Op::Description GPUFileShader::d("GPUFileShader", GPUFileShader_c);
C++ std::vector iterators error
First of all I'm sorry for my bad english, hope you guys will understand me :) Im writing WinAPI game and my classes behave very strange: all operations with vector crash my program so Windows says that my .exe stopped working. But when I debug these lines I get exceptions. This is how my class header looks like: #ifndef FIGURE_H_INCLUDED #define FIGURE_H_INCLUDED #include <vector> #include <Windows.h> #include "Other.h" using namespace std; enum Figure_Type { I, J, L, O, S, T, Z }; class Figure { public: /* CONSTRUCTORS */ Figure(); Figure(Figure_Type); /* MOVEMENT */ bool Move(vector<Cell>&, Direction&); void Drop(vector<Cell>&); bool Rotate(vector<Cell>&); /* OTHER */ void Draw(HDC&); private: /* METHODS */ void Generate(); void GenerateMasks(); void GenerateFigure(); Figure GetFigureCopy() const; /* DATA */ Shift shift; char mask[4][4]; vector<Cell> vCells; Figure_Type type; int rotation; }; #endif My constructors are using Generate() method, which code is: void Figure::GenerateFigure() { vCells.clear(); int defPosX = 4, defPosY = 20; Cell cell; for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { if(mask[y][x] == '0') { cell.x = defPosX + x + shift.dx; cell.y = defPosY - y + shift.dy; vCells.push_back(cell); } } } } And I'm getting exceptions on vCells.clear() method and (if I comment first line) vCells.push_back(cell) line. Actually every operation with vector / vector iterators crash my program even incrementing iterator, those are just the first so my code isn't running any longer after them. Exception text: "Unhandled exception at 0x5A4ACCD2 (msvcp110d.dll) in Tetris_completely_new.exe: 0xC000041D: An unhandled exception was encountered during a user callback." And these exceptions are thrown on 217's line of "xutility". I commented it: .... // MEMBER FUNCTIONS FOR _Container_base12 inline void _Container_base12::_Orphan_all() { // orphan all iterators #if _ITERATOR_DEBUG_LEVEL == 2 if (_Myproxy != 0) { // proxy allocated, drain it _Lockit _Lock(_LOCK_DEBUG); for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter; *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter) **(*_Pnext)->_Myproxy = 0;** // <------------ THIS LINE _Myproxy->_Myfirstiter = 0; } #endif /* _ITERATOR_DEBUG_LEVEL == 2 */ } .... Here is how my Cell struct looks like: struct Cell { Cell() : x(1), y(1) { } Cell(int _x, int _y): x(_x), y(_y) { } void Draw(HDC&) const; bool operator ==(const Cell& a) const { return (x == a.x && y == a.y); } bool operator !=(const Cell& a) const { return !(*this == a); } int x; int y; }; And Figure constructor: Figure::Figure() { srand(time(NULL)); vCells.clear(); type = Figure_Type(rand() % 7); rotation = 0; shift.dx = 0; shift.dy = 0; Generate(); }
You're likely invoking undefined behaviour. Without any more information, I'd say you're calling instance methods through stale object references/pointers (a reference taken at the time of callback registration is no longer valid?). Also, as currently written in the question, you're generating a figure based on unitialized bytes in mask, so you'd likely want to initialize these too. Here's a take on oa slightly modernized/cleaned up version. Note the use of initializer lists uniform initialization reordered member initialization not using using namespace in headers moved srand into main instead of the constructor See it Live on Coliru #ifndef FIGURE_H_INCLUDED #define FIGURE_H_INCLUDED #include <vector> #ifdef _WIN32 # include <Windows.h> # include "Other.h" #else # include <cstdint> # include <cstdlib> # include <ctime> using HDC = uint32_t; #endif struct Cell { Cell(int _x=1, int _y=1): x(_x), y(_y) { } void Draw(HDC&) const; bool operator ==(const Cell& a) const { return (x == a.x && y == a.y); } bool operator !=(const Cell& a) const { return !(*this == a); } int x; int y; }; struct Shift { Shift(int dx=0, int dy=0) : dx(dx), dy(dy) {} int dx, dy; }; enum class Direction { up, down, left, right }; enum Figure_Type { I, J, L, O, S, T, Z }; class Figure { public: /* CONSTRUCTORS */ Figure(); Figure(Figure_Type); /* MOVEMENT */ bool Move(std::vector<Cell>&, Direction&); void Drop(std::vector<Cell>&); bool Rotate(std::vector<Cell>&); /* OTHER */ void Draw(HDC&); private: /* METHODS */ void Generate(); void GenerateMasks(); void GenerateFigure(); Figure GetFigureCopy() const; /* DATA */ char mask[4][4]; std::vector<Cell> vCells; Figure_Type type; int rotation; Shift shift; }; #endif /* * And I'm getting exceptions on vCells.clear() method and (if I comment first * line) vCells.push_back(cell) line. Actually every operation with vector / * vector iterators crash my program even incrementing iterator, those are just * the first so my code isn't running any longer after them. * * Exception text: * **"Unhandled exception at 0x5A4ACCD2 (msvcp110d.dll) in * Tetris_completely_new.exe: 0xC000041D: An unhandled exception was * encountered during a user callback."** * * And these exceptions are thrown on 217's line of "xutility". I commented it: * * .... * // MEMBER FUNCTIONS FOR _Container_base12 * inline void _Container_base12::_Orphan_all() * { // orphan all iterators * #if _ITERATOR_DEBUG_LEVEL == 2 * if (_Myproxy != 0) * { // proxy allocated, drain it * _Lockit _Lock(_LOCK_DEBUG); * * for (_Iterator_base12 **_Pnext = &_Myproxy->_Myfirstiter; * *_Pnext != 0; *_Pnext = (*_Pnext)->_Mynextiter) * **(*_Pnext)->_Myproxy = 0;** // <------------ THIS LINE * _Myproxy->_Myfirstiter = 0; * } * #endif // _ITERATOR_DEBUG_LEVEL == 2 * } * .... * * Here is how my **Cell struct** looks like: */ //And **Figure constructor**: Figure::Figure() : mask {{0}}, vCells(), type((Figure_Type) (rand() % 7)), rotation(0), shift({0,0}) { Generate(); } //My constructors are using Generate() method, which code is: void Figure::Generate() { GenerateFigure(); } void Figure::GenerateFigure() { vCells.clear(); for(int y = 0; y < 4; y++) { for(int x = 0; x < 4; x++) { if(mask[y][x] == '0') vCells.push_back({4 + x + shift.dx, 20 - y + shift.dy}); } } } int main() { srand(time(0)); Figure fig1; Figure fig2; }
expected an identifier c++
I am trying to write a class and I finally got it to compile, but visual studio still shows there are errors (with a red line). The problem is at (I wrote #problem here# around the places where visual studio draws a red line): 1. const priority_queue<int,vector<int>,greater<int> #># * CM::getHeavyHitters() { 2. return & #heavyHitters# ; 3. } And it says: "Error: expected an identifier" (at the first line) "Error: identifier "heavyHitters" is undefined" (at the second line) The first problem I don't understand at all. The second one I don't understand because heavyHitters is a a member of CM and I included CM. BTW, I tried to build. It didn't fix the problem. Thanks!!! The whole code is here: Count-Min Sketch.cpp #include "Count-Min Sketch.h" CM::CM(double eps, double del) { } void CM::update(int i, int long unsigned c) { } int long unsigned CM::point(int i) { int min = count[0][calcHash(0,i)]; return min; } const priority_queue<int,vector<int>,greater<int>>* CM::getHeavyHitters() { return &heavyHitters; } CM::CM(const CM &) { } CM::~CM() { } int CM::calcHash(int hashNum, int inpt) { int a = hashFunc[hashNum][0]; int b = hashFunc[hashNum][1]; return ((a*inpt+b) %p) %w; } bool CM::isPrime(int a) { bool boo = true; return boo; } int CM::gePrime(int n) { int ge = 2; return ge; } Count-Min Sketch.h #pragma once #ifndef _CM_H #define _CM_H using namespace std; #include <queue> class CM { private: // d = ceiling(log(3,1/del)), w = ceiling(3/eps) int d,w,p; // [d][w] int long unsigned *(*count); // [d][2] int *(hashFunc[2]); // initialized to 0. norm = sum(ci) int long unsigned norm; // Min heap priority_queue<int,vector<int>,greater<int>> heavyHitters; // ((ax+b)mod p)mod w int calcHash(int hashNum, int inpt); // Is a a prime number bool isPrime(int a); // Find a prime >= n int gePrime(int n); public: // Constructor CM(double eps, double del); // count[j,hj(i)]+=c for 0<=j<d, norm+=c, heap update & check void update(int i, int long unsigned c); // Point query ai = minjcount[j,hj(i)] int long unsigned point(int i); const priority_queue<int,vector<int>,greater<int>>* getHeavyHitters(); // Copy constructor CM(const CM &); // Destructor ~CM(); }; #endif // _CM_H
>> is a single token, the right-shift (or extraction) operator. Some compilers don't recognize it correctly in nested template specialization. You have to put a space between the two angle brackets like this: Type<specType<nestedSpecType> > ident; ^^^