samedi 28 février 2015

C++ Assign GradeBook

Hi and thanks in advanced. I'm working on this H.W. and I'm beginner. I keep on running on in M.S. VS Professional but keeps returning too many errors and I fix them, yet same issues not sure if what I had added to the code is wrong. The results should display its takes no more than 30 char. it should display total number of students received a grade, the average, and class average in one digit double value and GPA. Here is the code:



#include <iostream>
#include "GradeBook.h" // include definition of class GradeBook
using namespace std;

// constructor initializes courseName with string supplied as argument;
// initializes counter data members to 0
GradeBook::GradeBook(string name)
{
cout << "The Grade Book Constructor is called" << endl;
setCourseName(name); // validate and stores courseName
aCount = 0; // initialize count of A grades to 0
bCount = 0; // initialize count of B grades to 0
cCount = 0; // initialize count of C grades to 0
dCount = 0; // initialize count of D grades to 0
fCount = 0; // initialize count of F grades to 0
displayMessage();
cout << "The Grade Book," << getCourseName() << "Contains" << endl << endl < endl;
displatGradeReport(0);
cout << "*****The end of Grade Book Constructor.*****" << endl;
} // end GradeBook constructor

// function to set the course name; limits name to 25 or fewer characters
void GradeBook::setCourseName( string name )
{
if ( name.size() <= 30 ) // if name has 30 or fewer characters
courseName = name; // store the course name in the object
else // if name is longer than 30 characters
{ // set courseName to first 30 characters of parameter name
courseName = name.substr( 0, 30 ); // select first 25 characters
cerr << "Name \"" << name << "\" exceeds maximum length (30).\n"
<< "Limiting courseName to first 30 characters.\n" << endl;
} // end if...else
} // end function setCourseName

// function to retrieve the course name
string GradeBook::getCourseName()
{
return courseName;
} // end function getCourseName

// display a welcome message to the GradeBook user
void GradeBook::displayMessage()
{
// this statement calls getCourseName to get the
// name of the course this GradeBook represents
cout << "Welcome to the grade book for\n" << getCourseName() << "!\n"
<< endl;
} // end function displayMessage

// input arbitrary number of grades from user; update grade counter
void GradeBook::inputGrades()
{
int grade; // grade entered by user

cout << "Enter the letter grades." << endl;
cout << "Enter the EOF character to end input." << endl;
cout << "Use Ctl + D, or Ctl + Z)" << endl;

// loop until user types end-of-file key sequence
while ( ( grade = cin.get() ) != EOF )
{
// determine which grade was entered
switch ( grade ) // switch statement nested in while
{
case 'A': // grade was uppercase A
case 'a': // or lowercase a
++aCount; // increment aCount
break; // necessary to exit switch

case 'B': // grade was uppercase B
case 'b': // or lowercase b
++bCount; // increment bCount
break; // exit switch

case 'C': // grade was uppercase C
case 'c': // or lowercase c
++cCount; // increment cCount
break; // exit switch

case 'D': // grade was uppercase D
case 'd': // or lowercase d
++dCount; // increment dCount
break; // exit switch

case 'F': // grade was uppercase F
case 'f': // or lowercase f
++fCount; // increment fCount
break; // exit switch

case '\n': // ignore newlines,
case '\t': // tabs,
case ' ': // and spaces in input
break; // exit switch

default: // catch all other characters
cout << "****Incorrect letter grade entered.****" << endl;
cout << " Enter a new grade." << endl;
break; // optional; will exit switch anyway
} // end switch
} // end while
} // end function inputGrades

// display a report based on the grades entered by user
void GradeBook::displayGradeReport()
{
// output summary of results
// total grades
int gradeCount = aCount + bCount + cCount + dCount + fCount;
cout << "\n\nThe total number of students receive grade is" << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl;
} // end calculate number of grades received

// display class average
// if user entered at least one grade
if (gradeCount != 0)
{
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
} // end if
} // end function displayGradeReport
void GradeBook::displayGradeReport(int n)
{
// display summary of results
// calculate total grades
int gradeCount = aCount = bCount = cCount = dCount = fCount = n;
cout << "The total number of students receive grades is " << gradeCount << endl;
cout << "Number of students who received each letter grade:"
<< "\nA: " << aCount // display number of A grades
<< "\nB: " << bCount // display number of B grades
<< "\nC: " << cCount // display number of C grades
<< "\nD: " << dCount // display number of D grades
<< "\nF: " << fCount // display number of F grades
<< endl << endl;

// calculate total grades


// display class average
// calculate total grades
int gradeTotal = 4 * aCount + 3 * bCount + 2 * cCount + 1 * dCount;

// set floating-point number format
cout << fixed << setprecision(1);

// compute and display class GPA with 1 digit of precision
if (gradeCount != 0)
{
cout << "\nThe class average is: "
<< static_cast< double > (gradeTotal) / gradeCount
<< endl << endl << endl;
}
else
{
cout << "\nThe class average is: 0.0" << endl << endl << endl;
}
} // end function displayGradeReport


Here is the .h



#include <string> // program uses C++ standard string class
using namespace std;

// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook


And here is the file I'm executing from in the project


include // program uses C++ standard string class


using namespace std;



// GradeBook class definition
class GradeBook
{
public:
GradeBook( string ); // initialize course name
void setCourseName( string ); // set the course name
string getCourseName(); // retrieve the course name
void displayMessage(); // display a welcome message
void inputGrades(); // input arbitrary number of grades from user
void displayGradeReport(); // display report based on user input
private:
string courseName; // course name for this GradeBook
int aCount; // count of A grades
int bCount; // count of B grades
int cCount; // count of C grades
int dCount; // count of D grades
int fCount; // count of F grades
}; // end class GradeBook

C++11 memory model: why can't compiler move statements across load() operations during optimization?

As I understand, for the sequentially consistent and acquire-release memory models if some x.store(some_value) operation from one thread is synchronized with a x.load() operation from the another one, then:


Rule 1. All memory operations that happen before the x.store(some_value) operation must appear before the x.load() operation.


This point seems clear to me:



-Thread 1-
y = 1;
x.store(2, memory_order_release);

-Thread 2-
if (x.load(memory_order_acquire) == 2)
assert(y == 1)


Here if the compiler places y = 1 operation after x.store(2), assert can fail and this is not the behavior that we expect.


Rule 2. All memory operations that happen after the x.load() operation must also appear after the x.store(some_value) operation.


But now I'm confused: why can't the compiler move the statements across load() operations? How can it violate the expected behavior of the program? I think of a such example:



-Thread 1-
x.store(2, memory_order_release); // x == 0 initially

-Thread 2-
while (x.load(memory_order_acquire) == 1);
y = 2; // y == 0 initially


Here, if compiler places y = 2 operation before while(), y becomes 2 (otherwise there is the infinite loop and y stays unchanged), but this example seems forced (I'm even not sure that compiler can do such "optimization"), and I suspect that there are more realistic situations for which Rule 2 was created.


Could you please give me the explanation of the Rule 2's necessity?


PROBLEMS MAKING IT WORK

I'm having trouble making it work. I'm taking class on cpp and this is my assignment. I'm wodnering why it doesnt work



#include <iostream>
using namespace std;

Class thing ( integer argu(flt float) ) {
static auto integer FLOAT____ = * 4;
return this -> std::iostream; // default destructor
};

thing::return(44) == 32 if (self.this == <-this)

float main (void arg) {
return thing.return if this-> main == (*this)thing
else return static;
}

How to derive from a variadic template class in C++

I have variadic template class which is just a wrapper for std::tuple :



template <typename ... Child>
class Tpl
{
public:
Tpl() {}
Tpl(Child ...args) : child(args...)
{}

template <typename T>
T& Get()
{
return std::get<T>(child);
}

template <typename T>
const T& GetConst()
{
return std::get<T>(child);
}
private:
std::tuple<Child ...> child;
};


How do I correctly derive a class from Tpl?



template <typename... Ts>
class SomeObject : public Tpl<Ts...>
{
public:
Some(/*Types ... args*/) /*: child(args...)*/
{

}
private:
int num;
};


The compiler message just tells me: "syntax error: missing ',' before '<' in the line: class DbgGameObject : public Tpl


Thanks for your help!


Ambiguous base class conversion with a compressed pair

So I tried creating a compressed pair using the empty base optimization. I would like it such that if class a and b are empty then compressed_pair<a, b> is empty as well. So I defined my compressed pair something like this:



template <class First, class Second>
struct compressed_pair : First, Second
{
compressed_pair() {}
compressed_pair(const First& x, const Second & y)
: First(x), Second(y)
{}
First& first() { return *this; }
Second& second() { return *this; }
};


However, if one of the types inherit from the other it becomes ambiguous. For example, when I compile this program:



struct a
{};

struct b : a
{};

int main()
{
compressed_pair<a, b> p;
auto x = p.first();
}


I get this error from clang:



compressed_pair.cpp:8:30: error: ambiguous conversion from derived class 'compressed_pair<a, b>' to base class 'a':
struct compressed_pair<struct a, struct b> -> struct a
struct compressed_pair<struct a, struct b> -> struct b -> struct a
First& first() { return *this; }
^~~~~
compressed_pair.cpp:21:16: note: in instantiation of member function 'compressed_pair<a, b>::first' requested here
auto x = p.first();
^


So how can I avoid the ambiguous conversion and still have compressed_pair<a, b> be empty?


std::find_if for custom objects returns bad iterator when vector has at least 1 element

So I have a vector of objects of type Player. If I try to use std::find_if on that vector and use a lambda expression that return true only if the name if the player is a name I want to check against, it will work the first time if the vector is empty (as in the iterator is nullptr), but once I add a Player object in the vector, the find_if will return an iterator filled with random, bad data.


My code:



auto player = find_if(m_playerList.begin(), m_playerList.end(), [name](Player& p)
{
return p.Name == name;
});

if (player._Ptr != nullptr)
{
// Do stuff
}

else
{
Player newPlayer;
newPlayer.Name = name;
m_playerList.push_back(newPlayer);
}


So in the first iteration of this function, the player is nullptr, because the vector didn't contain any elements. In the second iteration, if I search by the same name, it finds it in the vector, however if I search by a different name, it returns an object with mangled, random data and the check "if (player._Ptr != nullptr)" passes.


Question is, what causes this? Am I checking the "player" object properly to figure out if the find_if actually found a valid object in the vector?


C++ Launching programs with system() not giving desired results

I have a C++ code setup that launches items for me, all i have to do is input the name and it launches. The Problem is that when I have the C++ Application launch it the C++ Application "turns into it" By that i mean pretend i'm using it launch a minecraft server. It will act as if the minecraft server was were it was and its make files it needs there Not using the ones in its directory. If anyone can help please do.


(Heres the code)



#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

int main() {
std::string textin;
cin >> textin;
if ( textin == "ATLauncher" ) {
system ("C:\\users\\USER\\Main\\minecraftserver\\minecraftserver.exe");
return 0;
}
}

unique_ptr with standard containers: attempting to reference a deleted function

I'm trying to use unique_ptr with any stl container (actually list is prefer for me), I see that unique_ptr requires move semantics . this code where employee is a base class:



typedef std::unique_ptr<employee> p_employee;

std::list<p_employee> make_test_array() {
std::list<p_employee> objects = {
p_employee(new accounter(...)),
p_employee(new engineer(...)),
p_employee(new developer(...))
};

return objects;
}


you see what I'm trying to do - just a return this list from a function


so is there ability to do this? what is a right technique?


Why can't the linker find these functions? [duplicate]


This question already has an answer here:




In base.h I have:



class MyType {};

class Base {
public:
Base(MyType const& t);
MyType t;
};

template <typename T>
class Derived1 : public Base {
public:
Derived1(MyType const& t);
};


In base.cpp I have



#include "Base.h"

Base::Base(MyType const& t) : t(t) {

}

template<typename T>
Derived1<T>::Derived1(MyType const& t) : Base(t) {

}


In derived.h I have:



#include "Base.h"

class Derived2 : public Derived1<int> {
public:
Derived2(MyType const& t);
};


In derived.cpp I have:



#include "Derived.h"

Derived2::Derived2(MyType const& t) : Derived1<int>(t){

}


Yet the linker is telling me that



Derived1<int>::Derived1(MyType const&)


is an undefined symbol. Why doesn't the constructor I have for Derived1 count?


"Compilation failed." geany c++11 windows 8.1

I try to compile a small program in C + + but the compilation failed! Here's the code:



#include <iostream>
#include <vector>

int main()
{
std::vector<std::vector<double>> matrice { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

std::cout << "Bonjour, voici une matrice:" << std::endl;
for (auto element : matrice) {
for (auto val : element) {
std::cout << val << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;

return 0;


I installed MinGW on Windows


under Geany:



g++ -std=c++11 -Wall -c "%f"
g++ -std=c++11 -Wall -o "%e" "%f"

But the compilation failed


Thank you in advance for your help.


Error: "Mixed implicit and static pattern rules" in my Makefile

I had a working Makefile for small C++ applications that just had a couple of source code files inside a single folder that was also the output folder. Now I am trying to separate source and object files and ran into a problem. This is how my makefile looks right now, I'll go into detail where the problem occurs below.



CC = gcc
CXX = g++
RM = del

TARGET = plox.exe

CFLAGS = -Wall -ggdb -O3 $(INCLUDE)
CXXFLAGS = -std=c++11 -Wall -ggdb -O3 $(INCLUDE)
LDFLAGS = $(LIB) -lglfw3 -lopengl32 -lglu32 -lgdi32

INCLUDE = -I$(GLFW_INC) -I$(GLAD_INC)
LIB = -L$(GLFW_LIB)

SRC_DIR = src
BUILD_DIR = build

GLFW_DIR = d:/external/glfw-3.1
GLFW_INC = $(GLFW)/include
GLFW_LIB = $(GLFW)/lib64

GLAD = d:/external/glad-c
GLAD_INC = $(GLAD)/include

CXX_SOURCES = $(SRC_DIR)/%.cpp
CXX_OBJS = $(addprefix $(BUILD_DIR)/, $(CXX_SOURCES:.cpp=.o))
OBJS = $(CXX_OBJS) $(BUILD_DIR)/glad.o

all: $(TARGET)

$(TARGET): $(OBJS)
$(CXX) -o $@ $^ $(LDFLAGS)

$(CXX_OBJS): %.o: $(SRC_DIR)%.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<

$(BUILD_DIR)/glad.o: src/glad.c
$(CC) -c $(CFLAGS) -c -o $(BUILD_DIR)/glad.o $(SRC_DIR)/glad.c

.PHONY: clean

clean:
$(RM) $(TARGET) $(OBJS)


The problem is in the line:



$(CXX_OBJS): %.o: $(SRC_DIR)/%.cpp


Before my changes, it looked like this:



$(CXX_OBJS): %.o: %.cpp


A friend helped gave me a template and I never really knew what that line really does. In another thread I learned that this is a static pattern rule so I guess this is where I made the mistake. But writing it down just now, I think the error could be earlier already. I might have made a mistake when defining $(CXX_OBJS). Could it be that the objects in that list are of the form build/src/test.o instead of build/test.o?


But how can I fix the addprefix line to produce the correct output? And where does the error in the title come from; where am I mixing those? I thought it could be about the $(SRC_DIR) in the static pattern rule because I probably misunderstood how it worked, but omitting it doesn't make the error go away. Moreover (assuming CXX_OBJS is working correctly later), if the static pattern rule checks every file in the list $(CXX_OBJS) for a match with %.o, and then has a dependency on the same file with ending .cpp, then that is also not correct because of the build folder prefix.


All in all, I'm very confused about how to handle the folder prefixes correctly and any advice is greatly appreciated!


C++ Pimpl Idiom Imcomplete Type using std::unique_ptr

I apologize for the large amount of code required to demonstrate the issue. I am having a problem using the pimpl idiom with std::unique_ptr. Specifically the problem seems to occur when one class (which has pimpl'ed implementation) is used as member data in another composite class with pimpl'ed implementation.


Most of the answers I've been able to find deal with a lack of explicit destructor declaration, but as you can see here, I have declared and defined the destructors.


What is wrong with this code, and can it be modified to compile without changing the design?


Note: the error seems to occur in the definition of SomeComposite::getValue() and that the compiler cannot see the error until compile time. The error is encountered in memory.h and the message is Invalid application of 'sizeof' to an incomplete type 'pimplproblem::SomeInt::impl'.


SomeInt.h



#pragma once
#include <iostream>
#include <memory>

namespace pimplproblem
{
class SomeInt
{

public:
explicit SomeInt( int value );
SomeInt( const SomeInt& other ); // copy
SomeInt( SomeInt&& other ) = default; // move
virtual ~SomeInt();
SomeInt& operator=( const SomeInt& other ); // assign
SomeInt& operator=( SomeInt&& other ) = default; // move assign
int getValue() const;

private:
class impl;
std::unique_ptr<impl> myImpl;
};
}


SomeInt.cpp



#include "SomeInt.h"

namespace pimplproblem
{
class SomeInt::impl
{
public:
impl( int value )
:myValue( value )
{}

int getValue() const
{
return myValue;
}
private:
int myValue;
};

SomeInt::SomeInt( int value )
:myImpl( new impl( value ) )
{}

SomeInt::SomeInt( const SomeInt& other )
:myImpl( new impl( other.getValue() ) )
{}

SomeInt::~SomeInt()
{}

SomeInt& SomeInt::operator=( const SomeInt& other )
{
myImpl = std::unique_ptr<impl>( new impl( other.getValue() ) );
return *this;
}

int SomeInt::getValue() const
{
return myImpl->getValue();
}
}


SomeComposite.h



#pragma once
#include <iostream>
#include <memory>
#include "SomeInt.h"

namespace pimplproblem
{
class SomeComposite
{

public:
explicit SomeComposite( const SomeInt& value );
SomeComposite( const SomeComposite& other ); // copy
SomeComposite( SomeComposite&& other ) = default; // move
virtual ~SomeComposite();
SomeComposite& operator=( const SomeComposite& other ); // assign
SomeComposite& operator=( SomeComposite&& other ) = default; // move assign
SomeInt getValue() const;

private:
class impl;
std::unique_ptr<impl> myImpl;
};
}


SomeComposite.cpp



#include "SomeComposite.h"

namespace pimplproblem
{
class SomeComposite::impl
{
public:
impl( const SomeInt& value )
:myValue( value )
{}

SomeInt getValue() const
{
return myValue;
}
private:
SomeInt myValue;
};

SomeComposite::SomeComposite( const SomeInt& value )
:myImpl( new impl( value ) )
{}

SomeComposite::SomeComposite( const SomeComposite& other )
:myImpl( new impl( other.getValue() ) )
{}

SomeComposite::~SomeComposite()
{}

SomeComposite& SomeComposite::operator=( const SomeComposite& other )
{
myImpl = std::unique_ptr<impl>( new impl( other.getValue() ) );
return *this;
}

SomeInt SomeComposite::getValue() const
{
return myImpl->getValue();
}
}

C++: file.seekg does not behave correctly if the ifstream is passed to a function in a different file

I am trying to backup a line in an ifstream. file.tellg() is returning a value I was not expecting. In the example bellow, after reading the first line (a string length of 15 characters) I expected file.tellg() to return 16. Instead, it is returning 41. Could someone please provide some insights on this behavior?


test.cpp



#include <fstream>
#include <ios>
#include <string>
#include <iostream>
using namespace std;

int main(){
ifstream file("sample.ics", ios::in);

string line;
string key0;
string key1;
string value0;
string value1;

getline(file, line, '\n');

cout << "line = " << line << endl;
cout << "line.length = " << line.length() << endl; // should be 15;

cout << "Attempt:" << endl;
int pos = file.tellg(); // should be 16;
cout << " pos = " << pos << endl;

getline(file, key0, ':');
getline(file, value0, '\n');

cout << " First:" << endl;
cout << " " << key0 << ":" << value0 << endl;

cout << " backing up..." << endl;
file.seekg(pos, ios_base::beg);

getline(file, key1, ':');
getline(file, value1, '\n');

cout << " Second:" << endl;
cout << " " << key1 << ":" << value1 << endl;

file.close();
}


Output:



line = BEGIN:VCALENDAR
line.length = 15
Attempt:
pos = 41
First:
CALSCALE:GREGORIAN
backing up...
Second:
ION:2.0


sample.ics



BEGIN:VCALENDAR
CALSCALE:GREGORIAN
VERSION:2.0
METHOD:PUBLISH
...

decltype(auto) in new initializer?

In C++11 I can do the following just fine:



auto a = new auto{42};


But none of the following work in any compiler I've tried:



decltype(auto) a = new decltype(auto){42};
auto a = new decltype(auto){42};


How do I use decltype(auto) in a new initializer in C++11?


Class differences between C++03 and C++11

I'm current building an application in which I have a log function that is accessible in most of my classes which was declared as below



#ifndef FILENAME_H
#define FILENAME_H

#pragma once

#include "log.h"

class ClassName {
private:
log LogHandler;
}


This worked fine for a long time and then I wanted to include another function elsewhere in my application that was only compatible with C++11 so I told the compiler to compile to these standards. I was then receiving an error on "log logHandler" saying log is not a declared name.


I was able to resolve the problem by changing the line to



class log logHandler;


I was wondering if anybody could tell me what has changed between C++03 and C++11 that required me to do this?


C++ How To open an application using Text Input and If Statements

Im trying to make a simple application launcher using C++.


I have looked online and i can't find a specific answer i have found multiple questions and items that i have pieced together to make something but i can't get it to work, can anyone help?



#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
int textin;
cin >> textin;
if ( textin == "ATLauncher" ) { system("C:\Users\NAME\Main\minecraftlaunchers\AtLauncher\ATLauncher.exe");
system ("pause");
return 0;
}
}


(Note I'm not used to StackOverFlows formatting so the code may seam "messed up" Also using ")


Compiler error when trying to add constant float3x3 to shader file

I am trying to add this code to my Metal language file:



constant float3x3 rgb2xyz(
float3(0.412453f, 0.212671f, 0.019334f),
float3(0.357580f, 0.715160f, 0.119193f),
float3(0.180423f, 0.072169f, 0.950227f)
);


or this



constant float3x3 rgb2xyz = float3x3(
float3(0.412453f, 0.212671f, 0.019334f),
float3(0.357580f, 0.715160f, 0.119193f),
float3(0.180423f, 0.072169f, 0.950227f)
);


The metal compiler gives me the following error:



No matching constructor for initialization of 'const constant float3x3' (aka 'const constant matrix<float, 3, 3>')


However if I do



typedef struct {
float3x3 matrix;
float3 offset;
float zoom;
} Conversion;

constant Conversion colorConversion = {
.matrix = float3x3(
float3 ( 1.164f, 1.164f, 1.164f ),
float3 ( 0.000f, -0.392f, 2.017f ),
float3 ( 1.596f, -0.813f, 0.000f )
),
.offset = float3 ( -(16.0f/255.0f), -0.5f, -0.5f )
};


I don't get any compile error.


Any ideas what is going wrong? It also works without problems with vector types:



constant float3 bgr2xyzCol1(0.357580f, 0.715160f, 0.119193f);


How would be a good way to define a constant matrix directly in the code?


Memory ordering behavior of std::atomic::load

While I have to admit I don't fully understand the formal definitions of the different relaxed semantics of memory order I thought that the sequentially consistent ordering was pretty straightforward in that it guarantees that "a single total order exists in which all threads observe all modifications in the same order." To me this implies that the std::atomic::load with the default memory order of std::memory_order_seq_cst will also act as a memory fence. This is further corroborated by the following statement under "Sequentially-consistent ordering":


Total sequential ordering requires a full memory fence CPU instruction on all multi-core systems.


Yet, my simple example below demonstrates this is not the case with MSVC 2013, gcc 4.9 (x86) and clang 3.5.1 (x86), where the atomic load simply translates to a load instruction.



#include <atomic>

std::atomic_long al;

#ifdef _WIN32
__declspec(noinline)
#else
__attribute__((noinline))
#endif
long load() {
return al.load(std::memory_order_seq_cst);
}

int main(int argc, char* argv[]) {
long r = load();
}


With gcc this looks like:



load():
mov rax, QWORD PTR al[rip] ; <--- plain load here, no fence or xchg
ret
main:
call load()
xor eax, eax
ret


I'll omit the msvc and clang which are essentially identical. Now on gcc for ARM we get what I expected:



load():
dmb sy ; <---- data memory barrier here
movw r3, #:lower16:.LANCHOR0
movt r3, #:upper16:.LANCHOR0
ldr r0, [r3]
dmb sy ; <----- and here
bx lr
main:
push {r3, lr}
bl load()
movs r0, #0
pop {r3, pc}


Am I wrong to assume that the atomic::load should also act as a memory barrier ensuring that all previous non-atomic writes will become visible by other threads?


This is not an academic question, it results in a subtle race condition in our code which put into question my understanding of the behavior of std::atomic.


count "empty space" right/left in a 2D vector efficiently

I have a grid of the form std::vector< vector<int> > grid (rows, std::vector<double>(columns)); which is a member variable of a class. The grid has stored values from the set {0,1,2, ... , 9}. Imagine if I go through the grid and at every position where grid[row][col] != 0 I need to know how many zeros are to the left and to the right before again grid[newRow][newCol] != 0 is fulfilled (to the left/right means in this row, so one has to iterate through the column index). For the moment I do it with the following two functions:



int countLeft(unsigned int rowIndex, unsigned int colIndex) {
int left = 0;
for (signed int i = colIndex-1; i >= 0; i--) {
if (this->grid[rowIndex][colIndex] != 0 && this->grid[rowIndex][i] == 0){
left++;
}
else
break;
}
return left;
}

int countRight(unsigned int rowIndex, unsigned int colIndex){
int right = 0;
for (unsigned int i = colIndex + 1; i < this->grid[0].size(); i++) {
if (this->grid[rowIndex][i] == 0 && this->grid[rowIndex][colIndex] != 0) {
right++;
}
else
break;
}
return right;
}


Running the Performance wizard on VS2013 I found out that these two functions are slowing down my program significantly. Therefore my question, how I could improve my method of knowing the zeros to the left/right, without counting every time. Thanks in advance.


What are good tools which can help to get rid of C/C++ header files?

Languages like Java or C# do not require header files and do just fine with placing everything in a single source file. So it is obvious that the concept of header files serves little to no purpose and is merely a historical artefact of C/C++ which causes unnecessary complexity and maintainance overhead.


Obviously it would be easier to write C++ code the same way as in Java, placing all the declarations and definitions in the same file. Tools like lzz allow this coding style by parsing a single file for its definitions, then generating the required .h and .cpp files automatically. Unfortunately this tool doesn't seem to be maintained any more and doesn't support C++11.


Are there any alternative tools and/or coding styles which allow for headerless coding with C/C++?


Use template to apply a function template

If the following example were C++ it would contain non-sensical gibberish so I'll define the example to be written in pseudocode (and hence correct). It strongly hints at what I want to do in C++.



#include <vector>

template<class T>
void increment(const T& x)
{
++x;
}

template<template<class> class F>
struct Apply
{
template<class T>
void operator()(std::vector<T>& v)
{
for (auto& x : v)
F<T>(x);
}
};

template<template<class> class F, class T>
void apply(F<T> f, std::vector<T>& v)
{
for (auto& x : v)
f(x);
}

int main()
{
std::vector<int> v{1,2,3};

// apply increment function to v

// maybe this?
Apply<increment> a;
a(v);

// hmm... or this?
apply(increment, v);
}


I don't know how to turn this into C++ such that:




  1. increment is a function and not a function object.




  2. The parameter of increment is either deduced or supplied by Apply/apply.




  3. Apply/apply does not know about the name increment.




I can satisfy two out of the three but I'm not sure how to satisfy all three at once. The problem I run into is the apparent need for using a function template as a template template parameter which my compiler doesn't like. Still, it certainly seems possible to get this to work even if that particular route is off limits.


How can it be done?


The nearest __sync_* alternative to acquire/release semantics?

I'm porting some C++ code to an earlier version of g++ which does not support atomic types (~g++ 4.2)


In my C++11 code, I would use acquire/release semantics to store atomic variables



atomic<int> a;
...
a.load(memory_order_acquire);
// Some operations on 'a'
a.store(new_val, memory_order_release);


Which __sync_* builtin would be the best replacement to the load/store option? I was thinking about using __sync_lock_test_and_set for the store, and __sync_lock_release for load, would this be sufficient?


Somewhat along the lines:



__sync_lock_release(a)
// Some ops on 'a'
__sync_lock_test_and_set(a,new_value);


(I'm trying to solve this without locks, if possible)


runtime error using sort function in C++

i have been solving a problem called Sort! Sort!! And Sort!!! on uva but the problem is that my code get runtime error whenever i submit it and i don't know why , i wonder if there is anyone who could help me



int m;
bool condition(int first , int second)
{
if(first%m<second%m){return first>second;}
if(first%m>second%m){return first<second;}
else
{
if(first%2!=0 && second%2==0){return first>second;}
if(first%2==0 && second%2!=0){return first<second;}
if(first%2!=0 && second%2!=0)
{
if(first>second){return first>second;}
if(second>first){return first<second;}
if(second==first){return 0 ;}
}
if(first%2==0 && second%2==0)
{
if(first>second){return first<second;}
if(second>first){return first>second;}
if(second==first){return 0;}
}
}
return 0;
}

int main()
{
int n,x;
while(cin>>n>>m)
{
if(n==0 && m==0){cout<<n<<" "<<m<<endl; break;}
vector <int> vec;
for(int j=0;j<n;j++)
{
cin>>x;
vec.push_back(x);
}
sort(vec.begin(),vec.end(),condition);
cout<<n<<" "<<m<<endl;
for(int j=0;j<n;j++)
{
cout<<vec[j]<<endl;
}
vec.clear();
}
return 0;
}

fibbonacci sequence even term sum?

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:


1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...


By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.



#include <iostream>
using namespace std;

int main() {
int i =1;
int j =2;
int k = 0;
while (k<4000000)
{
k = i +j;
i = k+j;
j=i +k;
}
cout << i <<endl;
cout << j << endl;
cout << k << endl;
return 0;
}


Am I even doing this correctly? Why am I getting three different nu


vendredi 27 février 2015

What's wrong with this C++11 Code? (Compiles in some IDE's but not others.)

The following code compiles and runs in Xcode 5 and in Visual Studio 2013. I am interested in trying out Codelite, but Codelite will not compile the following program (a problem since I am working with scoped enums in my project). As far as I understand it, Codelite is using the same compiler as Xcode.


Is the code valid per C++11? Why is Codelite unable to compile it?



#include <iostream>

namespace abc
{
namespace xyz
{
enum class SampleEnum
{
SomeValue = 0,
SomeOtherValue = 1
};
}
}

int main(int argc, char **argv)
{
abc::xyz::SampleEnum e = abc::xyz::SampleEnum::SomeValue;
return 0;
}


Here is the build output from Codelite. In case it's garbled, it's pointing to the word "SampleEnum" in the instantiation of the variable and saying "expected a class or namespace".



/bin/sh -c 'make -j8 -e -f Makefile'
----------Building project:[ ClangTest - Debug ]----------
codelite-cc /usr/bin/clang++ -c "/Users/xxx/Desktop/Test/ClangTest/main.cpp" -g -O0 -Wall -o ./Debug/main.cpp.o -I. -I.
/Users/xxx/Desktop/Test/ClangTest/main.cpp:7:8: warning: scoped enumerations are a C++11 extension [-Wc++11-extensions]
enum class SampleEnum
^
/Users/xxx/Desktop/Test/ClangTest/main.cpp:17:40: error: expected a class or namespace
abc::xyz::SampleEnum e = abc::xyz::SampleEnum::SomeValue;
~~~~~~~~~~^
1 warning and 1 error generated.
make[1]: *** [Debug/main.cpp.o] Error 1
make: *** [All] Error 2
2 errors, 1 warnings

I have a class Grid declared as follows:



class Grid
{
public:
Grid(int length_x, int length_y);
~Grid();

Position *at(int x, int y);

private:
int length_x, length_y;
std::vector<std::unique_ptr<Position>> grid;
};


Its most important member variable is the vector of unique_ptr<Position>, which I'm using to simulate a 2-dimensional array whose size is determined at runtime. The class declaration for the Position is as follows:



class Position {
public:
Position(int x, int y);
~Position();

int getX() { return x; };
int getY() { return y; };

private:
int x, y;
};


In the Grid's constructor, I want to create the desired number of Positions and add them to the vector<unique_ptr<Position>. Here's what I've tried so far:



Grid::Grid(int length_x, int length_y)
: length_x(length_x), length_y(length_y)
{
grid.resize(length_x * length_y);

for (int x = 0; x < length_x; x++) {
for (int y = 0; y < length_y; y++) {
std::unique_ptr<Position> temp = std::make_unique<Position>(x, y);
grid.push_back(std::move(temp));
}
}
}


I've also tried using emplace_back() instead of push_back(), as well as replacing the lines inside the for-loop with



grid.push_back(std::make_unique<Position>(x, y));


and also



grid.emplace_back(std::make_unique<Position>(x, y));


Nothing has worked, because when I try accessing any of the Positions' coordinates by iterating through the vector and calling Position::toString(), I always get the following error:


First-chance exception at 0x0087D8A3 in CombatSim.exe: 0xC0000005: Access violation reading location 0x00000000. Unhandled exception at 0x0087D8A3 in CombatSim.exe: 0xC0000005: Access violation reading location 0x00000000.


As far as I know, I could have one of four problems:

1) I'm adding the unique_ptr to the created Position object to the vector incorrectly

2) I'm using the wrong method to dynamically create Position objects.

3) All of the above.

4) Something I don't know about.


Here's the rest of the code:



Position::Position(int x, int y)
: x(x), y(y)
{
}

std::string Position::toString()
{
std::string result = "Position at (" + std::to_string(x) + ", " + std::to_string(y) + ")";

return result;
}

trying to understand -Wsign-conversion error

I have the following sample program, which gives me an error:


error: conversion to ‘__gnu_cxx::__normal_iterator<long unsigned int*, std::vector<long unsigned int> >::difference_type {aka long int}’ from ‘std::size_t {aka long unsigned int}’ may change the sign of the result [-Werror=sign-conversion] for (auto iter = v.begin(); iter != v.begin() + pos; ++iter) { ^ cc1plus: all warnings being treated as errors


if I compile it with -Wsign-conversion, i.e.: g++ ./test.cpp -std=c++11 -Wsign-conversion


source:



#include <vector>
#include <iostream>

int main() {
std::vector<std::size_t> v;
for (std::size_t i = 0; i < 10; ++i) {
v.push_back(i);
}

std::size_t pos = 4;

for (auto iter = v.begin(); iter != v.begin() + pos; ++iter) {
std::cout << *iter << " ";
}

return 0;
}


Can you explain why it is an error, and how should I go about dealing with it? Thank you.


Why does passing a vector of shared_ptrs by value to a lambda fail to compile? [duplicate]


This question already has an answer here:




To be specific, here's some code:



#include <memory>
#include <vector>

class Obj
{
public:
Obj(int number) : m_member(number) {}

int m_member;
};

int main(int argc, char *argv[])
{
std::vector<std::shared_ptr<Obj>> objPointers;

std::function<bool(int)> eventFunction = [=](int number)
{
auto objP = std::make_shared<Obj>(number);
objPointers.push_back(objP);
std::cout << number << " " << objP->m_member << std::endl;
return true;
};

eventFunction(20);

exit(EXIT_SUCCESS);
}


It fails to compile with this message: error: passing 'const std::vector<std::shared_ptr<Obj> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::shared_ptr<Obj>; _Alloc = std::allocator<std::shared_ptr<Obj> >; std::vector<_Tp, _Alloc>::value_type = std::shared_ptr<Obj>]' discards qualifiers [-fpermissive]|


I don't understand why it believes that it's a const vector?


Referencing a variable in a function c++

I'm trying to make sure that I understand what the use of the ampersand to reference a variable is. I know other similar questions have been asked but I would like to see if the code example I give uses it correctly.


example code:



// function prototype
GetBalance(float &balance);

int main()
{
float balance;
bool choice = true;

if (choice == true)
GetBalance(float &balance);
else
cout << "error" << endl;

return 0;
}

GetBalance(float &Balance)
{
cout << "please enter the balance: " << endl;
cin >> balance;

}


So in the main function the float variable is declared.


The function GetBalance references the variable declared in the main function. So that when the user enters a balance, the input is assigned to the balance variable.


Is this correct?


If not is what I want to do possible?


I would like to assign / pass the amount entered during the GetBalance functionto the variable "balance" declared in main().


C++ - How to Make Static Dictionary to Lookup Matrix

I am trying to write a C++ class that allows me to access certain matrix elements by a string lookup. I wanted to create a 'static' class that can do this, such as:



#include <unordered_map>
namespace Mine {
static double AA[3][4] = {
{5.04964676394959,-0.693207030363152,0.0422140829479668,-0.000968959310672217},
{2.6044054979329,0.288475262243944,-0.0208805589126506,0.000380899394040856},
{-4.32707864788065,1.07090008760872,-0.0777874445746693,0.00165150952598117}
};
static unordered_map<std::string, double[3][4]> Mine::parameter_store = { {"AA", AA}};


With the idea being that I would have several matrices, and could look them up based on a key. However, this seems to totally and utterly fail with the following error:



error: object expression of non-scalar type 'double [3][4]' cannot be used in a pseudo-destructor expression


Is it possible to build a lookup table this way in C++?


initialize a member unique_ptr to empty

In my program, I have a bunch of objects of a custom class Position. The declaration of Position is as follows:



class Position {
public:
Position(int x, int y);
~Position();

Actor *getActor() { return actor.get(); };
void setActor(Actor *actor) { actor = std::move(actor); };
Actor *clearActor() { return actor.release(); };

int getX() { return x; };
int getY() { return y; };

private:
int x, y;
std::unique_ptr<Actor> actor;
};


I also have a class called Actor. Not every Position will have an Actor, and so the majority of the time the unique_ptr "actor" of a Position object should be empty (I'm using unique_ptrs to automatically clean up any Actor associated with a Position at runtime).


The Position constructor is as follows:



Position::Position(int x, int y)
{
this->x = x;
this->y = y;
actor.reset(nullptr);
}


However, I know that this isn't correctly setting the stored pointer to nullptr because when I try calling actor.get() inside Position::getActor(), I get an error as follows:


First-chance exception at 0x01096486 in ____.exe: 0xC0000005: Access violation reading location 0x00000008.


Is there a way to initialize a member unique_ptr to nullptr? I know I could get around this by adding a variable to the Actor class that defines whether or not the Actor is active, setting the unique_ptr to a new inactive Actor, and ignoring all inactive Actors, but I'd rather avoid this if possible.


Thanks!


How to implement std::tuple efficiently such that a tuple of empty types is itself an empty type?

I am implementing std::tuple and I want it to be as efficient in both object size and compile time as possible. I am following the suggestions given here and here.


To improve compile-time performance, the implementation does not use recursive inheritance and instead uses multiple inheritance with the tuple_leaf trick. Additionally it uses the empty base class optimization when possible to reduce the size of the type.


To ensure that the empty base class optimization is always applied, my implementation of tuple itself derives from a base class instead of storing the implementation inside a member variable. However, this causes problems with nested tuples because the tuple_leaf technique works through conversion to a base class. Nested tuples cause ambiguity because the same type of tuple_leaf may occur more than once in the derivation chain.


A program illustrating a simplification of the problem is posted below. Is there a simple way to disambiguate the conversion and allow the program to compile and execute without throwing the assert? I have considered detecting the nested tuple case and encoding the multidimensional position of each tuple_leaf within its type somehow, but that seems complex and would probably degrade compile-time performance.



#include <type_traits>
#include <cassert>

template<int i, class T, bool = std::is_empty<T>::value>
struct tuple_leaf
{
tuple_leaf(T x) : val(x) {}

T& get() { return val; }

T val;
};


template<int i, class T>
struct tuple_leaf<i,T,true> : private T
{
tuple_leaf(T x) : T(x) {}

T& get() { return *this; }
};


template<int i, class T1, class T2>
struct type_at
{
using type = T1;
};


template<class T1, class T2>
struct type_at<1,T1,T2>
{
using type = T2;
};


template<class T1, class T2>
struct tuple_base : tuple_leaf<0,T1>, tuple_leaf<1,T2>
{
tuple_base(T1 a, T2 b) : tuple_leaf<0,T1>(a), tuple_leaf<1,T2>(b) {}

template<int i>
tuple_leaf<i,typename type_at<i,T1,T2>::type> get_leaf()
{
// XXX how to disambiguate this conversion?
return *this;
}
};


// XXX deriving from tuple_base rather than
// making tuple_base a member is the root of the issue
template<class T1, class T2>
struct my_tuple : tuple_base<T1,T2>
{
my_tuple(T1 a, T2 b) : tuple_base<T1,T2>(a, b) {}
};

template<int i, class T1, class T2>
typename type_at<i,T1,T2>::type& get(my_tuple<T1,T2>& t)
{
return (t.template get_leaf<i>()).get();
}

template<class T1,class T2>
my_tuple<T1,T2> make_tuple(T1 a, T2 b)
{
return my_tuple<T1,T2>(a,b);
}

struct empty {};

int main()
{
auto tuple = make_tuple(empty(), make_tuple(empty(),empty()));

assert((std::is_empty<decltype(tuple)>::value));
assert(sizeof(tuple) == sizeof(empty));

get<0>(tuple);

return 0;
}


The compiler output:



$ clang-3.5 -std=c++11 repro.cpp
repro.cpp:47:12: error: ambiguous conversion from derived class 'tuple_base<empty, my_tuple<empty, empty> >' to base class 'tuple_leaf<0, empty, true>':
struct tuple_base<struct empty, struct my_tuple<struct empty, struct empty> > -> tuple_leaf<0, struct empty>
struct tuple_base<struct empty, struct my_tuple<struct empty, struct empty> > -> tuple_leaf<1, struct my_tuple<struct empty, struct empty> > -> struct my_tuple<struct empty, struct empty> -> tuple_base<struct empty, struct empty> -> tuple_leaf<0, struct empty>
return *this;
^~~~~
repro.cpp:63:22: note: in instantiation of function template specialization 'tuple_base<empty, my_tuple<empty, empty> >::get_leaf<0>' requested here

return (t.template get_leaf<i>()).get();
^
repro.cpp:80:3: note: in instantiation of function template specialization 'get<0, empty, my_tuple<empty, empty> >' requested here
get<0>(tuple);
^
1 error generated.

Terminate an iterator with a nullptr

I'm trying to improve my knowledge of C++ by implementing various common data structures. I've started with a linkedlist. I'd like to be able to use a range based for loop with it. I read this question and then based my implementation off of this sample code.


My problem is that I'm currently terminating my linkedlist with a nullptr; the final ListNode has its data member next_ set to nullptr. Thus, I passed in nullptr as the argument in the iterator's constructor within the LinkedList<T>::end() function, which I believe should correctly terminate the function. And it works as expected; when I overload << it correctly writes the contents to stream.


Unfortunately it does so with some memory errors (seen while using DrMemory). This is because there is a line that improperly tries to extract a data member from a nullptr (code and explanation is below). However, adding a comparison for nullptr to avoid that fails (see below). Lastly, because overloading the (in)equality operators requires that they take a reference, at the final element of the list a reference to a nullptr is passed. According to this answer that is a big nono. How could I either fix my current implementation, or rework my implementation to avoid the nullptr?


I'm compiling using the mingw32-g++ compiler, version 4.8.1, as follows



$ mingw32-g++ -g -Wall -Werror -Wextra -pedantic -std=gnu++11 -c <cpp file>
$ mingw32-g++ -o main <object files>


And then I run it in DrMemory using



$ drmemory -- main


Running it in DrMemory gets me the output



UNINITIALIZED READ: reading register edx
# 0 ConstListIterator<>::operator!= [structures/listiterator.hpp:167]
# 1 _fu0___ZSt4cout [C:\Users\dannn_000\documents\github\datastructures/main.cpp:10]
# 2 __mingw_CRTStartup
# 3 mainCRTStartup
# 4 ntdll.dll!RtlInitializeExceptionChain +0x8e (0x77e6b5af <ntdll.dll+0x5b5af>)
# 5 ntdll.dll!RtlInitializeExceptionChain +0x59 (0x77e6b57a <ntdll.dll+0x5b57a>)
Note: @0:00:00.738 in thread 9500
Note: instruction: cmp %edx %eax


Based on the output from DrMemory the problem is in the overloaded operator != implementation in ConstListIterator, and looking at that we can clearly see the problem line:



return current_ != rhs.current_;


which will perform an uninitialized read when the last node (the nullptr) is reached. I thought to myself "oh, easy fix" and changed it to



if (rhs == nullptr)
return current_ != nullptr;
return current_ != rhs.current_;


which when compiled gives the error



mingw32-make : In file included from structures/list.hpp:16:0,
At line:1 char:1
+ mingw32-make main 2> t.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (In file include.../list.hpp:16:0,:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

from structures/linkedlist.hpp:16,
from main.cpp:1:
structures/listiterator.hpp: In instantiation of 'bool ConstListIterator<T>::operator!=(const ConstListIterator<T>&) [with T =
int]':
main.cpp:10:16: required from here
structures/listiterator.hpp:167:10: error: no match for 'operator==' (operand types are 'const ConstListIterator<int>' and
'std::nullptr_t')
if (rhs == nullptr)
^

structures/listiterator.hpp:167:10: note: candidate is:

structures/listiterator.hpp:153:6: note: bool ConstListIterator<T>::operator==(const ConstListIterator<T>&) [with T = int] <near
match>
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
^

structures/listiterator.hpp:153:6: note: no known conversion for implicit 'this' parameter from 'const
ConstListIterator<int>*' to 'ConstListIterator<int>*'

structures/listiterator.hpp:168:19: error: no match for 'operator!=' (operand types are 'ListNode<int>*' and 'const
ConstListIterator<int>')
return current_ != rhs;
^

mingw32-make: *** [main.o] Error 1


So then I go ahead and add a member function that would compare a ConstListIterator to a std::nullptr_t, but once that was added I got a new error



mingw32-make : In file included from structures/list.hpp:16:0,
At line:1 char:1
+ mingw32-make main 2> t.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (In file include.../list.hpp:16:0,:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError

from structures/linkedlist.hpp:16,
from main.cpp:1:
structures/listiterator.hpp: In instantiation of 'bool ConstListIterator<T>::operator!=(const ConstListIterator<T>&) [with T =
int]':
main.cpp:10:16: required from here
structures/listiterator.hpp:182:10: error: no match for 'operator==' (operand types are 'const ConstListIterator<int>' and
'std::nullptr_t')
if (rhs == nullptr)
^

structures/listiterator.hpp:182:10: note: candidates are:

structures/listiterator.hpp:156:6: note: bool ConstListIterator<T>::operator==(const ConstListIterator<T>&) [with T = int] <near
match>
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
^

structures/listiterator.hpp:156:6: note: no known conversion for implicit 'this' parameter from 'const
ConstListIterator<int>*' to 'ConstListIterator<int>*'

structures/listiterator.hpp:162:6: note: bool ConstListIterator<T>::operator==(std::nullptr_t&) [with T = int;
std::nullptr_t = std::nullptr_t]
bool ConstListIterator<T>::operator==(std::nullptr_t& rhs)
^

structures/listiterator.hpp:162:6: note: no known conversion for argument 1 from 'std::nullptr_t' to
'std::nullptr_t&'

structures/listiterator.hpp:183:19: error: no match for 'operator!=' (operand types are 'ListNode<int>*' and 'const
ConstListIterator<int>')
return current_ != rhs;
^

mingw32-make: *** [main.o] Error 1


Here is a (simplified) version of my code. I've removed a number of member functions I don't believe are relevant to this code, and I've done my best to remove their usage within the code itself.


listnode.hpp



#ifndef LISTNODE_HPP
#define LISTNODE_HPP 1

template <typename T>
struct ListNode {
public:

ListNode() = delete;
ListNode(T value);
ListNode<T>* getNext();
void setNext(ListNode<T>* node);
T& getValue();
const T& getCValue() const;
void setValue(T value);

private:
T value_;
ListNode<T>* next_;
};

// Standard implementations of all member functions.

#endif


I have another file, "list.hpp", that contains an abstract base class for my LinkedList class, all member functions are pure virtual functions. Excluded for brevity. This file also has the appropriate member functions for dealing with a non-const iterator, however those are more or less the same and aren't the ones being used here and are being excluded for that reason.


linkedlist.hpp



#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP 1

#include <cstddef>

#include "listnode.hpp"
#include "list.hpp"
#include "listiterator.hpp"
#include "../exceptions.hpp"

template <typename T>
class LinkedList : public List<T>
{
public:

LinkedList();
LinkedList(T* arr, std::size_t length);
~LinkedList();
ConstListIterator<T> begin() const;
ConstListIterator<T> end() const;

private:
std::size_t numElements_;
ListNode<T>* head_;
ListNode<T>* tail_;
};


template <typename T> inline LinkedList<T>::LinkedList() :
numElements_(0), head_(nullptr), tail_(nullptr) {
}

template <typename T> inline LinkedList<T>::LinkedList(
T* arr, std::size_t length) :
numElements_(length), head_(nullptr), tail_(nullptr) {
head_ = new ListNode<T>(arr[0]);
ListNode<T>* current = nullptr;
ListNode<T>* next = nullptr;
current = head_;

for (std::size_t i = 1; i < length; ++i) {
next = new ListNode<T>(arr[i]);
current->setNext(next);
current = next;
}
tail_ = current;
}

template <typename T> inline LinkedList<T>::~LinkedList()
{
ListNode<T>* current = head_;
ListNode<T>* next = nullptr;

for (std::size_t i = 0; i < numElements_; ++i) {
next = current->getNext();
delete current;
current = next;
}
}

template <typename T> inline
ConstListIterator<T> LinkedList<T>::begin() const
{
return ConstListIterator<T>(head_);
}

template <typename T> inline
ConstListIterator<T> LinkedList<T>::end() const
{
return ConstListIterator<T>(nullptr);
}
#endif


Lastly, the implementation of my iterator. Again, I've excluded the non-const version of these (for the same reason as above).


listiterator.hpp



#ifndef LISTITERATOR_HPP
#define LISTITERATOR_HPP 1

#include <iterator>

#include "listnode.hpp"

template <typename T>
class ConstListIterator
{
public:
typedef std::forward_iterator_tag iterator_category;
ConstListIterator() = delete;
ConstListIterator(ListNode<T>* node);
ConstListIterator operator++();
ConstListIterator operator++(int);
const ListNode<T>& operator*();
const ListNode<T>* operator->();
bool operator==(const ConstListIterator<T>& rhs);
bool operator==(std::nullptr_t& rhs);
bool operator!=(const ConstListIterator<T>& rhs);

private:
ListNode<T>* current_;
};

template <typename T> inline
ConstListIterator<T>::ConstListIterator(ListNode<T>* node) :
current_(node) {
}

template <typename T> inline
ConstListIterator<T> ConstListIterator<T>::operator++()
{
current_ = current_->getNext();
return *this;
}

template <typename T> inline
ConstListIterator<T> ConstListIterator<T>::operator++(int)
{
current_ = current_->getNext();
return *this;
}

template <typename T> inline
const ListNode<T>& ConstListIterator<T>::operator*()
{
return *current_;
}

template <typename T> inline
const ListNode<T>* ConstListIterator<T>::operator->()
{
return current_;
}

template <typename T> inline
bool ConstListIterator<T>::operator==(const ConstListIterator<T>& rhs)
{
return current_ == rhs.current_;
}

template <typename T> inline
bool ConstListIterator<T>::operator!=(const ConstListIterator<T>& rhs)
{
return current_ != rhs.current_;
}

#endif


And the file I'm using to run this all


main.cpp



#include "structures/linkedlist.hpp"
#include <iostream>

int main()
{
LinkedList<int> list;
list.append(1);

for (auto i : list)
std::cout << i << std::endl;

return 0;
}

Been Stuck on this for hours. Deleting extra spaces in a char string. C++

Question:Write a program that reads in a sentence of up to 100 characters and outputs the sentence with spacing corrected and with letters corrected for capitalization. In other words, in the output sentence, all strings of two or more blanks should be compressed to a single blank. The sentence should start with an uppercase letter but should contain no other uppercase letters. Do not worry about proper names; if their first letters are changed to lowercases, that is acceptable. Treat a line break as if it were a blank space, in the sense that a line break and any number of blank spaces are compressed to a single blank space. Assume that the sentence ends with a period and contains no other periods. For example, the input


noW iS thE TiMe fOr aLl gOOD MEN TO ComE TO tHe aId oF


ThE CounTRY. should produce the output:


Now is the time for all good men to come to the aid of the country.


My code:



#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string space(string &s1);
string indent(string &s2);
string spacetab(string &s3);
string user_sentence;

int main() {
cout<<"Please enter the awful sentence to fix"<<endl;

getline(cin,user_sentence,'.');
while(user_sentence[100]!='.'){
space(user_sentence);
indent(user_sentence);
spacetab(user_sentence);
char periodfinder = user_sentence.length();
if(user_sentence[0] != ' ') {
user_sentence[0] = toupper(user_sentence[0]);

}
for (int i=1;i < periodfinder;i++){
user_sentence[i] = tolower(user_sentence[i]);
}

cout<<user_sentence;
return 0;

}

}
string space(string &s1){
char innerloop = s1.length();
for(int j = 0; j<=innerloop;j++){
for(int i = 0; i<=j;i++){
if(s1[i] == ' ' && s1[i+1] == ' '){
s1.erase(s1.begin()+1);
}
else if (s1[0] == ' ') {
s1.erase(s1.begin());
}
else if (s1[i] == '\0' && s1[i-1] == ' '){
s1.erase(s1.end()-1);
}

}
}
return s1;
}
string indent(string &s2){
for(int i =0; i <= s2.length();i++){
if(s2[i] == '\n') {
s2[i]= ' ';
}
}
return s2;
}
string spacetab(string &s3){
for(int i =0; i <= s3.length();i++){
if(s3[i] == '\t') {
s3[i]= ' ';
}
}
return s3;
}


MY OUTPUT WORKS FINE TO FIX Capital letters but not for extra spaces Output1: Please enter the awful sentence to fix the cat in the hat. The cat in the hat 2nd input test: the cat in the hat. Please enter the awful sentence to fix Input: the cat in the hat. Output: T in the hat


How to flatten list of lists with boost:mpl


typedef boost::mpl::list<int, char> l1;
typedef boost::mpl::list<std::string, long> l2;


I want to flatten them into a single list l3 which contains



boost::mpl::list<int, char, string,long>.


How do I do this using boost::mpl ?


Why can't I move std::ofstream?

Looking at previous answers on SO, it seems that while std::ostream is not be movable, std::ofstream should be. However, this code



#include <fstream>

int main()
{
std::ofstream ofs;
std::ofstream ofs2{std::move(ofs)};
}


does not seem to compile in any version of gcc or clang I tried (with either --std=c++11 or --std=c++14). The compiler error varies somewhat, but here's what I get for gcc 4.9.0



6 : error: use of deleted function 'std::basic_ofstream::basic_ofstream(const std::basic_ofstream&)'


Is this the expected behavior, according to the standard?


Note that a very similar question was asked before ( Is std::ofstream movable? ) but seems the standard has changed since then ( as detailed in Why can't std::ostream be moved? ) rendering those answers outdated. Certainly, none of those answers explains why the code above does not compile.


Came across this issue when trying to use containers of ofstream, which does not work because of the above.


C++ interface for managing OpenGL vertex attributes

Four years ago I wrote a basic GLES2 engine in ObjC (http://ift.tt/1Djdo2B)


It struck me that certain operations are high in boilerplate, the best example being the loading of the vertex data to the GPU (specifically, creating a struct Vertex to match the vertex shader's attributes, and informing GL of the data packing).


I'm now working in C++11 using JUCE, which comes with a low-level GL wrapper API.


Attribute handling looks like this: http://ift.tt/1DjdmaZ


I hope that link makes it fairly obvious what I mean by "boilerplate heavy". If you wish to use the different shader, you must replicate a lot of lines of code; createAttribute, glVertexAttribPointer, glEnableVertexAttribArray, glDisableVertexAttribArray. And glVertexAttribPointer is particularly ugly, it requires the offset of the attribute within the vertex data structure.


So this is my question: how can I abstract out the specifics, to create a generic attribute handler? Using C++11 constructs it should be possible to automate much of the work.


I'm not going to ask for an implementation (although I would welcome any). I'm asking what a good interface would look like.


There are a lot of C++ GL engines out there, so I'm guessing this problem has been solved in a variety of different ways.




Here is my thinking so far:


glGetActiveAttrib looks like it allows one to extract the attributes from the shader source: 1, 2


So how about first compiling the shader, and then using glGetActiveAttrib to subsequently create a vertex structure?



class Vert {
void setupUsingShaderProgram(p) {
/* use glGetActiveAttrib on p... */
bytes = ...
}
int bytes;

void* operator [] (std::string nameInShader) {
// allow things like myvert['position']
// ... Supposing the shader contains:
// `attribute vec4 position;`
}


Problems:(1) type safety; having to typecast that void* into say a GLFloat[4]* the consumer could end up overwriting. (2) look up speed -- a dictionary lookup wouldn't be acceptable in a lot of situations like when you were manually setting values on thousands of vertices.


So I think the consumer would have to specify:



using Vert_xyz_uv_rgba = VertexGenerator< Vec3, Vec2, Vec4 >;

auto vert = Vert_xyz_uv_rgba(openGLContext, shaderprog);


And maybe Vert_xyz_uv_rgba contains a tuple containing a Vec3, Vec2, Vec4


So the consumer could do things like:



vert.setnumverts(1000);
vert[307][0] = someVec3;

//or...
vert[307]["position"] = someVec3; // again slow lookup


I can't see any nice solution. Ideally I would want to do something like:



using V = VertexGenerator< Vec3 position, Vec2 tex_uv, Vec4 rgba >;
auto vert = V(openGLContext, shaderprog);
vert[307].position = ...


So maybe I could create a C struct for a particular vertex type:



struct xyz_uv_rgba // CRTP? : VertGenerator<xyz_uv_rgba>
{
GLFloat xyz[3];
GLFloat uv[2];
GLFloat rgba[4];
}


That wouldn't be too much of a burden to create for each individual shader. Just mirror its attributes as a C-struct.


And it should be possible to automate the createAttribute, glVertexAttribPointer, glEnableVertexAttribArray, glDisableVertexAttribArray making use of glGetActiveAttrib.


Please don't be too hasty closing this question for being too open -- there will be a small number of viable patterns for doing this.


Returning std::initializer_list in clang

Consider this sample of code:



#include <initializer_list>
#include <iostream>

int main()
{
for(auto e: []()->std::initializer_list<int>{return{1,2,3};}())
std::cout<<e<<std::endl;
return 0;
}


I tried to compile it with g++ (gcc version 4.9.2 (Debian 4.9.2-10)) and the output is correct. In clang++ (Debian clang version 3.5.0-9 (tags/RELEASE_350/final) (based on LLVM 3.5.0)) output for example:



0
2125673120
32546


Where first line are always 0 and last two are "random".


It's error in clang or something else? I think that this sample of code is correct.


Update:


When the lambda function return type is something else (e.g. std::vector or std::array) this code works fine.


Can I use an alias for static member function templates?

Using C++11, I'd like to call a static member function template without qualifying it with the scope of its enclosing class:



struct Test {
template<typename T>
static bool Function(T x)
{ /* ... */ }
};

int x;
Test::Function(x); // I don't want to write this
Function(x); // I want to be able to write this instead


I can define another function with the same signature at global scope and forward the arguments, but I'd prefer a solution that doesn't force me to write another function. I'd also like to avoid using a macro.


This question is related: (using alias for static member functions?) but doesn't seem to cover the case of function templates.


vector of unique_ptr not being fully deleted (memory leaks)

I'm writing a program that will eventually require me to create a vector of unique_ptrs to objects of a custom class. I was getting some memory leaks, so I decided to remove the custom class from the equation and just try it with unique_ptr.


When I try creating a unique_ptr on the stack, there are no leaks. However, creating a vector of unique_ptrs does leak. For fun, I also tried moving a unique_ptr into the vector just to see what happened. My code is below (includes MSVS memory checking):



#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

#include <vector>
#include <memory>
using namespace std;

int main()
{
vector<unique_ptr<int>> testvector;
unique_ptr<int> addMe;

testvector.emplace_back(move(addMe));
testvector.clear();

_CrtDumpMemoryLeaks();
return 0;
}


When I comment out everything except the creation of "addMe", I get no leaks.

When I comment out everything except the creation of "testvector", I get a memory leak of 8 bytes.

When I comment out the emplace_back of "addme" to "testvector", I get a memory leak of 8 bytes.

When I comment out nothing, I get a memory leak of 12 bytes.

Everything behaves the same when I replace all "unique_ptr" with "shared_ptr".


Am I doing something wrong, or is this to be expected with vectors of smart pointers?


Thanks!


I may be wrong but I believe this to be a bug in clang and GCC.

Consider the code below. Both compilers complain (correctly) that the constructor A(int) is private in class D. Note that, as A is a virtual base class of D, A has to be initialized in the mem-initializer of class D, the most derived class, according to §12.6.2/7 in C++11. See live example.



class A {
public:
A(int i) : x(i) { }
A() : x(1) {}
int x;
};

class B : private virtual A {
protected:
B(int i) : A(i) { } };

class C : public B, private virtual A {
protected:
C(int i) : A(i), B(i) { }
};

class D : public C {
public:
D() : A(1), C(3) { }
};

int main() {
D d;
}


But both compilers don't bother with the fact that the default constructor for class A is also private in D, i.e., both compile and execute the code normally, if we define the constructor for D as follows:



D() : C(3) {}


And this is wrong, as far as I can tell.


Note that both compilers fail to compile (correctly) if we define:



D() : A(), C(3) {}

Macro to make class noncopyable

Is their any problem with following macro that makes class noncopyable?



#define PREVENT_COPY(class_name)
class_name(const class_name&) = delete;\
class_name& operator=(const class_name&) = delete;

class Foo
{
public:
PREVENT_COPY(Foo)

// .......
};

How to automatically convert a lambda to a std::function?

In C++11+ one can write something like this:



#include <functional>

std::function<float(int)> f = [](int i){ return i / 100.0; };


Is there a way to write a function make_std_function (possibly using templates) which allows to create a std::function object in the following manner:



auto f = make_std_function([](int i){ return i / 100.0; });

how to force compile-time constants with namespaces

I am currently working on a microcontroller, which makes any memory usage very expensive and thus I want to reduce the footprint as much as I can. Since there are many configuration parameters defined as constants, I think there is some potential for optimization.


Basically, I need something like an enum for non-integral types. However the solution looks like, it must meet the following constraints:



  • compile-time constant, thus no memory footprint at all

  • can be hidden in namespaces (thus, #define is no option here)

  • no function-like access (thus, constexpr is no option here)

  • can be of any type (but type safe, thus reinterpret_cast is no option here)

  • no libraries other than C++11 used


Any ideas are welcome! :)


I need to implement a function that should do specified task for specified duration which is passed to it as parameter (std::chrono::milliseconds).


I have come up with code :



void Run(std::chrono::milliseconds ms)
{
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
while (elapsed_seconds <= (ms / 1000))
{
std::cout << "Running" << std::endl;
end = std::chrono::system_clock::now();
elapsed_seconds = end - start;
}
}

int main()
{
{
std::chrono::milliseconds ms(30000);
Run(ms);
system("Pause");
}


I suppose the code to print Running for 30 seconds and then exit. But it does not do so. How do I achieve such behavior with C++ <chrono>


memory management for linked list and tree programs in c++

I solve algoritm questions from sites like leetcode, hacker rank or cracking the coding interview. I do most if the questions in c++. So for most of them i have a node struct as below



struct Node {
Node* next;
//for tree
Node* left;
Node* right;
int data;
//ctor
Node(int val) : left(nullptr);.....
};


then i have a function(s) which implements the algorithm



bool someAlgorithm(Node* root) {
//do stuff
}


and finally i create the nodes in the main



int main() {
auto root = new Node(4);
root->left = new ..
root->left->left = new ..
}


I want to incorporate memory management in this kind of solutions. If i use c++11 shared_ptr do i need to provide a destructor ? if yes what should i write in the destructor ? But i found that shared_ptr makes code overly complex and un-understandbale for such small programs.


In general what is the best way to make solving such questions memory safe ?


Inserting any number of types into a pack of template arguments

InsertTypes<Pack, P<Ts...>, Is...>::type is Pack with the types Ts... inserted in positions Is..., respectively. For example,



InsertTypes<Pack<int, double, char, long, int>, Pack<short, float, std::string>, 2,4,1>::type,


is



Pack<int, std::string, double, short, char, long, float, int


(short inserted between double and char, float inserted between long and int, and std::string inserted between int and double).


My method: Sort the Is... in reverse order first (from largest to smallest), and apply Insert for each type in Ts... and each int in Is... Why reverse sort the Is...? Because if they are not in that order, inserting a type will bump the positions off by one and mess up the other insertions. But there is a flaw in my plan, which I'll explain shortly. First let me provide the helper functions I've written, which I tested to work correctly on their own:


Insert<T, P<Types...>, N>::type is the pack P<Types...> with T inserted in position N.



template <typename, typename, typename, int> struct InsertHelper;

template <typename T, template <typename...> class P, typename First, typename... Rest, typename... Accumulated>
struct InsertHelper<T, P<First, Rest...>, P<Accumulated...>, 0> {
using type = P<Accumulated..., T, First, Rest...>;
};

template <typename T, template <typename...> class P, typename First, typename... Rest, typename... Accumulated, int N>
struct InsertHelper<T, P<First, Rest...>, P<Accumulated...>, N> : InsertHelper<T, P<Rest...>, P<Accumulated..., First>, N-1> {};

template <typename, typename, int> struct Insert;

template <typename T, template <typename...> class P, typename... Types, int N>
struct Insert<T, P<Types...>, N> : InsertHelper<T, P<Types...>, P<>, N> {};


Now ReverseSortIntSequence (using quicksort):



template <int I, int J>
struct IntLessThan : std::conditional<(I < J), std::true_type, std::false_type>::type {};

template <int, typename> struct PrependInt;

template <int N, template <int...> class Z, int... Is>
struct PrependInt<N, Z<Is...>> {
using type = Z<N, Is...>;
};

template <template<int> class, typename> struct FilterInts;

template <template<int> class F, template <int...> class Z, int I, int... Is>
struct FilterInts<F, Z<I, Is...>> {
using type = typename std::conditional<F<I>::value,
typename PrependInt<I, typename FilterInts<F, Z<Is...>>::type>::type,
typename FilterInts<F, Z<Is...>>::type
>::type;
};

template <template<int> class F, template <int...> class Z>
struct FilterInts<F, Z<>> {
using type = Z<>;
};

template <typename, typename> struct MergeIntSequences;

template <template <int...> class Z, int... Is, int... Js>
struct MergeIntSequences<Z<Is...>, Z<Js...>> {
using type = Z<Is..., Js...>;
};

template <typename> struct ReverseSortIntSequence;

template <template <int...> class Z, int N, int... Is>
struct ReverseSortIntSequence<Z<N, Is...>> {
template<int I> struct less_than : std::integral_constant<bool, (I >= N)> {};
template <int I> struct more_than : std::integral_constant<bool, (I < N)> {};
using subsequence_less_than_N = typename FilterInts<less_than, Z<Is...>>::type;
using subsequence_more_than_N = typename FilterInts<more_than, Z<Is...>>::type;
using type = typename MergeIntSequences<typename ReverseSortIntSequence<subsequence_less_than_N>::type,
typename PrependInt<N, typename ReverseSortIntSequence<subsequence_more_than_N>::type>::type
>::type;
};

template<template <int...> class Z>
struct ReverseSortIntSequence<Z<>> {
using type = Z<>;
};


Now InsertTypes itself:



template <typename, typename, typename> struct InsertTypesHelper;

template <typename Pack, template <typename...> class P, template <int...> class Z>
struct InsertTypesHelper<Pack, P<>, Z<>> {
using type = Pack;
};

template <typename Pack, template <typename...> class P, typename First, typename... Rest, template <int...> class Z, int N, int... Ns>
struct InsertTypesHelper<Pack, P<First, Rest...>, Z<N, Ns...>> : InsertTypesHelper<typename Insert<First, Pack, N>::type, P<Rest...>, Z<Ns...>> {};

template <typename, typename, int...> struct InsertTypes;

template <typename Pack, template <typename...> class P, typename... Types, int... Is>
struct InsertTypes<Pack, P<Types...>, Is...> : InsertTypesHelper<Pack, P<Types...>, typename ReverseSortIntSequence<index_sequence<Is...>>::type> {};


Now, my tests:



int main() {
std::cout << std::is_same<
typename ReverseSortIntSequence<index_sequence<5,10,8,4,0,2,1,2,7,8,3>>::type,
index_sequence<10,8,8,7,5,4,3,2,2,1,0>
>::value << std::endl; // true

std::cout << std::is_same<
InsertTypesHelper<Pack<int, double, char, long, int>, Pack<float, short, std::string>, index_sequence<4,2,1>>::type,
Pack<int, std::string, double, short, char, long, float, int>
>::value << std::endl; // true (*)

std::cout << std::is_same<
typename ReverseSortIntSequence<index_sequence<2,4,1>>::type,
index_sequence<4,2,1>
>::value << std::endl; // true (**)

std::cout << std::is_same<
InsertTypes<Pack<int, double, char, long, int>, Pack<short, float, std::string>, 2,4,1>::type,
Pack<int, std::string, double, short, char, long, float, int>
>::value << std::endl; // false (rats!)
}


I get false above because despite (*) and (**) being true above, we must have Pack<short, float, std::string> permuted in the same way 2,4,1 is permuted in order to get that in reverse sorted order. I could proceed with this fix, but now it is getting overboard. I will still go ahead with that, but I seriously suspect there is a better method altogether, probably fairly short too. Any good ideas here?