question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,369,124 | 69,369,318 | Visual Studio Debugger, interpreting memory without bound or as different types? | I'm hoping to improve my debugging workflow by learning how to inspect values faster and with more clarity, but I'm having a big issue.
Visual Studio's C++ debugger makes some assumptions about my memory that aren't always true:
The "Type" of the value may not be how I want to see it's memory printed out
I may want to look at a cstring without 0 terminating the IDE's print out
There might be memory in front of the structure I want to look at
For instance, I might want to look at float value as 0x3f800000 instead of 1.0f, as seeing 0x0000803f instead of 4.60060298822e-41 makes it much easier to see there's an endian encoding issue naturally.
Or when tokenizing, I'll want to look at as many characters as I can scroll through, without NULL ending the print out, and possibly even look in front of this address.
It is possible to use array, 23 to print out 23 characters in array, but this is the only QoL feature I was able to find, and you have to make a bookmark for the variable, so it ends up being very clunky.
Are there any settings or extensions or features I missed, that could improve my ability to see memory in ways Visual Studio might not be able to predict for me?
| There are many questions here, sorry if I overlooked some.
For the type, Visual Studio's Watch window can cast. For example, if you have
float f = 1.23;
you can view it as float by just listing its name, or you can cast:
*(int*)&f 0x3f9d70a4 int
For the strings (and looking for memory around your variables) I suggest to use Memory view (Debug -> Windows -> Memory), you get four of those to look at different locations simultaneously. Or at the same location with different formatting. You can put an address of your variable there and some math (- some value). You can view as 1-, 2-, 4- or 8-byte values, Hex or Decimal, ANSI or Unicode, etc. Oh, and yes - you can scroll, pretty far.
For more complex types, you can use natvis
|
69,369,380 | 69,375,820 | std::scoped_lock and mutex ordering | I'm trying to determine if std::scoped_lock tries to establish an ordering or mutex id to acquire locks in a prescribed order. Is not clear to me that it does it from a somewhat brief looking at a browsable implementation I found googling around.
In case it is not doing that, What would be the closest to standard implementation of acquiring an ordered set of locks?
Typically the cleanest way to avoid deadlocks is to always acquire a group of locks in the same order (and yes, sure, always release them all before trying to acquire new locks again, but perhaps 2PL is a little beyond the scope of what std::scoped_lock should aim to do)
| The order for std::lock isn't defined until run-time, and it is not fixed. It is discovered experimentally by the algorithm for each individual call to std::lock. The second call to std::lock could lock the mutexes in a different order than the first, even though both calls might use the same list of mutexes in the same order at the call site.
Here is a detailed performance analysis of several possible implementations of std::lock: http://howardhinnant.github.io/dining_philosophers.html
Using a fixed ordering of the mutexes is one of the algorithms that is performance-compared in the above link. It is not the best performing algorithm for the experiments conducted.
The libstdc++ implementation the OP points to is a high quality implementation of what the analysis labels "Smart & Polite"
|
69,370,273 | 69,370,405 | What is going on in this code. Can somebody explain me? | Can please someone explain me what is going on with this code. I mean I don't get it. Here is the source code.
#include <iostream>
using namespace std;
int main(){
int a = 0;
int c = 0;
for (int b = 1; b <= 144 ; b++){
a = b;
b = c;
c = a + b;
cout << a << "\n";
}
}
Output :
1
1
2
3
5
8
13
21
34
55
89
144
Thanks in advance!
| Well, I'll go by explaining it line by line.
Before main()
First, the include <iostream> imports the cout function to output to the terminal.
The using namespace std; is like a shortener and imports the standard library. Instead of std::cout, now you are writing cout.
During main()
The int main() calls the main function of the file, which runs the program.
The int keyword references that it should return an integer value.
int a,c; references that you are declaring 2 variables, both integers, named a, and c.
The for loop has multiple parameters:
int b = 1; creates a variable that the for loop uses in its next arguments.
b <= 144; specifies that as b is being modified if it is less than or equal to 144 then the loop will continue to execute.
b++ means that for every iteration of the loop you will increase the value of b by one.
Here is an example of the first for loop iteration, with the b value filled in:
a = 1; // a is now 1
b = c; // c hasn't exactly been defined, but it is an integer
c = a + 1; // or 1 + 0. c is now 2
In the next iteration, I will fill some more values in:
a = 1; // b is 1 and a is set to b
b = 1; // b is set to c
c = 1 + 1;
Now, why is b the same as the last iteration? Because c was technically 0, b was set to 0, and after the loop, it was increased by 1, so then it was back to 1. The only difference was that c was 1, which set the second iteration value of c to 2.
In the comments above, someone referenced this is the Fibonacci sequence which if you aren't aware about, it is an interesting topic to google.
|
69,370,780 | 69,370,817 | Invalid types float[int] for array subscript in a for loop | I'm not familiar with c++. I've been doing a question. I need to pass the values from the first two functions(weight & height) to calcbmi function. There's an error in for loop in calcbmi function. Also it says "cannot convert 'float*' to 'float'" in main method calcbmi.
#include <iostream>
#include <cmath>
using namespace std;
void inputweight(float weight[], int size) {
cout << "Enter weights in kilogram: ";
int i = 0, w;
while (i < size) {
cin >> w;
if (w >= 45 && w <= 200) {
weight[i] = w;
i++;
}
else{
cout << "The value should be between 45-200." << endl;
}
}
cout << "Weights: ";
for (int i = 0; i < size; i++) {
cout << weight[i] << " ";
}
cout << endl;
}
void inputheight(float height[], int size) {
float h;
cout << "Enter height in cm: ";
for (int i = 0; i < size; ) {
cin >> h;
if (h >= 140 && h <= 200) {
height[i] = h;
i++;
}
}
cout << "Heights: ";
for (int i = 0; i < size; i++) {
cout << height[i] << " ";
}
cout << endl;
}
void calcbmi (float weight, float height, float bmi, int size) {
for (int i = 0; i < size; i++) {
bmi[i] = weight[i] / (height[i] / 100 * height[i] / 100);
}
cout << "BMI values:";
for (int i = 0; i < size; i++) {
cout << bmi[i] << " " << endl;
}
}
int main() {
int size;
cout << "Enter numebr of students: ";
cin >> size;
float weight[size], height[size], bmi[size];
inputweight(weight, size);
inputheight(height, size);
calcbmi(weight, height, bmi, size);
return 0;
}
Any help would be appreciated.
| Look at void calcbmi (float weight,float height, float bmi, int size) and you'll see that bmi is a float - not a float[], so you can't do bmi[i] = .... The same goes for weight and height.
The proper signature of the function should be:
void calcbmi (float weight[],float height[], float bmi[], int size)
Your program is however not strictly conforming C++ since you are using variable length arrays:
float weight[size],height[size],bmi[size];
I suggest replacing those with:
std::vector<float> weight(size), height(size), bmi(size);
It could look like this:
#include <iostream>
#include <limits>
#include <string_view>
#include <vector>
// One function that can be used for both weights and heights:
bool inputvector(std::vector<float>& values, std::string_view heading,
std::string_view unit, float min, float max)
{
std::cout << "Enter " << heading << "s in " << unit << '\n';
for(unsigned i = 0; i < values.size();) {
std::cout << heading << ' ' << (i + 1) << ": ";
// check that input succeeds and deal with failure
if(not(std::cin >> values[i])) {
// something went bad
if(std::cin.eof()) return false; // no way to recover
// some bad input, clear the failbit and empty the input buffer:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Invalid input, try again.\n";
} else if(values[i] >= min && values[i] <= max) {
++i;
} else {
std::cout << "Only " << heading << "s between " << min << " and "
<< max << ' ' << unit << " are allowed, try again.\n";
}
}
std::cout << heading << "s:";
for(auto value : values) std::cout << ' ' << value;
std::cout << '\n';
return true;
}
void calcbmi(std::vector<float>& weight, std::vector<float>& height,
std::vector<float>& bmi)
{
for(unsigned i = 0; i < bmi.size(); i++) {
bmi[i] = weight[i] / (height[i] / 100 * height[i] / 100);
}
std::cout << "BMI values:";
for(auto value : bmi) std::cout << ' ' << value;
std::cout << '\n';
}
int main() {
int size;
std::cout << "Enter number of students: ";
// check that input succeeds and that it's greater than zero:
if(std::cin >> size && size > 0) {
std::vector<float> weight(size), height(size), bmi(size);
if(inputvector(weight, "weight", "kg", 45, 200) &&
inputvector(height, "height", "cm", 140, 200))
{
calcbmi(weight, height, bmi);
}
}
}
If you are not going to use bmi after calcbmi, you don't really need to declare it outside the calcbmi function. You could just calculate the BMI values and print them directly in the calcbmi function.
|
69,371,288 | 69,371,327 | Class's container get() member function usage vs copying | I have created a config class which loads configuration from a config YAML.
I have created vector containers for each type
// Pseudo Code
class config
{
private:
std::vector<std::string> c_name;
public:
config(yaml_file_path)
{
// Handles reading from yaml and loading data to c_name container.
load(yaml_file_path);
}
std::vector<std::string> get_name()
{
return c_name;
}
};
I use this object in other class to get the name config.
class loadConfig
{
config cfg(yaml_file_path);
std::vector<std::string> name = cfg.get_name();
// Further use of vector name like checks.
}
Question : What would be better?(as code practice and execution time and/or memory space)
Using get_name() function in various places in code. OR
Copying value in container, as I have done?
|
What would be better?( as code practice and execution time and/or memory space)
Your get_name() function does the container copy each time of the call. This is much expensive and do not required as long as you do not want to modify it outside the class.
I would suggest having one/ both of the overloads instead, so that the compiler can choose upon the (non-const/ const)object you call:
// for the non-const `config` objects call
std::vector<std::string>& get_name() /* noexcept */ {
return c_name;
}
// for the const `config` objects
const std::vector<std::string>& get_name() const /* noexcept */ {
return c_name;
}
Now at caller, you can have
auto& name = cfg.get_name(); // non-const ref for further modifications
or
const auto& name = cfg.get_name(); // const-ref for read only purposes.
In both cases, you will not copy the container.
That being said, for the classes such as config, which has only one container as internal storage, my personal favorite would be making the class iterable by providing the begin and end overloads:
class config
{
std::vector<std::string> c_name;
public:
auto begin() noexcept { return c_name.begin(); }
auto cbegin() const noexcept { return c_name.cbegin(); }
auto end() noexcept { return c_name.end(); }
auto cend() noexcept { return c_name.cend(); }
};
This makes the you write code such as>
config names;
for (auto& name : names) // or for (auto const& name : names)
{
// ...do something with names
}
|
69,371,551 | 69,371,615 | Deduct template parameter fail while using if constexpr | I am trying to figure out how the sfinae concept works in C++. But I can't convince the object-type compiler if bool is true or false.
#include <iostream>
class A {
public:
void foo() { std::cout << "a\n"; }
};
class B {
public:
void ioo() { std::cout << "b\n"; }
};
template<class T>
void f(const T& ob, bool value = false)
{
if constexpr (!value) ob.foo();
else ob.ioo();
}
int main()
{
A ob1;
B ob2;
f(ob1, true);
f(ob2, false);
}
| You need to let the bool parameter to be part of template. In your case, bool value is a run time parameter.
By adding the value as non-template parameter, your code can compile:
template<bool Flag, class T>
// ^^^^^^^^
void f(const T& ob)
{
if constexpr (Flag) {
ob.foo();
}
else
ob.ioo();
}
and you may call like:
f<true>(ob1);
f<false>(ob2);
As a side note, your A::foo() and B::ioo() must be const qualified member functions, as you want to call, with a const objects of each classes inside the f.
That being said, the bool parameter is redundant if you can use the std::is_same
#include <type_traits> // std::is_same
template<class T>
void f(const T& ob)
{
if constexpr (std::is_same_v<T, A>) {
ob.foo();
}
else if constexpr (std::is_same_v<T, B>)
ob.ioo();
}
Now call needs to be just:
f(ob1);
f(ob2);
|
69,372,318 | 69,373,730 | Qt Accidental activation of dragLeaveEvent,what should I do? | I have a QPushButton on a QScrollArea, the parent of the QPushButton is the QScrollArea. I drag the object to the QScrollArea and then to the QPushButton which always activates the dragLeaveEvent of the QScrollArea, I don't want this function to activate, what should I do?
| Thank you for your replies, I have solved the problem.
The method is very simple, just set the parent of the QPushButton to QScrollArea::widget() and it's solved.
|
69,372,464 | 69,372,561 | c++11 how to convert legacy class to template | I have a legacy class like:
class Wrapper{
public:
Wrapper(void*);
void* get();
};
I want to create a type safe wrapper like:
template<class T>
class Wrapper{
public:
Wrapper(T);
T get();
};
Stuff like this won't work because of C++11:
template<class T = void*> //Here I would need <>
class Wrapper...
typedef Wrapper<void*> Wrapper; //This isn't allowed
Is there a way to convert Wrapper to a template class without editing all places where it's already used?
| If you do not want to change at other places, you can give your templated class a different name (because you don't even use it then in the first place):
template<typename T>
class WrapperT
{
public:
WrapperT(T t) : _T(t) {}
T get() { return _T; }
private:
T _T;
};
using Wrapper = WrapperT<void*>;
If you then removed every usage of Wrapper you can rename WrapperT
|
69,372,524 | 69,378,553 | Is it possible to get the type of the derived class from base class without using template in C++? | Suppose I have some unrelated classes, that I want all of them to have a pointer of themselves. Naturally I could use template to achieve this:
template <typename T>
struct Base {
// omitted the code to setup the variable
static T *ptr;
}
class Derived1 : Base<Derived1> {}
class Derived2 : Base<Derived2> {}
// To use:
Derived1 d();
d.ptr->func();
My question is, can we achieve this without template, especially with the introduction of so many features in C++20 and 23 (such as Concepts)?
Ideally I'd love to have this:
struct Base {
using Derived = std::directly_derived_type(Base);
static Derived *ptr;
}
class Derived1 : Base {}
class Derived2 : Base {}
In this case if Base is ever instantiated without being a base class, compiler should refuse to compile the code because Derived can't be resolved.
| Based on the discussion, there is no template-less approach to CRTP. So I guess I'll stick to the current code.
|
69,372,954 | 69,376,724 | ecCodes (grib reading library) does not free the memory | I am using ecCodes library in my project, and I have encountered an issue that memory is not freed between reading the files.
The minimal example representing the problem is this (and is basically a combination of those two library API usage examples [1](https://confluence.ecmwf.int/display/ECC/grib_get_keys) [2]:
#include <string>
#include <vector>
#include <iostream>
#include "eccodes.h"
int main() {
std::string filenames[] = {"../data/era5_model.grib", "../data/era5_model2.grib", "../data/era5_model3.grib",
"../data/era5_model4.grib"};
std::vector<long> vec = {};
for (auto & filename : filenames) {
FILE* f = fopen(filename.c_str(), "r");
int err = 0;
codes_handle* h;
while ((h = codes_handle_new_from_file(nullptr, f, PRODUCT_GRIB, &err)) != nullptr) {
long k1 = 0;
err = codes_get_long(h, "level", &k1);
vec.push_back(k1);
}
codes_handle_delete(h);
fclose(f);
}
std::cout << vec[52];
return 0;
}
In the example the program reads 4 identical ERA5 files, each of size 1.5GB. Before opening new file previous one is closed with codes_handle_delete() and fclose().
Therefore, the expected behaviour would be for the memory usage to stay at about 1.5GB. However, in reality the memory usage steadily increases to about 6.5GB and is freed when program closes (see screenshot below).
This particular example has been run on CLion with CMake (Release configuration), but the issue occurs with every other configuration and also in my other Rust project which calls ecCodes with FFI.
The library seems well tested and supported so it seems unlikely that it is a library bug. Therefore, is that an expected behaviour or is my code wrong? If the latter, how can I correct it?
I am using Ubuntu 21.04 and ecCodes 2.20.0 installed with apt
| So I contacted the library authors and realized that I have not read this example carefully enough.
For the ecCodes to correctly free the memory codes_handle should be deleted every time it is created (analogically to how you should free the memory every time you alloc it). Therefore in my example codes_handle_delete() should be INSIDE the while loop:
while ((h = codes_handle_new_from_file(nullptr, f, PRODUCT_GRIB, &err)) != nullptr) {
long k1 = 0;
err = codes_get_long(h, "level", &k1);
vec.push_back(k1);
codes_handle_delete(h);
}
After that change memory usage is almost unnoticeable.
|
69,373,479 | 69,374,778 | How to get GCC-style line annotated error messages from Python interpreter? | When I compile a program using GCC and there is a part of the line that is incorrect, the error message I receive usually annotates the incorrect part. For example, an invalid header file leads to
prog.cpp:1:10: fatal error: iostreamm: No such file or directory
#include <iostreamm>
^~~~~~~~~~~
compilation terminated.
Notice the ^ above that tells exactly where in the statement the error is. When I run a Python script that does a nontrivial task, a similar ^ does not appear, but I believe there is enough information for the interpreter to output one. Is there way I could view nicer ^ annotated error messages from the Python interpreter?
Example Python error message:
Traceback (most recent call last):
File "hw1/code/assignment.py", line 255, in <module>
main()
File "hw1/code/assignment.py", line 245, in main
train(my_model, train_inputs, train_labels)
File "hw1/code/assignment.py", line 157, in train
grad_w, grad_b = model.back_propagation(train_inputs[i], probs, train_labels[i])
File "hw1/code/assignment.py", line 96, in back_propagation
grad_w[j, k] += self.learning_rate * (y_j - probs[j, i]) * inputs[i, k]
IndexError: index 10 is out of bounds for axis 1 with size 10
Wanted Python error message:
Traceback (most recent call last):
File "hw1/code/assignment.py", line 255, in <module>
main()
File "hw1/code/assignment.py", line 245, in main
train(my_model, train_inputs, train_labels)
File "hw1/code/assignment.py", line 157, in train
grad_w, grad_b = model.back_propagation(train_inputs[i], probs, train_labels[i])
File "hw1/code/assignment.py", line 96, in back_propagation
grad_w[j, k] += self.learning_rate * (y_j - probs[j, i]) * inputs[i, k]
^~~~~~~~~~~~~~~~~~~~~
IndexError: index 10 is out of bounds for axis 1 with size 10
| You do get such arrows for syntax errors, which is the closest equivalent to a compilation error for the Python implementation.
What you are asking for is arrows pointing to the sub-expressions that lead to raise (throw in C++). Neither GCC nor CPython at the moment do that.
|
69,373,619 | 69,373,659 | Called object type 'int' is not a function or function pointer | I am kinda new to C++, therefore, I don't know what is the cause of this error, I am trying to solve the edit distance problem recursively, however, this error shows up.
error: called object type 'int' is not a function or function pointer
return __comp(__b, __a) ? __b : __a;
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int distance(string, string, int, int);
int cost(string, string, int, int);
int main(){
string v = "love";
string v2 = "hate";
cout<<distance(v, v2, v.size()-1, v2.size()-1);
}
int distance(string v, string v2, int a, int b)
{
if (a==0) return b;
if (b==0) return a;
return min(
distance(v, v2, a, b-1)+1,
distance(v, v2, a-1, b)+1,
distance(v, v2, a-1, b-1)+cost(v, v2, a, b));
}
int cost(string v, string v1, int a, int b)
{
if (v[a]==v1[b]) return 0;
return 1;
}
| 3rd argument of std::min is the comparer, you might prefer the overload taking initializer_list:
return min({
distance(v, v2, a, b - 1) + 1,
distance(v, v2, a - 1, b) + 1,
distance(v, v2, a - 1, b - 1) + cost(v, v2, a, b)});
|
69,373,816 | 69,374,111 | Error: no matching function for call to 'sf::RenderWindow::draw(<unresolved overloaded function type>)'| SFML in C++ | I tried to create a Button class and use it with SFML, unfortunately, it produces the error:
no matching function for call to 'sf::RenderWindow::draw()'|
and a few more.
This is the code:
void onclic(){
cout << "Clicked";
}
class Button{
public:
string ButtonText;
Color color;
int sizee;
int x;
int y;
RenderWindow winname;
void func(){
cout << "\n";
}
void Butt(string ButtonText, Color color, int sizee, int x, int y, function<void()> funcc, RenderWindow winname){
Text tt;
tt.setString(ButtonText);
tt.setColor(color);
tt.setPosition(x, y);
tt.setCharacterSize(sizee);
Event e;
while (winname.pollEvent(e)) {
switch (e.type) {
case Event::MouseButtonPressed:
funcc();
}
}
}
};
int main() {
sf::RenderWindow sfmlWin;
sfmlWin.setTitle("Hello!");
sf::Font font;
if (!font.loadFromFile("Raleway-Regular.ttf")) {
while (sfmlWin.isOpen()) {
sf::Event e;
while (sfmlWin.pollEvent(e)) {
switch (e.type) {
case sf::Event::EventType::Closed:
using namespace sf;
Text t;
t.setCharacterSize(20);
t.setString("Something");
sfmlWin.draw(t);
}
}
sfmlWin.clear();
sfmlWin.draw(t);
sfmlWin.display();
}
return -1;
}
sf::Text message("Hello, World!", font);
while (sfmlWin.isOpen()) {
sf::Event e;
while (sfmlWin.pollEvent(e)) {
switch (e.type) {
case sf::Event::EventType::Closed:
using namespace sf;
Text t;
t.setString("Something");
sfmlWin.draw(t);
Button buttt;
Color col(0,255,0);
buttt.Butt("CLICK!", col, 20, 50, 50, onclic, sfmlWin);
sfmlWin.draw(buttt.Butt);
}
}
if (e.type == sf::Event::MouseButtonPressed)
{
if (e.mouseButton.button == sf::Mouse::Left)
{
if(e.mouseButton.x >= 20 && e.mouseButton.y >= 20 && e.mouseButton.x <= 40 && e.mouseButton.y <= 40){
cout << "Pressed.";
}
}
}
sfmlWin.clear();
sfmlWin.draw(message);
sfmlWin.display();
}
return 0;
}
This was the first error in the Build log in Code::Blocks.
error: use of deleted function 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)'.
The very next line was
In file included from C:...\SFML-2.5.1-windows-gcc-7.3.0-mingw-64-bit\SFML-2.5.1\include/SFML/Graphics.hpp:47, from E:\something.cpp:4: C:\Users...\SFML-2.5.1-windows-gcc-7.3.0-mingw-64-bit\SFML-2.5.1\include/SFML/Graphics/RenderWindow.hpp:44:25: note: 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)' is implicitly deleted because the default definition would be ill-formed: class SFML_GRAPHICS_API RenderWindow : public Window, public RenderTarget ^~~~~~~~~~~~
Where did I go wrong?
|
error: use of deleted function 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)'.
This tells you that you are trying to copy a sf::RenderWindow but a sf::RenderWindow is not copyable.
In the shown code, this is the offending copy:
void Butt(string ButtonText, Color color, int sizee, int x, int y,
function<void()> funcc, RenderWindow winname)
// ^^^^^^^^^^^^
Make that a reference instead:
void Butt(string ButtonText, Color color, int sizee, int x, int y,
function<void()> funcc, RenderWindow& winname)
// ^
|
69,373,967 | 69,394,366 | QQmlPropertyMap in propery QQmlPropertyMap | I have a class that can create dynamic properties without Q_PROPERTY
//myclass.h
#include <QQmlEngine>
#include <QQmlPropertyMap>
class MyClass : public QQmlPropertyMap
{
public:
static MyClass& instance();
~MyClass() override = default;
Q_DISABLE_COPY_MOVE(MyClass)
private:
explicit MyClass();
};
QObject *qmlMyClassInterface(QQmlEngine *engine, QJSEngine *scriptEngine);
//myclass.cpp
#include "myclass.h"
#include <QTimer>
QObject *qmlMyClassInterface(QQmlEngine *engine, QJSEngine *scriptEngine) {
Q_UNUSED(scriptEngine)
MyClass *p = &MyClass::instance();
engine->setObjectOwnership(p, QQmlEngine::CppOwnership);
return p;
}
MyClass &MyClass::instance() {
static MyClass singleton;
return singleton;
}
MyClass::MyClass() {
insert("Test1", "Test 1");
insert("Test2", "Test 2");
QTimer::singleShot(3000, [this]{
insert("Test1", "Update test 1");
insert("Test2", "Update test 2");});
}
//main.cpp
#include "myclass.h"
qmlRegisterSingletonType<MyClass>("MyClass", 1, 0, "MyClass", qmlMyClassInterface);
//main.qml
import MyClass 1.0
title: MyClass.Test1
text: MyClass.Test2
Is it possible in the property QQmlPropertyMap have QQmlPropertyMap. To get a subproperty. Something like this in qml:
text: MyClass.Test2.SubTest1
| I found a solution. In myclass.h declare
Q_DECLARE_METATYPE(QQmlPropertyMap*)
In the constructor of MyClass
QQmlPropertyMap *subProperty = new QQmlPropertyMap(this);
subProperty->insert("SubTest1", "some text");
QVariant stored;
stored.setValue(subProperty);
insert("Test2", stored);
QTimer::singleShot(3000, [subProperty]{
subProperty->insert("SubTest1", "Update some text");
});
Now in qml you can do this
text: MyClass.Test2.SubTest1
Thanks to this, you can create dynamic properties and sub-properties without Q_PROPERTY and change values from C ++, all changes will be notified in qml
|
69,375,132 | 69,375,253 | How can I use different struct as template argument in a template function? | I am writing a template function like that:
template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID);
The type T that I want to use is some different structs, for example:
struct A
{
int A_data;
bool A_data_2;
// etc.......
};
struct B
{
double B_data;
char B_data_2;
// etc.......
};
I want the function can access different member variables depends on different struct passing to T,so I wrote such code:
template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID)
{
if(std::is_same<T, A>{})
{
// Do something with Data.A_data and Data.A_data_2
}
else if(std::is_same<T, B>{})
{
// Do something with Data.B_data and Data.B_data_2
}
// other code.
}
And use it:
A data={100,false};
std::string id;
std::string result = EncodeData<A>(0,data,"read_id_xxxxxxxx",id);
But when I compile it, the following error happened:
error C2039: "B_data": is not a member of "A".
error C2039: "B_data_2": is not a member of "A".
How can I fix this? Or what else I can do to solve this problem in one single function?
P.S. I'm using MSVC Compiler(Visual Studio 2019)
|
What else I can do to slove this problom in one single function?
This is not possible under c++11 compiler. However, in C++17 you have if constexpr to do such:
template<typename T>
std::string EncodeData(int DataType, T const& Data, std::string const& ReadCommandID, std::string& ThisID)
{
if constexpr (std::is_same_v<T, A>)
{
// Do something with Data.A_data and Data.A_data_2
}
else if constexpr (std::is_same_v<T, B>)
{
// Do something with Data.B_data and Data.B_data_2
}
}
For C++11 you still need two functions. Therefore, I would suggest having a function overload for each, which might be more readable than having templates.
|
69,376,164 | 69,376,248 | Virtual derived functions and include loops | I am currently learning C++ as a student and I have a problem.
Here is my problem :
I have a class Point (described below)
I have a class Cartesian and Polar whom inherit from Point
I need to create a function to convert a Cartesian to Polar and a Polar to Cartesian. It needs to be callable directly from Cartesian and Polar or by Point.
Here's roughly what I got right now (it doesn't compile) :
// point.hpp
class Point {
public:
virtual void display(std::ostream&) const = 0;
virtual void convert(Cartesian&) const = 0;
virtual void convert(Polar&) const = 0;
friend std::ostream& operator<<(std::ostream&, const Point&);
};
// cartesian.hpp
class Cartesian : public Point {
private:
double _x;
double _y;
public:
Cartesian();
Cartesian(const double, const double);
void display(std::ostream&) const;
void convert(Polar&) const override;
void setX(const double);
void setY(const double);
double getX() const;
double getY() const;
};
// polar.hpp
class Polar : public Point {
private:
double _a;
double _d;
public:
Polar();
Polar(const double, const double);
void display(std::ostream&) const;
void convert(Cartesian&) const override;
void setAngle(const double);
void setDistance(const double);
double getAngle() const;
double getDistance() const;
};
I know the design is crap but I can't change it.
Here's the unit tests to pass :
TEST_CASE ( "TP1_Point::ConversionVersPolaire_V1" ) {
const double x = 12.0;
const double y = 24.0;
const double a = 63.434948;
const double d = 26.832815;
const Cartesian c(x,y);
Polar p;
c.convert(p);
REQUIRE ( p.getAngle() == Approx(a).epsilon(1e-3) );
REQUIRE ( p.getDistance() == Approx(d).epsilon(1e-3) );
}
//-----------------------------------------------------------------------------------------------
TEST_CASE ( "TP1_Point::ConversionVersCartesien_V1" ) {
const double a = 12.0;
const double d = 24.0;
const double x = 23.475542;
const double y = 4.9898805;
const Polar p(a,d);
Cartesian c;
p.convert(c);
REQUIRE ( c.getX() == Approx(x).epsilon(1e-3) );
REQUIRE ( c.getY() == Approx(y).epsilon(1e-3) );
}
//-----------------------------------------------------------------------------------------------
TEST_CASE ( "TP1_Point::ConversionVirtuel" ) {
const double x = 12.0;
const double y = 24.0;
const double a = 63.434948;
const double d = 26.832815;
Cartesian c(x,y);
Polar p(a,d);
const Point * x1 = &c;
const Point * x2 = &p;
Cartesian c1;
Cartesian c2;
Polar p1;
Polar p2;
x1->convert(c1);
x1->convert(p1);
x2->convert(c2);
x2->convert(p2);
REQUIRE ( c1.getX() == Approx(x).epsilon(1e-3) );
REQUIRE ( c1.getY() == Approx(y).epsilon(1e-3) );
REQUIRE ( c2.getX() == Approx(x).epsilon(1e-3) );
REQUIRE ( c2.getY() == Approx(y).epsilon(1e-3) );
REQUIRE ( p1.getAngle() == Approx(a).epsilon(1e-3) );
REQUIRE ( p1.getDistance() == Approx(d).epsilon(1e-3) );
REQUIRE ( p2.getAngle() == Approx(a).epsilon(1e-3) );
REQUIRE ( p2.getDistance() == Approx(d).epsilon(1e-3) );
}
Thanks in advance for your answers.
| In these declarations of member functions
virtual void convert(Cartesian&) const = 0;
virtual void convert(Polar&) const = 0;
the names Cartesian and Polar are not yet declared.
You need either to introduce them as forward declarations before the class Point like
class Cartesian;
class Polar;
or to use elaborated type names in the function declarations like
virtual void convert( class Cartesian& ) const = 0;
virtual void convert( class Polar& ) const = 0;
As the function display is also virtual you should use the keyword override in its declarations in derived classes.
void display(std::ostream&) const override;
Also if one of the function convert is not overridden in one of the derived classes then the corresponding class will be still abstract.
|
69,376,628 | 69,376,965 | Creating the container of smart pointers by cloning elements of another container | I have a class, which supports cloning (via method clone). I have a bunch of its instances in a vector of std::unique_ptr.
Now, I want to create an std::set of same smart pointers from the above vector, ideally during its construction. The obvious design is as following:
#include <memory>
#include <set>
#include <vector>
class A
{
public:
/// type of itself
typedef A self;
A() = default;
A(const self& another) = default;
virtual ~A() = default;
std::unique_ptr<A> clone() const
{
return std::make_unique<A>();
}
};
class SetOfA
{
public:
SetOfA() = default;
// Here is the method I would like to improve
SetOfA(const std::vector<std::unique_ptr<A> >& data)
{
//do not like this loop, prefer this to be in initialization part?
for (const auto& d : data) {
set_of_a.insert(std::move(d->clone()));
}
}
private:
std::set<std::unique_ptr <A> > set_of_a;
};
But is there a way to avoid this for loop in constructor and move the std::set construction into initialization part?
| If you can use Boost, here is a possible solution:
SetOfA(const std::vector<std::unique_ptr<A>>& data) :
set_of_a(
boost::make_transform_iterator(data.begin(), std::mem_fn(&A::clone)),
boost::make_transform_iterator(data.end(), std::mem_fn(&A::clone)))
{ }
|
69,376,734 | 69,378,350 | Undefined Reference in self-built shared library with cmake | I am currently trying to utilize a self-built shared library. The Library FooBar utilizes the "Foo" Library to do some costly calculations. "Foo" however needs "Bar", the licensing library. It has been successfully cross-compiled when using the following CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(FooBar LANGUAGES CXX)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
find_library(Curl
NAMES curl)
find_library(Foo
NAMES foo)
find_library(Bar
NAMES bar)
file(GLOB OBJECT_FILES CONFIGURE_DEPENDS ${PROJECT_SOURCE_DIR}/src/resources/*.o)
file(GLOB SOURCE_FILES CONFIGURE_DEPENDS ${PROJECT_SOURCE_DIR}/src/*.cpp)
add_library(FooBar SHARED ${SOURCE_FILES} ${OBJECT_FILES})
target_link_libraries(FooBar PRIVATE Threads::Threads)
target_link_libraries(FooBar PRIVATE -L${Foo} -L${Bar} -L${Curl})
The compilation is successful without any errors but when I want to include it in the executable, "FooBar" does give me an undefined reference to an function in "Bar", the licensing library. I already checked the "Bar"-library, it contains the used function!
CMakeLists.txt of the executable:
cmake_minimum_required(VERSION 3.12)
project(FooBarExe)
add_subdirectory(FooBar)
add_executable(FooBarExe ${FooBarExe_SRC} ${FooBarExe_INC}) # FooBarExe is just the placeholder for its original name!
target_link_libraries(FooBarExe PRIVATE FooBar)
Error message:
"FooBarExe/FooBar/FooBar.so: undefined reference to 'function'
collect2: error: ld returned 1 exit status"
Does anyone have another idea to solve this issue? I already reordered the libraries in target_link_libraries, compiled it as a static library, included and linked both libraries to FooBarExe via set_target_properties and INTERFACE_LINK_LIBRARIES without any success...
Edit:
I tried the following suggested solutions:
Removing "-L" when adding Library
Added a Check after the find_library(Bar ...)
| There was an interface change in the "Bar" Library, which went unnoticed by me. Had to replace the header file and the library. Found the change by looking deeper into the library, using the nm -gDC xxxx.so command.
Thank you all for your help, the error was done by me...
|
69,377,635 | 69,409,388 | Debug C++ DLL with VSCode instead of Visual Studio | Im working on a project where i need to debug a C++ DLL/Lib. I have the DLL/PDB/H/Source files and i need a "Client" to invoque the DLL so i can debug some functions.
So far i have in Visual Studio a solution for a "DLL Client". To have it working i had to add my "Aditional Include Directories" (the .h file), the dll path on "Linker" and do a xcopy of the dll/pdb in "Build Events".
This is working but i dont like the visual studio interface very much and want to try to code/debug with VSCode.
My client is very simple so far:
#include <iostream>
#include "mydll.h"
int main()
{
char version[20];
GetVersion(version);
std::cout << "Version: " << version << '\n';
}
My DLL is made with a makefile. Im having trouble on how to set up my launch.json (or what to setup) on VSCode to add the include directories and the pdb info so when i run my client the dll/pdb is linked to the client.
The launch.json is the default of vscode only with a name change
{"configurations": [
{
"name": "(gdb) DLL Client",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/dllclient.out",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
"setupCommands": [
{
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}
Any help? Thanks
| So, i dont know if its the best solution but is the one i could find. Probably there is some way to improove this with the C++ extension of vscode.
launch.json (for debug)
{"configurations": [
{
"name": "(gdb) VCVarsall 32",
"type": "cppvsdbg",
"request": "launch",
"program": "${workspaceFolder}\\main.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"targetArchitecture": "x86",
"miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",
"preLaunchTask": "C++: vcvarsall Main 32",
},
]}
tasks.json (to build main and link the library)
{
"tasks": [
{
"type": "process",
"label": "C++: vcvarsall Main 32",
"command": "cmd",
"options": {"cwd": "${workspaceFolder}"},
"args": ["/C vcvarsall x86 && cl /Od /Zi /EHsc /Fd:vc140.pdb /Fo:main.obj ./main.cpp /I ${workspaceFolder}\\dev /link ${workspaceFolder}\\libs\\mylibrary.lib /OUT:main.exe /PDB:vc140.pdb"
],
"group": {
"kind": "build",
"isDefault": true
},
}
],
"version": "2.0.0"
}
|
69,378,099 | 69,378,343 | std::unordered_map gives error when inserting using emplace function | I'm getting this weird error when inserting an element into std::unordered_map using emplace function but not if I use operator[] function overload. This is my code:
#include <iostream>
#include <unordered_map>
#include <memory>
class B {
public:
B() = default;
~B() = default;
};
class A {
public:
A() = default;
~A() = default;
std::unique_ptr<B> b_ptr;
};
int main() {
std::unordered_map<std::string, A> mp;
// mp.emplace("abc", A()); // gives compiler here
auto& a = mp["def"];
}
I'm getting huge error print when compiled. This is a short note of error: template argument deduction/substitution failed
| When you use emplace like mp.emplace("abc", A()); what you are doing is creating a temporary A, and that object is then copied/moved into the object that emplace is going to construct. When you did ~A() = default; in the class, that gets rid of the compiler supplied default move constructor, and the copy constructor is implicitly deleted because std::unique_ptr can't be copied so the A() can't be moved or copied into the object emplace is going to create.
You can fix this by using the std::piecewise_construct taged version of emplace to forward the parts of the key value pair to emplace like
mp.emplace(std::piecewise_construct, // call the piecewise_construct overload
std::forward_as_tuple("abc"), // forwards "abc" to the key
std::forward_as_tuple()); // forwards nothing to the value so it can be default constructed
or you could just add a move constructor to A using
A(A&&) = default;
so that emplace can move the A() you created in main into mp.
|
69,379,215 | 69,380,333 | QTimer dont stop when windows is closed | I am currently starting on QTCreator. I have been asked to use QTimers in a particular context which is this:
We have an open window,
One or more QTimers are triggered and make things appear on the screen every x msec.
When we press "Escape" the window should close and everything should be reset to 0.
But here is the problem, the timers are defined in a static way:
QTimer::singleShot(500, this, SLOT(foo());
When I call this->close() (which closes my window), the timers do not stop and continue. I tried several solutions: browse all the QTimers contained in my object, obviously there are none since they are defined in static. Instead of declaring them in static I've tried to create each time a new QTimer object like that:
QTimer *timer= new QTimer(this);
timer->setSingleShot(true);
timer->setInterval(2000);
timer->setParent(this);
timer->start();
And then call timer->stop() later, but I think it's very brutal when you have multiple Timers in the same code.
Is there a way to stop the timers when this->close is called, knowing that the timers are defined as a static one ?
| Assuming you are using,
QWindow *qw = new QWindow();
QTimer *timer= new QTimer();
To solve the issue you need to connect destroyed() signal of QWindow to timer's slot stop()
So as soon as window is destroyed all registered timers will be stopped without explicit stop call. make sure you connect all timer instances. Code snippet as following,
QObject::connect(&qw, SIGNAL(destroyed()), timer, SLOT(stop()))
QObject::connect(&qw, SIGNAL(destroyed()), timer2, SLOT(stop()))
QObject::connect(&qw, SIGNAL(destroyed()), timer3, SLOT(stop()))
PS:
QTimer *timer= new QTimer(this); // here you are setting parent as 'this' already
timer->setSingleShot(true);
timer->setInterval(2000);
timer->setParent(this); // remove this, no need to set parent again.
timer->start();
|
69,379,238 | 69,379,560 | Splitting template class definitions and declarations fails for nested templates | I know what I want, but I don't know how to tell the compiler what I want. I have split declarations and method definitions in .h and .cpp file, but the .cpp file gets included in the header, so all I did was separate declarations and definitions.
header file (avltree.h) - it includes the source file!:
template < class KEY_T, class DATA_T >
class CAvlTree {
public:
//----------------------------------------
template < class KEY_T, class DATA_T >
class CNode;
typedef CNode< KEY_T, DATA_T> * tNodePtr;
template < class KEY_T, class DATA_T >
class CNode {
public:
KEY_T key;
DATA_T data;
CNode< KEY_T, DATA_T > * left;
CNode< KEY_T, DATA_T > * right;
char balance;
CNode() : left(nullptr), right(nullptr), balance(0) {}
CNode(KEY_T key, DATA_T data) :
key (key), data (data), left(nullptr), right(nullptr), balance(0) {}
};
//----------------------------------------
template < class KEY_T, class DATA_T >
struct tAvlInfo {
CNode< KEY_T, DATA_T> * root;
CNode< KEY_T, DATA_T> * current;
KEY_T key;
bool isDuplicate;
bool branchChanged;
};
typedef bool (* tNodeProcessor) (CNode< KEY_T, DATA_T> * nodePtr);
private:
tAvlInfo< KEY_T, DATA_T > m_info;
//----------------------------------------
public:
DATA_T* Find(KEY_T& key);
private:
CNode< KEY_T, DATA_T> * AllocNode(void);
};
#include "avltree.cpp"
source file (avltree.cpp):
template < typename KEY_T, typename DATA_T >
DATA_T* CAvlTree< KEY_T, DATA_T >::Find (KEY_T& key)
E0276 name followed by '::' must be a class or namespace name
{
CNode* root;
for (CNode* node = m_info.root; node; ) {
if (key < node->key)
node = node->left;
else if (key > root->key)
node = node->right;
else {
m_info.current = node;
return &node->data;
}
}
return nullptr;
}
template < typename KEY_T, typename DATA_T >
CNode* CAvlTree< KEY_T, DATA_T >::AllocNode (void)
E0020 identifier "CNode" is undefined
E0864 CAvlTree is not a template
{
if (m_info.current = new CNode < KEY_T, DATA_T >) {
m_info.branchChanged = true;
return m_info.current;
}
return nullptr;
}
What the compiler says (VS 2019 community, c++2020 enabled):
E0276 name followed by '::' must be a class or namespace name
E0020 identifier "CNode" is undefined
E0864 CAvlTree is not a template
I have no bloody clue how to write this down the correct way. Please enlighten me.
I have similar code for a template class with a single typename which works, but cannot conclude from that how to do this for two typenames.
Using the tNodePtr type instead of CNode< KEY_T, DATA_T > * in my source code also doesn't work.
Btw, I know that the compiler doesn't "transfer" KEY_T and DATA_T from the CAvlTree declaration just because I am using the same names.
| Your problem is the:
template < class KEY_T, class DATA_T >
class CNode;
Those KEY_T and DATA_T are unrelated to the one of CAvlTree.
clang and gcc even emit an error for those because of name shadowing (I don't know if VS does that too).
Due to CNode being a class template, the compiler expects you to provide template arguments for it (like you did for CNode< KEY_T, DATA_T> * AllocNode(void);) at all places where you use CNode.
But if you use KEY_T and DATA_T of CAvlTree for every CNode in your code, then the question is why did you define CNode as a class template in the first place.
And this part of the code indicates that you don't want CNode to be a class template:
template < class KEY_T, class DATA_T >
class CNode;
typedef CNode< KEY_T, DATA_T> * tNodePtr;
// …
CNode< KEY_T, DATA_T> * AllocNode(void);
The same seems to be true for template < class KEY_T, class DATA_T > struct tAvlInfo.
Due to that, I would assume that the code you want to have should look like this:
template <class KEY_T, class DATA_T>
class CAvlTree {
public:
//----------------------------------------
class CNode {
public:
KEY_T key;
DATA_T data;
CNode *left;
CNode *right;
char balance;
CNode() : left(nullptr), right(nullptr), balance(0) {}
CNode(KEY_T key, DATA_T data)
: key(key), data(data), left(nullptr), right(nullptr), balance(0) {}
};
//----------------------------------------
struct tAvlInfo {
CNode *root;
CNode *current;
KEY_T key;
bool isDuplicate;
bool branchChanged;
};
typedef bool (*tNodeProcessor)(CNode *nodePtr);
private:
tAvlInfo m_info;
//----------------------------------------
public:
DATA_T *Find(KEY_T &key);
private:
CNode *AllocNode(void);
};
template <typename KEY_T, typename DATA_T>
DATA_T *CAvlTree<KEY_T, DATA_T>::Find(KEY_T &key) {
CNode *root;
for (CNode *node = m_info.root; node;) {
if (key < node->key)
node = node->left;
else if (key > root->key)
node = node->right;
else {
m_info.current = node;
return &node->data;
}
}
return nullptr;
}
template <typename KEY_T, typename DATA_T>
auto CAvlTree<KEY_T, DATA_T>::AllocNode(void) -> CNode * {
if (m_info.current = new CNode) {
m_info.branchChanged = true;
return m_info.current;
}
return nullptr;
}
And using the auto identifier ( argument-declarations... ) -> return_type syntax allows you to use the CName name directly. Otherwise, you would need to write template <typename KEY_T, typename DATA_T> typename CAvlTree<KEY_T, DATA_T>::CNode* CAvlTree<KEY_T, DATA_T>::AllocNode(void)
|
69,379,489 | 69,380,680 | State pattern error in C++ (no suitable constructor) | class Tool {
public:
virtual void mouseUp();
virtual void mouseDown();
virtual ~Tool();
};
class SelectionTool : public Tool {
void mouseDown() override {
std::cout << "SelectionTool icon\n";
}
void mouseUp() override {
std::cout << "Draw a dashed rectangle\n";
}
};
class BrushTool : public Tool {
void mouseDown() override {
std::cout << "BrushTool icon\n";
}
void mouseUp() override {
std::cout << "Draw line\n";
}
};
class Canvas {
Tool _currentTool;
public:
void mouseDown() {
_currentTool.mouseDown();
}
void mouseUp() {
_currentTool.mouseUp();
}
Tool getCurrentTool(){
return this->_currentTool;
}
void setCurrentTool(Tool currentTool) {
this->_currentTool = currentTool;
}
};
int main(int argc, char *argv[]){
auto george = std::make_unique<Canvas>();
george->setCurrentTool(std::make_unique<BrushTool>());
george->mouseDown();
george->mouseUp();
return 0;
}
No suitable user-defined conversion from "std::unique_ptr<Brush, std::default_delete>" to "Tool" exists.
I am following youtube course where that kind of polymorphism is used in Java and I tried to implement it in C++ but it doesnt work. Whats wrong with that code?
| I suspect the polymorphism video you were using didn't use smart pointer types.
You can't just use std::shared_ptr<T> as if it were the underlying type. They have get and set interfaces, but they are not a seamless replacement. If they were, they couldn't do their job!
Using std::unique_ptr adds more conditions that you may not want to deal with right now. I'm just going to use std::shared_ptr here.
If you want shared pointers, I'd suggest making a typedef to the shared pointer type and use that everywhere. You can assign std::shared_ptr<derived> to std::shared_ptr<base> similar to the inheritance rules for raw pointers. Just be sure you have a virtual base destructor, which you do.
#include <iostream>
#include <algorithm>
class Tool {
public:
virtual void mouseUp() {}
virtual void mouseDown() {}
virtual ~Tool() {}
};
typedef std::shared_ptr<Tool> shared_tool_type;
class SelectionTool : public Tool {
void mouseDown() override {
std::cout << "SelectionTool icon\n";
}
void mouseUp() override {
std::cout << "Draw a dashed rectangle\n";
}
};
class BrushTool : public Tool {
void mouseDown() override {
std::cout << "BrushTool icon\n";
}
void mouseUp() override {
std::cout << "Draw line\n";
}
};
class Canvas {
shared_tool_type _currentTool;
public:
void mouseDown() {
_currentTool.get()->mouseDown();
}
void mouseUp() {
_currentTool.get()->mouseUp();
}
std::shared_ptr<Tool> getCurrentTool() {
return this->_currentTool;
}
void setCurrentTool(shared_tool_type currentTool) {
this->_currentTool = currentTool;
}
};
int main(int argc, char* argv[]) {
auto george = std::make_shared<Canvas>();
george->setCurrentTool(std::make_shared<BrushTool>());
george->mouseDown();
george->mouseUp();
return 0;
}
|
69,379,497 | 69,392,636 | C++ std::random and enum class | I've got a fussy question regarding more modern C++ "preferred" styles.
Say I want to use the contents of std::random in order to select a value from an enum class. How can I finagle that? We're talking some pretty basic stuff here, where the first selection works just fine, but Visual Studio scolds me (rightly) for using bare enums:
enum Direction:uint8_t {
Left, Right
};
std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);
// and so on...
I was surprised enum-base works for a classic enum. But, simply adding the word class into the mix causes the whole shebang to fail to compile.
enum class Direction:uint8_t {
Left, Right
};
std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);
// Severity Code Description Project File Line Suppression State
// Error C2338 invalid template argument for uniform_int_distribution:
// N4659 29.6.1.1 [rand.req.genl]/1e requires one of short, int, long, long long, unsigned short,
// unsigned int, unsigned long, or unsigned long long
// C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\
// include\random 1863
And so on. =)
I can certainly swallow my pride and principle for the sake of solving this problem, but I wanted to abide by modern standards.
I'd be tickled pink if someone had some clever workaround or other best-practice-style-thing when one wants to shuffle an enum like this.
| Both enum and enum class are rather problematic: they don't know their size, they can't be iterated etc. As a replacement, you can use std::variant with dummy types:
struct Left {};
struct Right {};
using Direction = std::variant<Left, Right>;
template<typename V, typename E, std::size_t idx = 0>
auto constexpr cast = [] { // written once, works for any "enum"
if constexpr (std::is_same_v<std::variant_alternative_t<idx, V>, E>) return idx;
else return cast<V, E, idx + 1>;
}();
std::uniform_int_distribution direction{cast<Direction, Left>, cast<Direction, Right>};
As a bonus, now you can get the number of elements in your "enums":
static_assert(std::variant_size_v<Direction> == 2);
And you can even iterate over their enumerators:
template<typename F, typename... Es> // written once, works for any "enum"
constexpr void for_each(F f, std::variant<Es...> const&) {
(..., (void)f(Es{})); // void cast to ignore possible operator,() overloading
}
int main() {
for_each([](auto enumerator) {
std::cout << cast<Direction, decltype(enumerator)> << ' ';
}, Direction{});
}
|
69,380,549 | 69,381,326 | Is cos(x) required to return identical values in different C++ implementations that use IEEE-754? | Is there any sort of guarantee - either in the C++ standard or in some other document - that C++ code computing cos(x) will produce identical values when compiled with g++, clang, MSVC, etc., assuming those implementations are using IEEE-754 64-bit doubles and the input value x is exactly equal? My assumption is "yes," but I'd like to confirm that before relying on this behavior.
Context: I'm teaching a course in which students may need to compute trigonometric functions of inputs. I can assure that those inputs are identical when fed into the functions. I'm aware that equality-testing doubles is not a good idea, but in this specific case I was wondering if it was safe to do so.
| cos is a transcendental function. Transcendental functions are subject to the table-maker's dilemma. Informally, what this means is: let's say you come up with some iterative algorithm for approximating the cosine of an input value: for example, a Taylor series. When you run this iterative algorithm, you have to decide how much extra precision to keep at the intermediate stages (rounding too early may reduce the accuracy of the final result). But because the function is transcendental, it's very difficult to determine how many extra bits must be carried during the calculation in order to yield a correctly rounded final result, and for some input values, the number of extra bits required might be very large.
For this reason, it is generally not practical to design hardware that guarantees correctly rounded results for transcendental functions such as cos (where "correctly rounded" means that the resulting floating point value is the one that's closest to the true real value of the function). Instead, the hardware designers will implement a calculation technique that performs reasonably well and that, for most practical input values, will yield a result that is within 1 bit of the exact real result. (If you absolutely need a cosine function that always yields a correctly rounded result, then apparently it's possible to implement one: GNU MPFR claims to have done it. But this will perform much worse than hardware.)
IEEE 754 (2008) lists cos as one of the "recommended correctly rounded functions", which means that if you implement IEEE 754's version of cos, then you have to yield a correctly rounded result. But these functions are only "recommended" to be provided, and not required. Therefore, a conforming implementation of IEEE 754 might not provide a correctly rounded cos function, and might instead provide a "practical" cos function as described in the previous paragraph. Therefore, in practice, two implementations of C++ which both claim to be IEEE 754 compliant may not yield the exact same value for a transcendental function such as cos when applied to the same argument.
(Note that IEEE 754 requires implementations to provide a square root function that is correctly rounded. This is not a transcendental function, so correctly rounding it is not nearly as difficult.)
|
69,380,561 | 69,380,915 | C++ Why diff EOF checks recommended for text vs numeric? | My textbook recommends using the member accessor method iStreamVar.eof() when dealing with textual data and while (iStreamVar) when dealing with numeric data.
Can someone please explain why it would matter?
Quote from book:
Using the function eof to determine the end-of-file status works best if the input is text. The earlier method of determining the end-of-file status works best if the input consists of numeric data.
That is the only thing mentioned on the topic. After this, it just explains how the process works.
| Which method you use for determining the end of data depends on how you use it. My guess is, both methods which your textbook mentions are used wrong, so they fail in different situations. That's why it recommends using different methods in different situations.
The correct method is not trivial, and it depends on how important error resilience is for you.
If you want to read a space-delimited stream with numbers in it, and you are sure the file contains no errors, the code is simplest:
int value;
while (iStreamVar >> value)
{
...
}
Note that it's not any of the two original options.
If your file contains space-delimited textual data, and you are sure there are no errors, use the same code (but declare the temporary variable as string instead of int).
If you want to detect and recover from errors, use more elaborate code. But I cannot recommend you any specific code structure - it depends on what exactly you want to do in case of errors. Also:
Are text records delimited by space or newline?
What if the input text-file contains an empty line?
Numbers - floating-point or not?
Numbers - if there is a stray character like a among number data, what to do?
So there is no single correct recipe for doing proper input with error resilience.
|
69,380,733 | 69,394,822 | Weird behaviour of some specific Windows locales: why, and how to cope? | I wrote a simple C++ program to test available Windows locales.
#include <iostream>
#include <iomanip>
#include <locale>
int main(int argc, char* argv[])
{
const char* locName = (argc < 2) ? "" : argv[1];
std::locale loc (locName);
std::cout.imbue(loc);
std::cout << "Locale is " << loc.name() << '\n';
std::cout << std::fixed << std::setprecision(8);
std::cout << 12345654321 <<'\n';
std::cout << 123456.54321 << '\n';;
return 0;
}
I compiled it with msvc19. Here are some test results:
c:\Temp>.\test
Locale is
12,345,654,321
123,456.54321000
c:\Temp>.\test C
Locale is C
12345654321
123456.54321000
So far so good.
c:\Temp>.\test xx_xx
Locale is xx_xx
12,345,654,321
123,456.54321000
c:\Temp>.\test xxx_xxx
c:\Temp>
Locale xx_xx does not exist, neither does xxx_xxx, but one is giving the same results as the default locale, and the other freezes the stream. OK, some more tests...
c:\Temp>.\test en_us
Locale is en_us
12,345,654,321
123,456.54321000
c:\Temp>.\test de_de
Locale is de_de
12.345.654.321
123.456,54321000
c:\Temp>
Perfect, as it should be. But...
c:\Temp>.\test fr_fr
Locale is fr_fr
12345654321
c:\Temp>.\test fre_fr
Locale is fre_fr
12,345,654,321
123,456.54321000
c:\Temp>
What? fr_fr won't print floating point numbers at all, but fre_fr will (albeit with the roles of , and . apparently reversed). However they are supposed to be aliases of the same locale!
c:\Temp> python
>>> import locale
>>> locale.normalize('fr_fr')
'fr_FR.ISO8859-1'
>>> locale.normalize('fre_fr')
'fr_FR.ISO8859-1'
Hmm...
c:\Temp>.\test fr_FR.ISO8859-1
c:\Temp>
No output at all.
Now I have read somewhere that one cannot use the encoding suffix in setting C or C++ locales. I can understand that (although it's annoying as hell). But why the weird behaviour of fr_fr (and fr and french and fr_FR and French_France) and how can I recognise and avoid such defective locales ahead of time? Interestingly, fr_be and fr_lu behave as expected.
| There are two separate problems.
fre_fr and fr_FR.ISO8859-1 are not valid locale names as far as Windows is concerned. They are accepted by some third-party software (Python and maybe others) but one cannot use them in C setlocale or C++ std::locale. Weirdly, there seem to be two different failure modes when an invalid locale name is passed to the std::locale constructor. Sometimes it is silently interpreted exactly like a default user locale, and sometimes an exception is thrown. xx_xx and fre_fr are of the first kind, and xxx_xxx and fr_FR.ISO8859-1 are of the second kind. I have no explanation for this.
fr_fr uses a non-ASCII thousands separator (a non-breaking space). Since the encoding used by this locale is Latin-1, it will break if the terminal is set up to handle UTF-8, because this character code is an incomplete/invalid UTF-8 sequence. chcp 1252 solves the problem.
|
69,381,068 | 69,381,230 | Can't find Configuration Property in Visual Studio (C++) | I'm trying to use gcd function from #include <numeric> in Visual Studio 2019 (Community version). However, using namespace std, visual studio just says that "gcd" is undefined. Based on my research, I'm supposed to change the C++ version. However, in the normal settings I can't find "Configuration Properties" and right clicking on the project in the solution explorer to then select properties, just shows me an empty window (see emtpy-property-window picture).
Background info:
Created project with C++ (Cmake Project) in Visual Studio 2019 Community
Added a C++ file (.cpp) with main function and one class
For Building I'm using Cmake
Using namespace std and #inlcude <iostream> so far (with no problem)
When using #include <numeric> and then trying to use gcd(x,y), I get the previous described error-hint
Visual Studio tries to fix the error with adding namespace std, even though that's already added.
Any idea to solve either problem?
| The gcd function was added in C++17. You probably haven't set the appropriate standard in your project settings. At least this is the exact issue you'll get when trying to use std::filesystem::... with an older C++ standard with Visual Studio. (The file system library was added in C++17 too.)
In the project properties Configuration Properties > General > C++ Language Standard should be set to ISO C++17 Standard (/std::c++17) to make the code compile.
You can open the project properties by selecting Properties in the context menu for the target shown in the solution explorer btw; the properties shown in your screenshot just display some very basic information about the selected item.
|
69,381,645 | 69,381,756 | While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0 | While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
| Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.
|
69,381,715 | 69,381,773 | My code is in an infinite loop and I need it taken out. It should output 5 rows with 3 columns with no duplicates in each row | So there is a bug in my code that puts it in an infinite loop. I need that taken out and I cannot find it for the life of me.
Here is the code:
#include <iostream>
#include <cstdlib>
const int MAX = 6;
const int SIZE_OF_SAMPLES = 3;
const int REP = 5;
bool inArray (int[], int, int );
void UniqRandInt (int, int, int[]);
int main() {
// std::cerr<<"in main\n";
int arr[SIZE_OF_SAMPLES];
srand(9809); //Seed random number generator.
for (int i = 0; i < REP; i++) {
UniqRandInt(MAX, SIZE_OF_SAMPLES, arr);
for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
return 0;
}
void UniqRandInt(int max, int n, int result[]) {
int cntr = 0, r;
while(cntr < n) {
r = rand(); //Get random number
r = r % (max + 1);
if (inArray(result, cntr, r)) {
result[cntr] = r;
cntr++;
}
}
return;
}
bool inArray(int array[], int arrSize, int x) {
for (int i = 0; i < arrSize; ++i) {
if (array[i] == x) {
return true;
}
}
return false;
}
It is outputting somthing like:
222
000
555
000
Here is what is supposed to output:
something like:
254
105
035
432
523
I need 5 rows with all different numbers.
| Within the while loop
while(cntr < n) {
r = rand(); //Get random number
r = r % (max + 1);
if (inArray(result, cntr, r)) {
result[cntr] = r;
cntr++;
}
}
the variable cntr is not incremented if the condition in the if statement evaluates to false. So if such a value of r that is absent in a sub-array of the array arr was generated then the while loop will be infinite.
And any value of r for the first iteration of the loop when cntr is equal to 0 is such a value that is not present in a sub-array of the array due to this function definition
bool inArray(int array[], int arrSize, int x) {
for (int i = 0; i < arrSize; ++i) {
if (array[i] == x) {
return true;
}
}
return false;
}
because within the function definition the for loop will not have an iteration and the control will be passed to the return statement
return false;
That is in this case the for loop will look like
for (int i = 0; i < 0; ++i) {
As you can see its condition will evaluate to false.
Also if you need all different numbers then at least the condition in the if statement
if (inArray(result, cntr, r)) {
should be rewritten like
if ( not inArray(result, cntr, r)) {
It seems it is enough to change this if statement to get the expected result (privided that the code does not have any other logical or other errors :)).
Pay attention to that you have a typo in this for loop
for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
std::cout << arr[i] << " ";
^^^^^^
}
You need to write
for(int j = 0; j < SIZE_OF_SAMPLES; j++) {
std::cout << arr[j] << " ";
^^^^^^
}
|
69,381,798 | 69,383,641 | Why do I get a seg fault when assigning a string pointer to a string pointer? | Consider the following simplified code:
typedef struct __attribute__ ((__packed__)) {
int numberB;
std::string strA;
} StructA;
typedef struct __attribute__ ((__packed__)) {
int numberB;
std::string strB;
} StructB;
char *ExampleClass::getBuffer(void){
char* mBuf;
int offset = 10;
return mBuf+offset;
}
void ExampleClass::ExampleFunction(StructA *A){
StructB *B = (StructB *)getBuffer();
B->numberB = A->numberA;
B->strB = A->strA;
return;
}
There is a lot of code not shown here intentionally, but I believe the root of my question do be demonstrated: Why do I get a segmentation fault when trying to assign B->strB = A->strA?
Thanks
| In getBuffer(), mBuf is uninitialized, but you add offset to it, so the pointer being return'ed is indeterminate. It certainly does not point at a valid StructB object, which is why the subsequent code in ExampleFunction() crashes when accessing B's members. Technically, this is undefined behavior, so anything can happen, a crash is not guaranteed.
But, even if mBuf were initialized to a valid char[] buffer large enough to hold a StructB object, there is still no StructB object actually being constructed in this code, thus B->numberB and B->strA are not valid objects.
getBuffer() would need to do something more like this:
char* ExampleClass::getBuffer(){
char* mBuf = ...; // point to some char[] buffer that is at
// least 10+sizeof(StructB) in size, and
// isn't deallocated when getBuffer exits...
int offset = 10;
new(mBuf+offset) StructB;
return mBuf+offset;
}
void ExampleClass::ExampleFunction(StructA *A){
StructB *B = (StructB *)getBuffer();
B->numberB = A->numberA;
B->strB = A->strA;
B->~StructB();
}
Or else, ExampleFunction() would need to do this instead:
char* ExampleClass::getBuffer(){
char* mBuf = ...; // point to some char[] buffer that is at
// least 10+sizeof(StructB) in size, and
// isn't deallocated when getBuffer exits...
int offset = 10;
return mBuf+offset;
}
void ExampleClass::ExampleFunction(StructA *A){
StructB *B = new(getBuffer()) StructB;
B->numberB = A->numberA;
B->strB = A->strA;
B->~StructB();
}
|
69,381,876 | 69,479,217 | What is oneAPI and how does it compare to TBB? | We've been using TBB for years and I see when upgrading, we're taken to a oneAPI TBB page now instead. Does oneAPI TBB replace the traditional TBB? Are both versions being maintained or is the standalone TBB now deprecated?
Trying to determine which to migrate to. Looks to me like oneAPI TBB replaces TBB, as the TBB pages haven't been updated since last year but I can't easily tell.
What also confuses me is that in the include directory, there exists both tbb/tbb.h and oneapi/tbb/tbb.h and both have the same files within them. Are they identical? I can't tell which to use.
| oneTBB is the next version of TBB. While they are almost source compatible, the binary compatibility is not preserved and some interfaces were either removed or changed. Consider the topics: Migrating from Threading Building Blocks (TBB) and TBB Revamp.
As for tbb.h, all oneAPI components reside inside oneapi/, i.e. it is recommended to use oneapi/tbb.h(while tbb/tbb.h is the same and available for source compatibility with TBB)
|
69,382,472 | 69,382,682 | Algorithm to find minimum in array of point | I have a vector of values with the minimum, but which is non-decreasing after it and non-increasing before. Here is the example:
std::vector<int> arr = {90, 80, 70, 60, 55, 62, 71, 89, 104}
In the example I want to find 55.
I want to be able to find its minimum efficiently. O(n) complexity is not enough. Supposedely, it is possible to some sort of modify binary search, but I would like to know whether there are existing solutions.
| You can achieve O(lg n) complexity as follows:
int findTurningPoint(const vector<int>& v, int begin, int end) {
int mid = (begin + end) / 2;
if (v[mid - 1] > v[mid] && v[mid + 1] > v[mid]) {
return mid;
} else if (v[mid - 1] > v[mid]) {
return findTurningPoint(v, mid + 1, end);
} else if (v[mid - 1] < v[mid]) {
return findTurningPoint(v, begin, mid - 1);
}
}
vector<int> arr = {90, 80, 70, 60, 55, 62, 71, 89, 104};
cout << findTurningPoint(arr, 0, arr.size() - 1); // 4
Method explained:
Select the element in the middle of the vector. Check whether it forms a minima by comparing it with its neighbours. If not, find whether this element and its neighbours form an increasing sequence. If they do, repeat the above process for all elements to the left of the middle element. Otherwise, repeat the process for all elements to the right of the middle element.
|
69,382,578 | 69,384,088 | The element 'xsl:stylesheet' is used but not declared in the DTD/Schema | I'm trying to convert an XSL-FO document to HTML using the "fo2html.xsl" file from RenderX. That was the suggestion from this StackOverflow post:
Converting XSL-FO to HTML
I'm using the load() method, and it works on everything up until loading the "fo2html.xsl" file.
hr = pXMLDoc->load(vSource, &vbResult);
The IXMLDOMParseError object is telling me that it's line 24 of the XML that is the problem.
<!DOCTYPE xsl:stylesheet [
<!ENTITY anchor "<xsl:apply-templates select='@id' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'/>">
<!ENTITY add-style "<xsl:call-template name='add-style-attribute' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'/>">
]>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
exclude-result-prefixes="fo">
Line 24 is the last line of the above XML. The error source is returning exclude-result-prefixes="fo">, and the reason is:
The element 'xsl:stylesheet' is used but not declared in the DTD/Schema
I've tried pDoc2->put_resolveExternals(VARIANT_TRUE); and pDoc2->setProperty(L"ProhibitDTD", v);, but neither changed anything.
What do I need to do to load "fo2html.xsl" using MSXML?
Thanks!
| You could try adding an XML declaration (see https://www.w3.org/TR/REC-xml/#sec-prolog-dtd) that indicates that the document is standalone:
<?xml version="1.0" standalone="yes" ?>
Alternatively, you might need to expand the entities yourself and get rid of the DOCTYPE declaration so there's no schema in the file.
|
69,382,679 | 69,382,718 | Will this create an object of Sales_data, or it will create variables inside the class? | I'm a 13 year old who's trying to learn C++. I bought C++ Primer and I came across something confusing for me:
struct Sales_data {/**/ } acum, trans, * salesptr = nullptr;
struct Salees_data {};
Salees_data accumm, transs, * salessptr;
I do understand what is a struct and class but I have no idea what this statement will do.
Will it create objects of the Sales_data struct, or it will create variables inside the Sales_data struct?
| This defines a Sales_data struct and
acum and trans - Two Sales_data instances
salesptr - A Sales_data pointer, initialized to nullptr
struct Sales_data {/**/ } acum, trans, * salesptr = nullptr;
This defines a Salees_data struct and
accumm and transs - Two Sales_data instances
salessptr - A Salees_data pointer, uninitialized
struct Salees_data {};
Salees_data accumm, transs, * salessptr;
or it will create variables inside the Sales_data struct?
No, there are no member variables in either of the class definitions.
I say class definitions because structs are classes too, only with a different default access specifier (public instead of private).
|
69,382,829 | 69,421,968 | How to create a QML component from C++ with component scope instance hierarchy | I have a test QML file like this:
// TestMain.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
id: root
width: G_WIDTH
height: G_HEIGHT
readonly property real x_SCALE: width / G_WIDTH
readonly property real y_SCALE: height / G_HEIGHT
title: "Test Window"
visible: true
Item {
id: wrapper
anchors.fill: parent
<innerItem>
}
}
And I want to dynamically create and assign the innerItem at runtime from C++ (I am trying to setup a testing framework). Here is what I have in C++:
engine->load("TestMain.qml");
if (engine->rootObjects().isEmpty()) { // Error }
auto root = engine->rootObjects().first();
auto wrapper = qobject_cast<QQuickItem*>(main->children()[1]);
QQmlComponent component(engine.get(), "ComponentToBeTested.qml");
auto item = qobject_cast<QQuickItem*>(component.createWithInitialProperties(props));
item->setParentItem(wrapper);
item->setSize(wrapper->size());
app->exec();
But ComponentToBeTested doesn't seem to be able to see x_SCALE and y_SCALE defined in TestMain. What am I missing here?
| This is due to missing QQmlContext.
I would need to create the QML instance passing the context:
item = qobject_cast<QQuickItem*>(
component.createWithInitialProperties(
props,
engine.contextForObject(wrapper)));
|
69,382,871 | 69,383,087 | Syntax misunderstanding and confusion | I am trying to read a file and also try the Gauss elimination process. One thing that is unclear to me is the syntax of the ifstream, when you want to read a file. In on previous example the syntax was like this:
ifstream filein;
filein.open(Filename=name of the file I will read from)
if(not filein.good()){
cout <<"There's seems to be a problem";
exit(1);
Then in my current exercise the following is written:
ifstream dfile(fname=name of the file I will read from) ;
if( not dfile)
{
cout <<"There seems to be a problem";
exit(1);
}
In both cases we are trying to read what is in the file, now my questions are:
1 - Why aren't the code sequences the same since the same things is being done, meaning we are reading from a file?
2 - In the beginning we have file.open and in the other program we don't. Then we see filein in the first one and dfile in the next one. I tried google to find out what is the meaning of them but I got no results. Can someone explain to me how this reading/writing thing works? In our classes the professor didn't took the time to do so.
| The code isn't the same because... there is almost always more than one way to write a program. The two examples are showing different approaches.
The first case uses the default constructor to create an ifstream object which, by default, doesn't open a file. Then, the ifstream::open() method is called to open a file. Finally, the method ifstream::good() is called to see if the file was opened successfully.
In the second case, a non-default constructor is used to initialize the ifstream object with the name of the file to read, and a different test is used. The not operator takes an operand of type bool, and so the compiler first calls the operator bool defined for ifstream to convert the object into a bool, which is used to determine whether a problem was encountered.
Note that, because there are various states that a file stream can in (for example, no file was found, or it couldn't be opened, or it was opened but we got to the end of it), these methods aren't necessarily going to give the same results.
There's more on this here: http://www.cplusplus.com/reference/fstream/ifstream/?kw=ifstream
|
69,382,875 | 69,382,926 | lab.cpp:112:14: error: no member named 'display' in 'std::vector<Invitee>' | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Date {
public:
Date() {
day = 12;
month = 31;
year = 2021;
}
Date(int x, int y, int z) {
day = x;
month = y;
year = z;
}
void GetDate() {
cout << "Date: " << day << "/" << month << "/" << year << endl;
}
private:
int day;
int month;
int year;
};
class Time {
public:
Time() {
hour = 12;
minute = 30;
}
Time(int x, int y) {
hour = x;
minute = y;
}
void GetTime() { cout << "Time: " << hour << ":" << minute << "\n"; }
private:
int hour;
int minute;
};
class Invitee {
string email;
public:
Invitee() { email = "jake_alvarado@csufresno.edu"; }
Invitee(string id) {
if (checkId(id) == true) {
email = id;
}
}
bool checkId(string &id) {
if (id.length() - 14 < 3) {
cout << "Invalid Email. Please Input New Email: \n";
cin >> id;
checkId(id);
}
if (isdigit(id.at(0))) {
cout << "Invalid Email. Please Input New Email: \n";
cin >> id;
checkId(id);
};
return true;
}
void display() { cout << "Email: " << email << endl; }
};
class Event {
string title;
string location;
Date *date;
Time *time;
vector<Invitee> list;
public:
Event(string t, string l, int day, int month, int year, int h, int m,
string e) {
title = t;
location = l;
date = new Date(day, month, year);
time = new Time(h, m);
list.push_back(e);
}
void display() {
cout << "Title: " << title << endl;
cout << "Location: " << location << endl;
date->GetDate();
time->GetTime();
list.display(); ///////////////////// This Line is Issue
}
};
int main() {
Event e1("Lunch", "Park", 9, 24, 2021, 12, 30, "jake_alvarado@csufresno.edu");
e1.display();
return 0;
}
I understand that the compiler is getting confused between accessing the std and vector library and accessing my class Invitee. But I'm not sure exactly how to correct this issue. Can anyone help me out with this?
The problem occurs within the Class "Event" I think and within the Class Invitee under the function "Display". I am also pretty sure my display function isn't correct.
What I want it to do is display the string email that is put inside the vector<invitee> list.
| list is a vector<Invitee> and has only the member functions defined by the std::vector class template, so you can't do list.display(). That member function doesn't exist.
You could however loop over the Invitees stored in list and call the display() member function on each element:
for(Invitee& inv : list) inv.display();
An unrelated suggestion: Make all the member functions that doesn't modify the object const:
void display() const { // <- there
cout << "Email: " << email << endl;
}
This makes it possible to call the member function in const contexts.
|
69,383,065 | 69,383,196 | How to use a template template argument from a member templated type alias of a struct | I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax:
struct A
{
template <typename T>
using type = int;
};
template <template <typename> class C>
struct B
{
// ...
};
B<typename A::type> b; // Does not compile: error: template argument for template template parameter must be a class template or type alias template
B<typename A::template type> b; // Does not compile: error: expected an identifier or template-id after '::'
B<typename A::template <typename> type> b; // Does not compile
B<typename A::template <typename> class type> b; // Does not compile
| A::type is a template, not a typename.
B<A::template type> b1; // OK
B<A::type> b2; // OK
|
69,383,144 | 69,383,286 | Code involving counting prime numbers stops working once a composite number is input. C++ | Code involving counting prime numbers stops working once a composite number is input. C++.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum=0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
else
{
break;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
j == 1;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Example of program's output:
Please enter a series of numbers, press (Q or q) to process: 2
The corresponding element for the cumulative total sequence is: 2
Please enter a series of numbers, press (Q or q) to process: 7
The corresponding element for the cumulative total sequence is: 9
Please enter a series of numbers, press (Q or q) to process: 4
The corresponding element for the cumulative total sequence is: 13
Please enter a series of numbers, press (Q or q) to process: 13
The corresponding element for the cumulative total sequence is: 26
Please enter a series of numbers, press (Q or q) to process: 17
The corresponding element for the cumulative total sequence is: 43
Please enter a series of numbers, press (Q or q) to process: q
Largest number: 17
Smallest number: 2
How many prime numbers? 2
Have a great day!
The first two inputs are prime numbers and work properly, but once I input a composite number (4) the rest of the prime numbers do not get counted as a prime number.
| You set j = 0 outside of your d-while loop. A prime number does not change the value of j, but a composite number does. Once you put in a composite number and j is changed to be something other than 0, that value stays as it is for the next iteration of your do-while loop.
Solution:
move int j = 0; to be inside the do-while loop so that it is reset for each number.
In general you should declare variables in as small/local of a scope as possible.
So while var, smallest, largest, and prime are all used outside the do-while loop, your variables num, sum, i, and j are only used within the do-while loop and so should only be declared within the loop.
Additionally, i is only used in the for-loop and so should be declared only there: for (int i = 2; i <= num / 2; i++)
Also, not relevant to your question, but I noticed that you have this:
if (num == 0 || num == 1)
{
j == 1;
}
and I'd like to point out that the statement j == 1; is useless. It checks if j is 1 and returns true or false, which then is not used.
I assume you meant this:
if (num == 0 || num == 1)
{
j = 1; //assignment, not check
}
|
69,383,240 | 69,383,312 | Determining specific type to use inside "if constexpr" | I am trying to get a feel for using "if constexpr( expr )" and perform actions if a particular type is detected.
I am tinkering with the following bit:
#include <iostream>
#include <type_traits>
struct aT {};
struct bT {};
struct cT {};
constexpr aT atype;
constexpr bT btype;
constexpr cT ctype;
int main()
{
if constexpr (std::is_same<decltype(atype), aT>::value)
std::cout << "I am type " << typeid(atype).name() << std::endl;
else if constexpr (std::is_same<decltype(btype), bT>::value)
std::cout << "I am type " << typeid(btype).name() << std::endl;
else if constexpr (std::is_same<decltype(ctype), cT>::value)
std::cout << "I am type " << typeid(ctype).name() << std::endl;
}
I get no compile errors/warnings. However, on execution, none of the if constexpr tests evaluate to true.
If anyone might shine a bit of light on this I'd appreciate it.
| constexpr implies const in the context of variable declaration. Try this:
if constexpr (std::is_same<decltype(atype), const aT>::value)
std::cout << "I am type " << typeid(atype).name() << std::endl;
|
69,383,412 | 69,383,441 | Using auto in lambda function declaration | When can auto be used as the type specifier of a variable initialized with a lambda function? I'm try to use auto in the following program:
#include <iostream>
#include <functional>
class A
{
const std::function <void ()>* m_Lambda = nullptr;
public:
A(const std::function <void ()>& lambda): m_Lambda (&lambda) {}
void ExecuteLambda()
{
(*m_Lambda)();
}
};
void main()
{
int i1 = 1;
int i2 = 2;
const auto lambda = [&]()
{
std::cout << "i1 == " << i1 << std::endl;
std::cout << "i2 == " << i2 << std::endl;
};
A a(lambda);
a.ExecuteLambda();
}
I'm using Visual Studio Community 2019 and when I start executing a.ExecuteLambda(), the program stops with the following exception:
Unhandled exception at 0x76D9B5B2 in lambda.exe:
Microsoft C ++ exception: std :: bad_function_call at memory location 0x00B5F434.
If I change the line const auto lambda = [&]() to const std::function <void ()> lambda = [&](), it works perfectly. Why is it not allowed to use auto? Can something be changed to allow it to be used?
| A lambda expression does not result in a std::function. Instead, it creates an unnamed unique class type and that has an overload for operator(). When you pass your lambda to A's constructor, it creates a temporary std::function object, and you store a pointer to that temporary object. When A's constructor ends, that temporary object is destroyed, leaving you with a dangling pointer.
To fix this, just get rid of using pointers. That would look like
#include <iostream>
#include <functional>
class A
{
std::function <void ()> m_Lambda;
public:
A(const std::function <void ()> lambda): m_Lambda (lambda) {}
void ExecuteLambda()
{
m_Lambda();
}
};
void main()
{
int i1 = 1;
int i2 = 2;
const auto lambda = [&]()
{
std::cout << "i1 == " << i1 << std::endl;
std::cout << "i2 == " << i2 << std::endl;
};
A a(lambda);
a.ExecuteLambda();
}
|
69,383,489 | 69,383,558 | SFINAE for unsigned type selection | I'm trying to use SFINAE to check if a type has an unsigned equivalent. While it seems to work for int and bool, it fails for float. From the error it seems a certain type is not defined. The question is if the template argument to enable_if is ill-formed, why isn't this removed from overload selection ?
#include <type_traits>
#include <iostream>
template <typename T>
std::enable_if_t<sizeof(std::make_unsigned<T>), bool> hasUnsigned(T x)
{
return true;
}
bool hasUnsigned(...)
{
return false;
}
int main()
{
float x; // If it's int, or char, it below displays true
std::cout << std::boolalpha << hasUnsigned(x) << std::endl;
}
Error with float
In file included from has_unsigned.cc:1:
/usr/include/c++/10/type_traits: In instantiation of ‘struct std::make_unsigned<float>’:
has_unsigned.cc:5:18: required by substitution of ‘template<class T> std::enable_if_t<(sizeof (std::make_unsigned<_Tp>) != 0), bool> hasUnsigned(T) [with T = float]’
has_unsigned.cc:18:48: required from here
/usr/include/c++/10/type_traits:1826:62: error: invalid use of incomplete type ‘class std::__make_unsigned_selector<float, false, false>’
1826 | { typedef typename __make_unsigned_selector<_Tp>::__type type; };
| ^~~~
/usr/include/c++/10/type_traits:1733:11: note: declaration of ‘class std::__make_unsigned_selector<float, false, false>’
1733 | class __make_unsigned_selector;
| ^~~~~~~~~~~~~~~~~~~~~~~~
| You are using make_unsigned on an invalid type (see below) which makes the behavior undefined or program ill-formed. A better approach would be to check if it's an integer:
std::enable_if_t<std::is_integral_v<T>, bool>
From std::make_unsigned:
If T is an integral (except bool) or enumeration type, provides the member typedef type which is the unsigned integer type corresponding to T, with the same cv-qualifiers.
If T is signed or unsigned char, short, int, long, long long; the unsigned type from this list corresponding to T is provided.
If T is an enumeration type or char, wchar_t, char8_t (since C++20), char16_t, char32_t; the unsigned integer type with the smallest rank having the same sizeof as T is provided.
Otherwise, the behavior is undefined. (until C++20)
Otherwise, the program is ill-formed. (since C++20)
|
69,383,928 | 69,384,472 | Macro for detecting non-static non-type members in classes | In C++ Templates - The complete guide, 2nd edition, at page 434, a macro is defined to generate predicates testing the existence of a nontype memeber in a class:
#include <type_traits>
#define DEFINE_HAS_MEMBER(Member) \
template<typename T, typename = void> \
struct HasMemberT_##Member : std::false_type {}; \
template<typename T> \
struct HasMemberT_##Member<T, std::void_t<decltype(&T::Member)>> : std::true_type {};
The the text reads
It would not be difficult to modify the partial specialization to exclude cases wehre &T::Member is not a pointer-to-member type (which amounts to excluding static data members).
So I've played around with static_asserts and compiler errors and remember about types of static and non-static of members of classes:
struct A {
int begin;
static int end;
};
static_assert(std::is_same<decltype(&A::begin), decltype(A::begin) A::*>::value, ""); // passes
static_assert(std::is_same<decltype(&A::end), decltype(A::end)*>::value, ""); // passes
And thought that maybe a good modification of the lambda above aimed at detecting non-static members only is to change
: std::true_type
to
: std::is_same<decltype(&T::Member), decltype(T::Member) T::*>
whereas if I wanted to check for static memebers only, I could change it to
: std::is_same<decltype(&T::Member), decltype(T::Member)*>
Is it really this easy? Or am I overlooking something important?
| You are overlooking non-static member functions.
The primary use case of the traits created by DEFINE_HAS_MEMBER is to check for the existence of a particular method. To borrow from the terminology in the question, a range is defined by having begin() and end(). While the trait created by the original macro works, your extra condition does not.
prog.cc:7:61: error: invalid use of non-static member function 'int A::begin()'
7 | static_assert(std::is_same<decltype(&A::begin), decltype(A::begin) A::*>::value, "");
| ^~~~~
prog.cc:7:72: error: template argument 2 is invalid
7 | static_assert(std::is_same<decltype(&A::begin), decltype(A::begin) A::*>::value, "");
|
The reason in standartese is this:
[expr.prim.id]
2 An id-expression that denotes a non-static data member or non-static member function of a class can only be used:
as part of a class member access in which the object expression refers to the member's class or a class derived from that class, or
to form a pointer to member ([expr.unary.op]), or
if that id-expression denotes a non-static data member and it appears in an unevaluated operand. [ Example:
struct S {
int m;
};
int i = sizeof(S::m); // OK
int j = sizeof(S::m + 42); // OK
— end example ]
These are the only valid uses of something like T::Member. Non static member functions don't hit any of the bullets, so the construct is ill-formed when used to define the body of HasMemberT_##Member's specialization. No SFINAE, just a hard error.
|
69,383,936 | 69,384,677 | Failing to compare two template template types with fixed number of arguments | I have a SFINAE template version of is_same for comparing template template arguments.
It generally works as expected on both templates with fixed and variadic number of template parameters:
namespace eld::util::traits
{
template<template<typename...> class ATT, template<typename...> class BTT>
struct is_same_tt : std::false_type
{
};
template<template<typename...> class TT>
struct is_same_tt<TT, TT> : std::true_type
{
};
}
template<typename AT, typename BT, typename CT>
struct fixed_args_number
{
};
template<typename...>
struct variadic_args
{
};
static_assert(eld::util::traits::is_same_tt<fixed_args_number, fixed_args_number>(), "");
static_assert(eld::util::traits::is_same_tt<variadic_args, variadic_args>(), "");
But when I compare a template template with a fixed number of template parameters to a member template template, I get false, though true, when parameters are variadic.
template<template<typename...> class TT>
struct designated
{
template<typename... T>
using tt_type = TT<T...>;
};
// Does not compile
//static_assert(
// eld::util::traits::is_same_tt<fixed_args_number, designated<fixed_args_number>::tt_type>(),
// "");
static_assert(eld::util::traits::is_same_tt<variadic_args, designated<variadic_args>::tt_type>(),
"");
What is the reason? (I only checked it with MinGW64)
The initial problem is to find in a type list a designated class that satisfies the condition for the equality of template template types.
| Neither should work: GCC has a bug of helpfulness that it considers an alias template to be the same as the underlying template if they’re sufficiently similar. The fixed/variadic mismatch, while still usable in practice, is enough for it to revert to conforming behavior.
|
69,384,631 | 69,385,288 | Extract a c++ variant type from a list of type names | I am designing a pipeline class that needs to extract a std::variant from a list of distinct types in a filter class. For example:
template <typename T>
struct Filter {
using type = T;
// ...
}
template <typename... Filters>
struct Pipeline {
// how to properly define the variant type?
// std::variant<Filters::type...> buffer;
};
For example, if I have three different filter types:
Filter<int>, Filter<double>, Filter<std::string>
then, the variant should be std::variant<int, double, std::string>. However, I need to remove duplicate types in the variant, for example:
Filter<int>, Filter<double>, Filter<std::string>, Filter<int>
then, the variant should NOT be std::variant<int, double, std::string, int> but std::variant<int, double, std::string>. Additionally, I need to replace void with std::monostate. For example:
Filter<int>, Filter<double>, Filter<void>, Filter<int>, Filter<void>
then, the variant should be std::variant<int, double, std::monostate>.
How to design such a metaclass that can properly define the variant type based on the given type names template <typename... Filters> using c++17?
| Based on Piotr's answer:
#include <variant>
template <typename T, typename... Ts>
struct unique { using type = T; };
template <typename... Ts, typename U, typename... Us>
struct unique<std::variant<Ts...>, U, Us...>
: std::conditional_t<(std::is_same_v<U, Ts> || ...),
unique<std::variant<Ts...>, Us...>,
unique<std::variant<Ts..., U>, Us...>> {};
template <typename... Ts>
using variant_t = typename unique<
std::variant<>,
std::conditional_t<std::is_same_v<Ts, void>, std::monostate, Ts>...>::type;
then your Pipeline can be defined as:
template <typename T>
struct Filter {
using type = T;
};
template <typename... Filters>
struct Pipeline {
variant_t<typename Filters::type...> buffer;
};
Demo.
|
69,384,923 | 69,384,973 | How to condense a struct in a class c++? | I have a a.h which has a class d. I am wondering how to make a shorthand way to use the struct 'a' inside of my class.
//a.h
class d
{
public:
struct a
{
int val;
}
};
//a.cpp
#include "a.h"
using d::a; //line with error
a methodName()
{
//does stuff
return object_of_type_a;
}
| what about this one
class d
{
public:
struct a
{
int val;
};
};
typedef struct d::a da;
|
69,385,934 | 69,386,265 | Forced to call the base constructor when using virtual inheritance although it will never be called? | I have a class Base which has a parameterized constructor and two classes Middle1 and Middle2 which virtually inherit from Base (in order to solve the diamond problem). In addition, class Foo inherits from Middle1 and Middle2.
Foo now calls the Base constructor explicitly and passes the parameter.
class Base
{
private:
int value;
protected:
Base(int& value) { this->value = value; }
};
class Middle1 : virtual public Base
{
protected:
Middle1() { }
};
class Middle2 : virtual public Base
{
protected:
Middle2() { }
};
class Foo : public Middle1, public Middle2
{
public:
Foo(int& value) : Base(value) { }
};
However, the code does not compile because Base lacks a default constructor and thus Middle1 and Middle2 don't have a default constructor to call, but need one which can be called by Foo.
Of course, I could now change the constructors of Middle1 and Middle2 to call the constructor of Base, too:
Middle1(int& value) : Base(value) { }
//...
Middle2(int& value) : Base(value) { }
// and then change my constructor of Foo:
Foo(int& value) : Base(value), Middle1(value), Middle2(value) { }
However, it seems rather clunky - especially given that because of the virtual inheritance, the Base constructor will never be called by Middle1 or Middle2 (they are not meant to be initialized, i.e. are basically abstract classes). Thus, having to introduce the parameter to the constructors of both Middle1 and Middle2 seems rather useless.
Is there any other way to make the above code compile without also having to introduce parameterized constructors in Middle1 and Middle2?
| In virtual inheritance, the most-derived class has to directly call all of its ancestor constructors. Since Base doesn't have a default constructor, Middle1() and Middle2() can't compile if they can't pass an int& to Base().
However, in the code you have shown, there is no reason for Base() to take an int by reference. Pass it by value instead, and then Middle1() and Middle2() can pass 0 to Base():
class Base
{
private:
int value;
protected:
Base(int value = 0) { this->value = value; }
};
class Middle1 : virtual public Base
{
protected:
Middle1() { }
};
class Middle2 : virtual public Base
{
protected:
Middle2() { }
};
class Foo : public Middle1, public Middle2
{
public:
Foo(int value) : Base(value) { }
};
Though, I would suggest passing a pointer (or a std::optional) instead:
class Base
{
private:
int value;
protected:
Base(int* avalue = nullptr) { if (avalue) this->value = *avalue; }
};
class Middle1 : virtual public Base
{
protected:
Middle1() { }
};
class Middle2 : virtual public Base
{
protected:
Middle2() { }
};
class Foo : public Middle1, public Middle2
{
public:
Foo(int& value) : Base(&value) { }
};
|
69,386,167 | 69,391,142 | I'm using boost::filtered_graph, but the output of print_graph and write_graphviz differ -- any idea why? | I'm new to boost::graph (and boost really). I want to use boost::filtered_graph many times on the same original graph, and use the write_graphviz function to let me visualise the results. I think my understanding must be off though because the following code isn't doing what I think it should: to output the same graph with print_graph and write_graphviz.
MWE (compiled with C++14, gcc 9.3 on Ubuntu 20.04; boost version 1.73):
#include <cstdio>
#include <fstream>
#include <iostream>
#include <boost/graph/copy.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphviz.hpp>
using namespace std;
typedef boost::adjacency_list< boost::vecS, boost::vecS > Graph;
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef boost::graph_traits<Graph>::vertex_iterator vertex_iterator;
template <typename GraphType>
struct uniform_random_vertex_filter
{
uniform_random_vertex_filter() : prob(1.0) {} // default constructor is required
uniform_random_vertex_filter(float p) : prob(p) {}
bool operator()(const typename boost::graph_traits<GraphType>::vertex_descriptor& v) const
{
return drand48() < prob; // randomly select some vertices
}
private:
float prob;
};
int main(int argn, char **argc) {
unsigned int n = 5;
ofstream of;
Graph g(n);
vertex_iterator vit, uit, vend;
// build a complete graph on n vertices (I'm sure there's a simpler command for this):
for (boost::tie(vit,vend) = vertices(g); vit != vend; ++vit) {
for (uit = vit; uit != vend; ++uit) {
if (uit == vit) { continue; }
add_edge(*vit, *uit, g);
}
}
std::cout << "Original graph (OriginalGraph.dot):" << std::endl;
boost::print_graph(g);
of.open("OriginalGraph.dot", std::ios::trunc);
boost::write_graphviz(of, g);
of.close();
uniform_random_vertex_filter<Graph> vfilter(0.5);
boost::filtered_graph<Graph, boost::keep_all, uniform_random_vertex_filter<Graph> >
filteredGraph(g, boost::keep_all(), vfilter);
std::cout << "Filtered graph -- random selection of vertices (RandomVertexSelection.dot):" << std::endl;
boost::print_graph(filteredGraph);
Graph F;
boost::copy_graph(filteredGraph,F);
of.open("RandomVertexSelection.dot", std::ios::trunc);
boost::write_graphviz(of, F);
of.close();
return 0;
}
Which produces this output:
> Debug/BoostGraphFilter
Original graph:
0 --> 1 2 3 4
1 --> 2 3 4
2 --> 3 4
3 --> 4
4 -->
Filtered graph -- random selection of vertices (RandomVertexSelection.dot):
0 --> 1 2 3 4
1 --> 2 3
2 --> 3
>
--- which is fine, but the dot files are:
> cat OriginalGraph.dot
digraph G {
0;
1;
2;
3;
4;
0->1 ;
0->2 ;
0->3 ;
0->4 ;
1->2 ;
1->3 ;
1->4 ;
2->3 ;
2->4 ;
3->4 ;
}
> cat RandomVertexSelection.dot
digraph G {
0;
1;
2;
}
Hence the filtered_graph that's printed isn't the same as that written to .dot file (which has lost all the edges in this case).
Can someone please help me understand what I've done wrong?
| Your filter is random. And since you didn't retain any state to make it transparent or deterministic, the results are random. Simple as that.
Ironically, at the same time you managed to get completely deterministic results across runs because you fail to use random correctly (e.g. seeding the generator).
In your case, the simplest would be to copy before first use: Live On Coliru
using Graph = boost::adjacency_list<boost::vecS, boost::vecS>;
Graph make_complete_graph(size_t n);
void report(Graph const& g, std::string name);
struct uniform_random_vertex_filter {
float prob = 1.0f;
bool operator()(auto v) const {
return drand48() < prob;
}
};
int main() {
Graph g = make_complete_graph(5);
report(g, "OriginalGraph");
for (int pct = 30; pct < 100; pct+=10) {
Graph F;
boost::copy_graph(boost::filtered_graph( //
g, //
boost::keep_all{},
uniform_random_vertex_filter{pct / 100.0f}),
F);
report(F, "RandomVertexSelection_" + std::to_string(pct));
}
}
// build a complete graph on n vertices
Graph make_complete_graph(size_t n)
{
Graph g(n);
for (auto [vit, vend] = vertices(g); vit != vend; ++vit) {
for (auto uit = vit; uit != vend; ++uit) {
if (uit != vit)
add_edge(*vit, *uit, g);
}
}
return g;
}
void report(Graph const& g, std::string name) {
boost::print_graph(g, std::cout << name << ":");
std::ofstream of(name + ".dot");
boost::write_graphviz(of, g);
}
If you want a stable random "cut" of a graph, make the filter stateful. This could be handy e.g. if you have a graph too large to copy.
Fixing The Random
As a sidenote, fixing the random to actually be seeded and reliably uniform:
Live On Coliru
#include <boost/graph/copy.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graphviz.hpp>
#include <fstream>
#include <iostream>
#include <random>
using Graph = boost::adjacency_list<boost::vecS, boost::vecS>;
using Filter = std::function<bool(Graph::vertex_descriptor)>;
Graph make_complete_graph(size_t n);
void report(Graph const& g, std::string name);
int main() {
Graph g = make_complete_graph(5);
report(g, "OriginalGraph");
std::mt19937 urbg{std::random_device{}()};
for (int pct = 30; pct < 100; pct += 10) {
Graph F;
std::bernoulli_distribution dist(pct / 100.);
boost::copy_graph(
boost::filtered_graph(g, boost::keep_all{},
Filter([&](auto) { return dist(urbg); })),
F);
report(F, "RandomVertexSelection_" + std::to_string(pct));
}
}
// build a complete graph on n vertices
Graph make_complete_graph(size_t n)
{
Graph g(n);
for (auto [vit, vend] = vertices(g); vit != vend; ++vit) {
for (auto uit = vit; uit != vend; ++uit) {
if (uit != vit)
add_edge(*vit, *uit, g);
}
}
return g;
}
void report(Graph const& g, std::string name) {
boost::print_graph(g, std::cout << name << ":");
std::ofstream of(name + ".dot");
boost::write_graphviz(of, g);
}
Now prints different random cuts every run.
|
69,386,453 | 69,641,441 | Qt holds Ctrl to drag software elements into the File Explorer, but the File Explorer does not accept them | I can receive when I don't press Ctrl, I need to implement Ctrl pressed for copy and Ctrl not pressed for cut (move), how can I achieve this?
| I have solved this problem, the QDrag::exec() function has some parameters to choose from, I rewrite it as exec(Qt::ActionMask, Qt::MoveAction); and it solves the problem perfectly.
|
69,386,540 | 69,386,827 | How to implement a universal function for both sequence and associative container? | I am thinking to write a function that works both for sequence and associative container. That's something like
template<class C, class V = typename C::key_type>
bool has_val(const C& c, const V& v)`
Inside the function, I would like to
Check if class C has member function const_iterator find(key_type) const for container classes like set/map.
If it doesn't contain find(), then we use std::find() for sequence container like std::vector.
What's the best practice to check, (1)?
If what I described above is not the best, please advise if there's a better approach?
(Unfortunately I don't have access to newer Folly with macro FOLLY_create_member_invoker but I do have FOLLY_CREATE_HAS_MEMBER_FN_TRAITS. I couldn't successfully get it through, though)
| Use SFINAE to detect whether to use c.find():
#include <algorithm>
template <class C, class V, typename = void>
constexpr inline bool use_mem_find = false;
template <class C, class V>
constexpr inline bool use_mem_find<C, V,
std::void_t<decltype(std::declval<const C&>().find(std::declval<const V&>()))>> = true;
template<class C, class V>
bool has_val(const C& c, const V& v) {
auto end = std::end(c);
if constexpr (use_mem_find<C, V>)
return c.find(v) != end;
else
return std::find(std::begin(c), end, v) != end;
}
Demo.
|
69,386,661 | 69,387,232 | Why do I get a error in leetcode submission but pass in IDE using the same code? | I am solving LeetCode question: 234. Palindrome Linked List:
Given the head of a singly linked list, return true if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
The number of nodes in the list is in the range [1, 10⁵].
0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Using C++ I get the error below:
=================================================================
==42==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000098 at pc 0x00000037ac7d bp 0x7ffc1760fda0 sp 0x7ffc1760fd98
READ of size 8 at 0x602000000098 thread T0
#2 0x7f5a8c3e70b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x602000000098 is located 8 bytes inside of 16-byte region [0x602000000090,0x6020000000a0)
freed by thread T0 here:
#3 0x7f5a8c3e70b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
previously allocated by thread T0 here:......
Here is my code:
/*code only in VS
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head->next) {
return true;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* prev = slow;
ListNode* current = prev->next;
while (current) {
ListNode* temp = current->next;
current->next = prev;
prev = current;
current = temp;
}
while (head != slow)
{
if (head->val != prev->val) {
return false;
}
head = head->next;
prev = prev->next;
}
return true;
}
};
/*code only in VS
int main()
{
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(0);
ListNode* c = new ListNode(3);
ListNode* d = new ListNode(4); //[1,0,3,4,0,1]
ListNode* e = new ListNode(0);
ListNode* f = new ListNode(1);
a->next = b;
b->next = c;
c->next = d;
d->next = e;
e->next = f;
Solution solution;
cout << solution.isPalindrome(a);
}*/
I can run it and get the right answer in my IDE (Visual Studio 2019 Community), but get an error in the LeetCode submission.
Any idea why this would happen?
| The error occurs when the Leet Code test system will try to release the memory used by the previous test case, before launching the next one.
Your code leaves the list in a state where it will run in cycles: the node that follows slow has been rewired by your code to point back to slow.
We can imagine how the Leet Code clean-up code will free the node that slow refers to, then free the next node's memory, and then arrive again at slow which was already freed/deleted. This is the cause of this error. It is therefore important that you leave the list in a consistent state, where it has the original number of nodes, and there are no cycles.
To resolve the error quicly, just add this line before the last loop:
slow->next = nullptr;
However, this leaves the second (reversed) half of your list unreachable for Leet Code to clean up. That's not really fair (although fast). To do it properly, make slow stop at the left side of the center when the list size is even (by moving fast one step ahead), and then rewire the tail of the first half with the (new) head of the second half (which was reversed):
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head->next) {
return true;
}
ListNode* slow = head;
ListNode* fast = head->next; // Stop loop sooner when size is even
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode* prev = nullptr; // this will be assigned to the new tail
ListNode* current = slow->next;
while (current) {
ListNode* temp = current->next;
current->next = prev;
prev = current;
current = temp;
}
slow->next = prev; // link tail of first half to head of reversed part
while (prev) // Continue the walk in second half until the list's end
{
if (head->val != prev->val) {
return false;
}
head = head->next;
prev = prev->next;
}
return true;
}
};
|
69,387,447 | 69,407,723 | Unable to resize win 32 window | I'm trying to learn how to create a window in win 32. This is as far as I have got with it. The problem I'm facing is I'm unable to create a window that can be resized by the user. I'm hoping that someone could help me solve this newbie problem.
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
std::string msg = "";
UINT width = 0;
UINT height = 0;
switch(uMsg)
{
case WM_SIZE:
width = LOWORD(lParam);
height = HIWORD(lParam);
if(width<(height*600)/800) SetWindowPos(hWnd, NULL, 0, 0, width, height, SWP_NOMOVE|SWPNOZORDER);
return true;
case WM_SIZING:
width = LOWORD(lParam);
height = HIWORD(lParam);
if(width<(height*600)/800) SetWindowPos(hWnd, NULL, 0, 0, width, height, SWP_NOMOVE|SWPNOZORDER);
return true;
case WM_DESTROY:
PostQuitMessage(0);
return true;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, INT nCmdShow)
{
WNDCLASSEX wnd = {0};
wnd.lpszClassName = "WindowLearn";
wnd.hInstance = hInstance;
wnd.lpfnWndProc = windowProc;
wnd.cbSize = sizeof(WNDCLASSEX);
wnd.style = CS_HREDRAW | CS_VREDRAW;
RegisterClassEx(&wnd);
HWND hWnd = CreateWindowEx(NULL, "WindowLearn", "WindowLearnChild", WS_THICKFRAME | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, 0, 0, 800, 600, NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, nCmdShow);
MSG msg = {0};
float pTime = 0.0f;
BOOL result;
while(msg.message != WM_QUIT)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Window gets created OK, but with this when I try to resize the window the window gets stuck to the mouse.
| It appears that you want to to idle processing, meaning having some tasks done for your directX application when no event are present in the event loop.
There are 2 different ways of doing that:
dedicate a separate thread for background processing. It adds the complexity of multiprocessing, but allows to do all the processing as a single piece of code, and let the system affect time slices to the event loop and the background processing.
use a modified event loop that does chunks of background processing when no event are present. PeekMessage is the key here:
...
MSG msg = {0};
for (;;)
{
if (PeekMessage(&msg, NULL, 0, 0, 0, 0) {
if (! GetMessage(&msg, NULL, 0, 0, 0)) break; // msg is WM_QUIT
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
// do some idle processing for a short time
// no event will be processing during that
...
}
}
The nice point is that you do not need any multi-threading, but you have to explicitely split you backgroung processing in short time slices.
|
69,388,002 | 69,388,277 | Overloaded function templates that differ only in their return types in C++ | It is well known that ordinary functions that differ only in their return type cannot be overloaded in C++.
But this limitation does not hold for overloaded function templates, for example:
int f(auto) { return 1; }
auto f(auto) { return 2; }
All compilers accept it, demo: https://gcc.godbolt.org/z/qj73Mzehd
Why does the language make such exception for the templates?
If the return type of the overloaded functions differ, then it will be possible to select one of the functions using the cast to expected function type. Surprisingly, Clang allows one to resolve the ambiguity even if the return type is actually the same, for example:
((int(*)(int))f)(3);
selects
int f(auto) { return 1; }
Demo: https://gcc.godbolt.org/z/snfvbq1ME
Is Clang wrong here?
|
Why does the language make such exception for the templates?
You mean this?
signature [defns.signature.templ]
⟨function template⟩ name, parameter-type-list, enclosing namespace (if any), return type, template-head, and trailing requires-clause (if any)
Yes, the return type is there. It's what always made possible things like
template<typename T>
typename std::enable_if<std::is_integral<T>::value>::type foo(T&);
template<typename T>
typename std::enable_if<!std::is_integral<T>::value>::type foo(T&);
SFINAE is why the return type is included in the signature. Substitution failure is possible in the return type, so it's part of signature comparison. You can still potentially generate two conflicting specializations to overload on (in the general case, not in the example), but the templates would be different.
|
69,388,168 | 69,388,475 | Is there a way to detect compiler -fxxxx flags in C++ code in clang? | Is there a way to detect compiler -fxxxx flags in C++ code in clang?
I don't want to store the whole command line in binary, I want to test an individual option.
I want it to provide compilation error or warning if some flag is specified to avoid the code crashing at runtime.
| There is no good way of detecting the presence of the flag in C++ code.
The compiler does not communicate the presence of this flag to the code.
You could write some code that changes behavior based on the presence of the flag, but doing so is very fragile, and not guaranteed to actually work. Intentionally introducing UB into your program is not a particularly good idea. But if you want to do it, it would be something along these lines:
void mark_nonnull(__attribute__((nonnull)) int* p) {}
bool deletes_checks_2(int* p) __attribute__((noinline)) {
mark_nonnull(p);
if (p) return true;
else return false;
}
bool deletes_checks() { return deletes_checks_2(nullptr); }
A better idea is to intercept this at the build system level. You could add a rule that compiles a test file to LLVM IR similar to this: https://reviews.llvm.org/differential/changeset/?ref=1123266 And then you check the resulting IR if the checks are there and abort the build if they aren't.
|
69,388,518 | 69,388,818 | weird compilation failure with overloaded const function and compiling with -pedantic | The code below fails to compile.
if I remove the bool foo(bool) overload, then the a.foo(&b); call compiles.
if I remove the const qualifier from bool foo(bool*) const; then the a.foo(&b); call compiles.
While writing the question I found out that without -pedantic to gcc it also compiles
I can't understand why...
struct A {
bool foo(bool){
return true;
}
bool foo(bool*) const {
return false;
}
};
int main() {
A a;
a.foo(true);
bool b;
a.foo(b);
a.foo(&b); // does not compile
const_cast<const A&>(a).foo(&b); // does compile
}
and the compilation error:
error: call of overloaded ‘foo(bool*)’ is ambiguous
a.foo(&b);
^
/tmp/asdasd.cpp:4:8: note: candidate: bool A::foo(bool)
bool foo(bool){
^~~
/tmp/asdasd.cpp:7:8: note: candidate: bool A::foo(bool*) const
bool foo(bool*) const {
thanks
| First of all, pointers are implicitly convertible to bool. So an overload set between a pointer and a bool will be ambiguous unless one of the overloads represents a perfect match on all parameters.
To better visualize the issue I extracted the member functions to free functions, which is basically the same thing:
struct A {};
void foo(A&, bool) {}
void foo(const A&, bool*) {}
int main() {
A a;
bool x;
foo(a, &x);
}
Neither of the function is a perfect match for foo, as the first one needs to convert the bool* into a bool and the second one needs to convert A to const.
Technically adding const would be a better match, but ISO C++ says it's still ambiguous in this case. When you remove -pedantic from gcc, it tells you exactly that:
<source>:9:9: warning: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
9 | test(a, &x);
| ~~~~^~~~~~~
Also, const_cast is a bit of a big hammer for adding const as it can also remove const, which can be very dangerous. Better use std::as_const or implement your own if you can't use C++17 yet.
|
69,388,612 | 69,388,848 | Conversion Constructor using map argument giving Errors | I made a small console program which has a class called Class_Room. I can make objects of school classrooms from it and store student names, roll numbers and ages in it. The student data are stored in a map. I wanted to make classroom object like this:
Class_Room class8C = {
{"student x", 2}, //2 for rollnumber
{"student y", 3}
};
So i made a conversion constructor:
Class_Room(std::map<int, std::string> map) {
for (std::pair<int, std::string> value : map) {
student_data[value.first] = { value.second, "NIL" };
}
}
but i get errors:
no instance of constructor Class_Room::Class_Room matches argument list
"initializing": cannot convert "initializer list" to Class_Room
Here is my whole code:
#include <iostream>
#include <vector>
#include <string>
#include <map>
class Class_Room {
public:
Class_Room(std::map<int, std::string> map) {
for (std::pair<int, std::string> value : map) {
student_data[value.first] = { value.second, "NIL" };
}
}
void new_student(int roll, std::string name, int age = 0)
{
data.clear();
data.push_back(name);
if (age != 0) {
data.push_back(std::to_string(age));
}
else {
data.push_back("NIL");
}
student_data[roll] = data;
}
std::map<int, std::vector<std::string>> get_student_data_map()
{
return student_data;
}
private:
std::map<int, std::vector<std::string>> student_data;
std::vector<std::string> data;
};
std::ostream& operator<< (std::ostream& output, Class_Room classroom)
{
std::map<int, std::vector<std::string>> student_data = classroom.get_student_data_map();
for (std::pair<int, std::vector<std::string>> value : student_data) {
output << value.first << " => " << value.second[0] << ", " << value.second[1] << "\n";
}
return output;
}
int main() {
Class_Room class8C = {{"Ihsan", 2}};
std::cout << class8C;
}
I'm a beginner to c++ and don't know what went wrong, any help would be appreciated.
| There's a bit more to this answer, but I'll go with the thing that will solve your issue, then will try to explain some of the more interesting bits so that you learn something from it.
GIST: Your map is the other way around
// your map has keys of type int, values of type string
Class_Room(std::map<int, std::string> map) { // pairs of <int, string>
for (std::pair<int, std::string> value : map) {
student_data[value.first] = { value.second, "NIL" };
}
}
// and then you want to insert pairs of <string, int>
// keys of type string, values of type int
// like: {"Ihsan", 2}
Inverting those should put you on the right track.
// Class_Room class8C = {{2, "Ihsan"}}; // but this is not enough!
// you actually need something along these lines:
Class_Room class8C{
std::map<int, std::string>{{2, "Ihsan"}}};
// or
Class_Room class8C{
{ // creates the map
{ // creates the pair to insert
2, std::string("Ihsan")
}
}
};
The error you're getting is because the compiler is trying to find the right constructor and it fails.
First, you need a map to pass to your constructor. The compiler will have to figure a way to create that map before calling your ctor (if that map doesn't already exist).
If you look at the constructors for std::map, you'll notice that the 5th one takes an initializer list: https://en.cppreference.com/w/cpp/container/map/map
The value_type template for that initializer list is also: <int, string>, same as the map itself. So the order matters.
You could have also created the map beforehand, but I guess you want concise code.
|
69,388,842 | 69,388,922 | How to pass an argument to a member function wrapped in std::function<void()>? | At first it seemed clear that I shouldn't be able to do this, but then I discovered that it can be done with free functions.
Here is an example where I pass void() functions from Child to Parent. The parent calls the function when their Frame comes up.
I have figured out the syntax to pass free functions with arguments, but I can't figure out how to pass a member function of Child with an argument.
Please help.
#include <iostream>
#include <vector>
#include <map>
#include <functional>
void f_Free1() { std::cout << "Hi there hello. I'm a free function without arguments."; }
void f_Free2(int i) { std::cout << "Hi there hello. I'm a free function with an argument. It's " << i; }
class Parent
{
std::map<unsigned int, std::vector<std::function<void()>>> Tasks;
protected:
void addTask(unsigned int frame, std::function<void()> task) { Tasks[frame].push_back(task); }
public:
virtual ~Parent() {}
unsigned int Frame = 0;
void tick()
{
if (Tasks.count(Frame))
{
for (auto task : Tasks[Frame])
{
task();
}
}
Frame++;
}
};
class Child : public Parent
{
void f_Child1() { std::cout << "This is a private Child function without arguments. "; }
void f_Child2(int i) { std::cout << "This is a private Child function with an argument. It's " << i; }
public:
Child()
{
addTask(3, f_Free1);
addTask(5, [a = int(4)] () { f_Free2(a); } ); // THIS WORKS!!!
addTask(7, std::function<void()> { std::bind(&Child::f_Child1, this) });
addTask(9, std::function<void()> { std::bind([a = int(4)]() { &Child::f_Child2(a), this) } }); // CAN'T MAKE THIS WORK
}
};
int main()
{
Child child;
for (unsigned int i = 0; i < 12; i++)
{
std::cout << "[" << child.Frame << "]";
child.tick(); // runs tasks whose frames are up
std::cout << std::endl;
}
return 0;
}
| Ditch the bind.
Use [this]() { f_Child1(); } and [this]() { f_Child(4); }.
Also, the free version can be just []() { f_Free2(4); }.
|
69,388,966 | 69,396,133 | Can't use defined type in C Python extension | I'm following the C Python extension tutorial to create new type.
I created the file custom.c, setup.py and added the following line to my CMakeLists.txt:
execute_process(WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} COMMAND ${PYTHON_BIN} setup.py build)
But when I run
Py_Initialize();
PyImport_AddModule("custom"));
PyRun_SimpleString("import custom\nmycustom = custom.Custom()");
PyErr_Print();
I got Attribute error: module 'custom' has no attribute 'Custom' even if I add the path to generated .pyd to sys.path
Python help on module is
Help on module custom:
NAME
custom
FILE
(built-in)
I am running on Windows 10 with Python 3.8
But I can import and use the module directly from a Python terminal
| PyImport_AddModule("custom"));
See https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject; this looks in sys.modules for "custom". If it can't find it then it creates a new empty module named "custom". It does not search the path for files.
import custom
This looks in sys.modules for "custom". If it finds a module there then it returns it. If it doesn't find a module then it searches the Python path for a suitable module.
You're programmatically creating a blank module, and that is getting used instead of the module on the Python path.
|
69,389,353 | 69,508,439 | How do you update a UTextureRenderTarget2D in C++? | I'm referenced @J. Rehbein's ask.
How do you update a UTextureRenderTarget2D dynamically in C++?
And use public modules ("Core", "CoreUObject", "Engine", "InputCore", "UMG", "GameplayTasks", "Landscape", "RHI", "RenderCore").
Why printed assertion failed log?
How fix assertion failed problem?
Please, teachers.
void AWorldCreator::BeginPlay()
{
Super::BeginPlay();
if (RenderTarget != nullptr) {
RenderTarget->InitCustomFormat(Width, Height, PF_B8G8R8A8, true);
auto region = FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);
FTexture2DRHIRef TextureRHI = RenderTarget->GameThread_GetRenderTargetResource()->GetRenderTargetTexture();
ENQUEUE_RENDER_COMMAND(UpdateTextureRegionsData)(
[=](FRHICommandListImmediate& RHICmdList)
{
check(TextureRHI.IsValid()); // Assertion failed line
});
}
}
| I want change URenderTargetTexture2D's texture. i'm tried how that use 2_DrawMaterial.
And i feel hardness from how convert UMaterialInstanceDynamic to UMaterialInterface.
So, next tried how that use ENQUEUE_RENDER_COMMAND. Blocked again.
So I posted a question.
Sorry and thanks everyone for read my awkward(weird?) question.
...
I succeed URenderTargetTexture2D updating without ENQUEUE_RENDER_COMMAND.
I converted UMaterialInstanceDynamic to UMaterialInterface thought UStaticMeshComponent.
I use UStaticMeshComponent's functions (GetMaterial, SetMaterial).
UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(Material, GetWorld());
...
StaticMeshComponent->SetMaterial(0, DynamicMaterial);
...
canvas->K2_DrawMaterial(StaticMeshComponent->GetMaterial(0), Position, Size, CoordinatePosition);
Thank you.
|
69,390,666 | 69,391,033 | std::move behaves differently on different compilers? | I was experimenting with a simple code for calculating cosine similarity:
#include <iostream>
#include <numeric>
#include <array>
#include <cmath>
float safe_divide(const float& a, const float& b) { return b < 1e-8f && b > -1e-8f ? 0.f : a / b; }
template< size_t N >
float cosine_similarity( std::array<float, N> a, std::array<float, N> b )
{
const float&& a2 = std::move( std::inner_product( a.begin(), a.end(), a.begin(), 0.f ) );
const float&& b2 = std::move( std::inner_product( b.begin(), b.end(), b.begin(), 0.f ) );
const float&& dot_product = std::move( std::inner_product( a.begin(), a.end(), b.begin(), 0.f ) );
return safe_divide( dot_product, ( std::sqrt(a2) * std::sqrt(b2) ) );
}
int main(){
std::array<float, 5> a{1,1,1,1,1}, b{-1,1,-1,1,-1};
std::cout<<cosine_similarity(a,b);
}
On x86-64 Clang 12.0.1 (and other versions), it compiles and gives the right answer.
However on every version of GCC that I've tested it compiles, but gives the wrong answer (or no answer).
It raises a few questions:
Is my use of std::move even valid?
Why does only Clang seem to work with this and no other compiler?
What does the standard say?
Here's a link to the experiment: https://godbolt.org/z/KWbMYorrc
| What is happening is:
std::inner_product( a.begin(), a.end(), a.begin(), 0.f ) returns a temporary, whose lifetime normally ends at the end of the statement
when you assign a temporary directly to a reference, there is a special rule that extends the life of the temporary
however, the problem with: std::move( std::inner_product( b.begin(), b.end(), b.begin(), 0.f ) ); is that the temporary is no longer assigned directly to a reference. Instead it is passed to a function (std::move) and its lifetime ends at the end of the statement.
std::move returns the same reference, but the compiler doesn't intrinsically know this. std::move is just a function. So, it doesn't extend the lifetime of the underlying temporary.
That it appears to work with Clang is just a fluke. What you have here is a program exhibiting undefined behaviour.
See for example this code (godbolt: https://godbolt.org/z/nPGxMnrzf) which mirrors your example to some extent, but includes output to show when objects are destroyed:
#include <iostream>
class Foo {
public:
Foo() { std::cout << "Foo was created\n"; }
~Foo() { std::cout << "Foo was destroyed\n"; }
};
Foo getAFoo() {
return Foo();
}
Foo &&doBadThings() {
Foo &&a = std::move(getAFoo());
Foo &&b = std::move(getAFoo());
std::cout << "If Foo objects have been destroyed, a and b are dangling refs...\n";
return std::move(a);
}
int main() {
doBadThings();
}
Output is:
Foo was created
Foo was destroyed
Foo was created
Foo was destroyed
If Foo objects have been destroyed, a and b are dangling refs...
In this case Clang and Gcc both produce the same output, but it's enough to demonstrate the problem.
|
69,391,091 | 69,391,714 | g++ is recognized by cmd but not by vs code | I'm trying to set c/c++ environment in my visual studio code. I have installed the mingw and set the environmental variable of the bin folder. However upon running a code in vs code, it shows the following error:
g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and
try again. At line:1 char:40
cd "e:\vsCodes\Cpp Codes" ; if ($?) { g++ threen1.cpp -o threen1 } ; ...
CategoryInfo : ObjectNotFound: (g++:String) [], CommandNotFound Exception
FullyQualifiedErrorId : CommandNotFoundException
But command prompt shows the following message when I enter g++ --version:
g++ (tdm64-1) 10.3.0 Copyright (C) 2020 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There
is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
I have tried solving the issue following the answers in this thread.
| You are using powershell terminal, If you dont know what powershell is or you dont need powershell, I recommend you to run Command prompt terminal (cmd). It's available in terminal menu here:
In powershell you can verify that g++ in PATH running this command echo $env:path, it's powershell equivalent of echo %PATH%
|
69,391,923 | 69,392,845 | CZMQ set send HWM / set receive HWM | Doesn't this have to work?
#include <czmq.h>
zsock_t *sockout = zsock_new_pub("inproc://a");
zsock_set_sndhwm (sockout, 20);
How to set HWM and/or BUF sizes?
UPDATE:
I added some more code and works in this context:
#include <string>
#include <czmq.h>
int main (void){
zsock_t *sockout = zsock_new_pub("inproc://a");
zsock_set_sndhwm (sockout, 20);
std::string data2send;
for (size_t i = 0; i < 1000; i++){
data2send = "data" + std::to_string(i);
zsock_send(sockout, "s", data2send.c_str() );
}
}
Although zsock_set_sndhwm (sockout, 20); works in this particular context.
I have to figure out the context where it doesn't works.
| I am answering my own question for a complete solution pub/rec
Publisher code:
#include <string>
#include <czmq.h>
int main (void)
{
zsock_t *sockout = zsock_new_pub("ipc://a");
zsock_set_sndhwm (sockout, 20);
zsock_set_rcvhwm (sockout, 20);
std::string data2send;
for (size_t i = 0; i < 1000; i++){
data2send = "data: " + std::to_string(i);
sleep(1);
zsock_send(sockout, "s", data2send.c_str() );
}
}
Subscriber (Receiver) code:
#include <string>
#include <czmq.h>
#include <iostream>
int main (void){
zsock_t *sockin = zsock_new_sub("ipc://a", "");
zsock_set_sndhwm (sockin, 20);
zsock_set_rcvhwm (sockin, 20);
char *m;
std::string m_str;
while(true){
zsock_recv(sockin, "s", &m);
std::cout << "**READ: " << m << "\n\n";
}
}
|
69,392,275 | 69,392,489 | Setting up eigen math library with visual studio | I have downloaded eigen and am trying to set it up with visual studio. My current file structure looks like this:
project:
src
Vendor
src:
main.cpp
Vendor:
Eigen
Here is my main.cpp file.
#include "../Vendor/Eigen/Core/Matrix.h"
#include <iostream>
int main()
{
Vector3f v;
}
I am getting hundreds of errors.
The first error is identifier uintptr_t is undefined in file atomic.
Edit: I opened the file "../Vendor/Eigen/Core/Matrix.h" and it seems to contain errors (some lines have squiggly red underlines).
| It is only a guess depending on your source structure but you copied the wrong sources:
You need to copy the Eigen directory into your Vendor not the src which is in Eigen directory. And then try to:
#include <Eigen/Core>
The structure of Eigen
Eigen
|--> .gitlab
|--> Eigen / you need to copy this full directory
|--> src / I guess you copied this
|--> Cholesky
|--> ...
...
|--> bench
|--> ...
...
|
69,392,516 | 69,395,497 | Does not work _cgets. Identifier not found | I am trying to compile the following code in visual studio 2019:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
char* p;
buffer[0] = 3;
p = _cgets(buffer); // problem with _cgets
printf("\ncgets read %d symbols: \"%s\"\n", buffer[1], p);
printf("A pointer is returned %p, buffer[2] on %p\n", p, &buffer);
return 0;
}
But I see the following error:
main.cpp(11,9): error C3861: '_cgets': identifier not found
| _cgets is no longer available, use _cgets_s instead:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
size_t sizeRead;
auto error = _cgets_s(buffer, &sizeRead);
printf("\ncgets read %zu symbols: \"%s\"\n", sizeRead, buffer);
return 0;
}
Or the much simpler c++ code:
#include <iostream>
#include <string>
int main()
{
std::string buffer;
std::getline(std::cin, buffer);
std::cout << "read " << buffer.size() << " characters \"" << buffer << "\"\n";
}
|
69,392,733 | 69,393,378 | an illegal memory access was encountered | I am a beginner at CUDA programming, writing a program composed of a single file main.cu which is shown below.
#include <iostream>
#include <opencv2/opencv.hpp>
#define DEBUG(str) std::cerr << "\033[1;37m" << __FILE__ << ":" << __LINE__ << ": \033[1;31merror:\033[0m " << str << std::endl;
#define CUDADEBUG(cudaError) \
if (cudaError != cudaSuccess) \
DEBUG(cudaGetErrorString(cudaError));
#define ERROR(str) \
{ \
DEBUG(str); \
exit(1); \
}
__global__ void makeGrey(
unsigned char *&pimage,
const int &cn,
const size_t &total)
{
unsigned i = blockDim.x * blockIdx.x + threadIdx.x;
unsigned icn = i * cn;
printf("%u\n", i);
if (i < total)
{
float result = pimage[icn + 0] * .114 +
pimage[icn + 1] * .587 +
pimage[icn + 2] * .299;
pimage[icn + 0] = result; //B
pimage[icn + 1] = result; //G
pimage[icn + 2] = result; //R
// pimage[icn + 3] *= result; //A
}
}
int main(int argc, char **argv)
{
if (argc != 3)
ERROR("usage: executable in out");
cv::Mat image;
unsigned char *dimage;
image = cv::imread(argv[1], cv::IMREAD_UNCHANGED);
if (!image.data)
ERROR("Image null");
if (image.empty())
ERROR("Image empty");
if (!image.isContinuous())
ERROR("image is not continuous");
const size_t N = image.total();
const int cn = image.channels();
const size_t numOfElems = cn * N;
const int blockSize = 512;
const int gridSize = (N - 1) / blockSize + 1;
CUDADEBUG(cudaMalloc(&dimage, numOfElems * sizeof(unsigned char)));
CUDADEBUG(cudaMemcpy(dimage, image.data, numOfElems * sizeof(unsigned char), cudaMemcpyHostToDevice));
makeGrey<<<gridSize, blockSize>>>(dimage, cn, N);
cudaError_t errSync = cudaGetLastError();
cudaError_t errAsync = cudaDeviceSynchronize();
if (errSync != cudaSuccess)
std::cerr << "Sync kernel error: " << cudaGetErrorString(errSync) << std::endl;
if (errAsync != cudaSuccess)
std::cerr << "Async kernel error: " << cudaGetErrorString(errAsync) << std::endl;
CUDADEBUG(cudaMemcpy(image.data, dimage, numOfElems * sizeof(unsigned char), cudaMemcpyDeviceToHost)); //line 73
CUDADEBUG(cudaFree(dimage)); //line 74
cv::imwrite(argv[2], image);
return 0;
}
When I execute the program, I get
Async kernel error: an illegal memory access was encountered
/path-to-main.cu:73: error: an illegal memory access was encountered
/path-to-main.cu:74: error: an illegal memory access was encountered
I checked CV_VERSION macro which is 4.5.3-dev, and Cuda Toolkit 11.4 is installed (nvcc version 11.4). Also afaik, the kernel does not execute at all (I used Nsight gdb debugger and printf). I could not understand why I am accessing an illegal memory area. I appreciate any help. Thank you in advance.
| As mentioned in a comment, your GPU function takes arguments by references.
__global__ void makeGrey(
unsigned char *&pimage,
const int &cn,
const size_t &total)
This is bad, passing a reference to a function means more or less that you're passing an address where you can find the value, not the value itself.
In your situation those values are in memory used by Host, NOT Device/GPU memory, when GPU tries to access those values it will most likely crash.
The types you are trying to pass, unsigned char*, int and size_t are very cheap to copy, there's no need to pass them by reference in the 1st place.
__global__ void makeGrey(
unsigned char *pimage,
const int cn,
const size_t total)
There are tools provided by nvidia to debug CUDA applications, but I'm not really familiar with them, you can also use printf inside GPU functions, but you will have to organize output from potentially thousand of threads.
In general, whenever you call GPU functions, be very cautious about what you're passing as parameters, as they need to be passed from Host memory to Device memory. Usually you want to pass everything by value, any pointers need to point to Device memory, and watch out from references.
|
69,393,323 | 69,394,678 | C++: initializing constexpr lambda to constexpr/non-constexpr variable | I'm reading the "C++ 17 The Complete Guide" book by Nicolai M. Josuttis and cannot understand the following example
auto squared1 = [](auto val) constexpr { // example 1. compile-time lambda calls
return val * val;
};
and the statement to it
If (only) the lambda is constexpr it can be used at compile time,
but squared1 might be initialized at run time, which means that some
problems might occur if the static initialization order matters (e.g,
causing the static initialization order fiasco).
The author suggests considering the following solution
constexpr auto squared = [](auto val) constexpr {
return val * val;
};
meaning that it would somehow avoid the previous problem.
I don't understand the problem with the first example regarding to the initialization order and therefore cannot understand how the author's solution improves it. Could you please explain it and give an example which demonstrates disadvantages of the first example?
| The statement auto square1 = initialize a global variable, not even constant. This is a runtime variable that you can mutate, assign to and potentially other stuff.
You could very well initialize such variable like this:
auto returnMeALambda() {
int capture = rand() % 2;
return [capture](auto val) {
return val * val + capture;
}
}
auto square1 = returnMeALambda();
As you can see, the code of returnMeALambda is strictly runtime, so square1 is forcibly initialized at runtime.
Those variables don't have a value that it usable at compile time. The compiler might very well initialize it at runtime, even if not forced to. This has cost at runtime, and with the static initialization order fiasco, you could technically use the lambda before it is initialized, or even use another global before it is initialized:
extern int baseval;
auto returnMeALambda() {
int capture = baseval + rand() % 2;
return [capture](auto val) {
return val * val + capture;
}
}
auto square1 = returnMeALambda();
int baseval = square1(2);
This code will always end up being undefined behaviour since it always use an uninitialized variable, no matter the initialization order.
The solution proposed by the author is to initialize the variable as a constexpr. This do three things in this case:
Makes the variable const. You cannot mutate its value at runtime.
Constant initialization is now mandated. The value of square1 is encoded in the executable binary code.
Makes the variable value available at compile time. You can now use the variable in constexpr context.
The second point is the property the author seek as a solution. The variable is guaranteed it won't ever be initialized at runtime, since the value is available at compile time and guarantees constant initialization by the compiler.
Note that in C++20 you can apply the second point by itself without forcing the value to be const using constinit.
constinit int value = 9;
Now the compiler is forced to initialize the value using constant initialization, but also the variable is mutable at runtime. This effectively solve the initialization order fiasco given you can constant initialize your variables.
|
69,393,860 | 69,394,694 | Use of decltype Gives warning Reference to Local Variable | I am trying to understand how decltype works in C++ and so going through examples. Just when i thought i understood what it means, i tried to create examples to confirm that and i got something that i cannot understand. The example is as follows:
#include <iostream>
template<typename T>
auto func2(T a, T b) -> decltype(b < a ? a:b)
{
//return a;//this gives warning of reference to local variable
//return b;//this gives warning of reference to local variable
return (b < a ? a:b);//this does not give warning of reference to local variable
}
int main()
{
std::cout << "Hello World" << std::endl;
int b = func2(4,3);
return 0;
}
As shown in the above code when i use the statement return a; or return b; i get a warning saying reference to local variable which is because we should never pass reference or pointers to local variable to outside their scope. But what i don't understand is that why are we not getting the same warning when i use return (b < a ? a:b);.
My thinking is that decltype(b < a ? a:b) should result in int&. And so when i write return (b < a ? a:b); a reference to local a or b should be returned depending on whether which one is greater and we should get the warning.
Check out the code here
|
But what i don't understand is that why are we not getting the same warning when i use return (b < a ? a:b);
How clever compiler warnings can be is entirely up to the compiler vendor; see e.g.
Warnings on sign conversion when assigning from the result of unsigned division
and when you catch a bug through a compiler warning, the general lesson should arguably be
Phew, glad my compiler caught that one: I need to understand this construct better
as opposed to
Why didn't the compiler also catch my other bug?
Understanding the construct where the bug appeared
I am trying to understand how decltype works in C++ and so going through examples. Just when i thought i understood what it means, i tried to create examples to confirm that and i got something that i cannot understand.
For completeness, [expr.cond]/5 covers the resulting type of a ternary conditional-expression its last two operands are both glvalues of the same type and value category:
If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.
Meaning in your example, the type of the result (for function arguments deducing the template parameter to int) is int:
void f(int x) {
auto result = false ? x : x;
static_assert(std::is_same_v<decltype(r), int>);
}
[dcl.type.decltype]/1 governs the rules for decltype, and particularly [dcl.type.decltype]/1.5 applies here:
For an expression E, the type denoted by decltype(E) is defined as follows:
[...]
/1.5 otherwise, if E is an lvalue, decltype(E) is T&, where T is the type of E;
Thus, in the particular (deduced) specialization func2<int>(...) of your example, the return type is deduced to int&.
|
69,394,369 | 69,394,475 | C++ constexpr constructor initializes garbage values | I wanted a simple class which would encapsulate a pointer and a size, like C++20's std::span will be, I think. I am using C++ (g++ 11.2.1 to be precise)
I want it so I can have some constant, module-level data arrays without having to calculate the size of each one.
However my implementation 'works' only sometimes, dependent on the optimization flags and compiler (I tried on godbolt). Hence, I've made a mistake. How do I do this correctly?
Here is the implementation plus a test program which prints out the number of elements (which is always correct) and the elements (which is usually wrong)
#include <iostream>
#include <algorithm>
using std::cout;
using std::endl;
class CArray {
public:
template <size_t S>
constexpr CArray(const int (&e)[S]) : els(&e[0]), sz(S) {}
const int* begin() const { return els; }
const int* end() const { return els + sz; }
private:
const int* els;
size_t sz;
};
const CArray gbl_arr{{3,2,1}};
int main() {
CArray arr{{1,2,3}};
cout << "Global size: " << std::distance(gbl_arr.begin(), gbl_arr.end()) << endl;
for (auto i : gbl_arr) {
cout << i << endl;
}
cout << "Local size: " << std::distance(arr.begin(), arr.end()) << endl;
for (auto i : arr) {
cout << i << endl;
}
return 0;
}
Sample output:
Global size: 3
32765
0
0
Local size: 3
1
2
3
In this case the 'local' variable is correct, but the 'global' is not, should be 3,2,1.
| I think the issue is your initialization is creating a temporary and then you're storing a pointer to that array after it has been destroyed.
const CArray gbl_arr{{3,2,1}};
When invoking the above constructor, the argument passed in is created just for the call itself, but gbl_arr refers to it after its life has ended. Change to this:
int gbl_arrdata[]{3,2,1};
const CArray gbl_arr{gbl_arrdaya};
And it should work, because the array it refers to now has the same lifetime scope as the object that refers to it.
|
69,394,698 | 69,394,761 | Storing derived class to the vector C++ | I have problem with storing child class object to the vector. I have parent class
class IngameObject
{
protected:
bool clickable = false;
};
I have second class
class Character : public IngameObject
{
protected:
bool clickable = true;
};
Now, I am trying to create new instance of Character and stroe it to the vector. I have vector defined as
std::vector<IngameObject*> objVector;
Code for creating Characters and stroring them is
for(int i = 0; i < 1; i++)
{
int a = i*32;
Character *c = new Character(this->holderTextures["texture"], sf::IntRect(a, a, 32, 32), sf::Vector2f(2*a, 10.f));
std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
this->objVector.emplace_back( c );
std::cout << instanceof<Character>(this->objVector.back()) << " TEST" <<std::endl;
}
In the first case, instance is Character. After emplace_back to the objVector is type of instance IngameObject and bool clickable is set to false. What I am doing wrong?
EDIT
Instanceof is defined as
template<typename Base, typename T>
inline bool instanceof(const T*) {
return std::is_base_of<Base, T>::value;
}
| Storing a derived class in a std::vector as you do is correct: the problem is not related with polymorphism or "storing derived class in a vector":
#include <iostream>
#include <vector>
class IngameObject
{
protected:
bool clickable = false;
};
class Character : public IngameObject
{
protected:
bool clickable = true;
};
int main()
{
std::vector<IngameObject*> objVector;
Character *c = new Character();
objVector.emplace_back( c );
delete c;
return 0;
}
The problem is related with you you implement instanceof
To solve the instanceof function, your class need to be polymorphic. Then, the pointer to the base class can be converted to the derived class, thus confirming that it is instanceof the base class:
#include <iostream>
#include <vector>
class IngameObject
{
protected:
bool clickable = false;
virtual ~IngameObject() = default;
};
class Character : public IngameObject
{
protected:
bool clickable = true;
};
template<class T, class U>
inline bool instanceof(U* ptr) {
return nullptr != dynamic_cast<T*>(ptr);
}
int main()
{
std::vector<IngameObject*> objVector;
Character *c = new Character();
std::cout << instanceof<Character>(c) << " TEST" <<std::endl;
objVector.emplace_back( c );
std::cout << instanceof<Character>(objVector.back()) << " TEST" <<std::endl;
delete c;
return 0;
}
Note: to make Base polymorphic, it needs to have at least one virtual method.
|
69,394,739 | 69,395,005 | Can I make conan usage optional to users of my library that uses conan? | Using conan to develop a library seems to force users of the library to also use conan. Is there a (standard) way I can replace the CONAN_PKG::protobuf reference in Targets.cmake with just protobuf?
Context
I am using cmake to build a static C++ library using protobuf, using conan to handle the protobuf dependency, ie
target_link_libraries(mylib
PUBLIC
CONAN_PKG::protobuf
)
When I install this library locally , ie ninja install the created MylibTargets.cmake contains a reference to CONAN_PKG::protobuf
set_target_properties(Mylib::Mylib PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include/mylib;${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "CONAN_PKG::protobuf"
This forces users of my library to use conan to resolve the CONAN_PKG::protobuf dependency. (I want users of the library to be able to use the protobuf headerfiles).
I am using
install(EXPORT MylibTargets
FILE MylibTargets.cmake
NAMESPACE Mylib::
DESTINATION lib/cmake/mylib
)
to generate MylibTargest.cmake
| Yes, all the modern CMake integrations can achieve some level of transparent integration. First attempts are cmake_find_package and cmake_find_package_multi, but the most modern one are:
CMakeDeps: see docs generates xxx-config.cmake scripts, so consumers can do a normal find_package(protobuf ...)
CMakeToolchain: see docs generates a conan_toolchain.cmake to help mapping the Conan settings to CMake syntax (and can be used with -DCMAKE_TOOLCHAIN_FILE=conan_toolchain.cmake
With this integration, it is possible to keep CMakeLists.txt completely agnostic of Conan. This integration will become the standard one in Conan 2.0.
|
69,394,803 | 69,394,963 | What are the parameters of the 0xC00000FD (Stack Overflow) error? | I've created a function which allocates an array, which is too big, on the stack (C++). The run results with this error:
Unhandled exception at 0x000000013F4DEBF7 in xxx.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000000000043000).
I've never seen the "parameters" section assigned to a particular instance of a stack overflow error, and my search on the internet yielded no results. Does anyone know what these parameters mean? I've observed that for multiple runs of the same code, the first parameter stays constant and the second parameter changes, but stays in the 6-5 digit range. I'm very curious as to what they mean.
In case it matters, here's a MRE:
constexpr uint8_t LOG_2_OF_BUCKET_COUNT = 20;
int main(){
uint32_t histogram[1 << LOG_2_OF_BUCKET_COUNT];
return 0;
}
| The "parameters" are described in the documentation for the EXCEPTION_RECORD structure. Everything in that exception message came from EXCEPTION_RECORD, first ExceptionAddress, then a module name derived from ExceptionAddress, then ExceptionCode and its friendly name, and finally NumberParameters are read from ExceptionInformation[].
Unfortunately for your purposes, the official documentation only describes parameters for EXCEPTION_ACCESS_VIOLATION and EXCEPTION_IN_PAGE_ERROR and says for all other exception types the parameters array has undefined contents.
With that caveat noted, there is consistency between the parameters for the two exception types where they are documented, and stack overflow is internally detected via an access violation, so it makes sense to decode as described for EXCEPTION_ACCESS_VIOLATION. Specifically:
The first element of the array contains a read-write flag that indicates the type of operation that caused the access violation.
If this value is zero, the thread attempted to read the inaccessible data.
If this value is 1, the thread attempted to write to an inaccessible address.
If this value is 8, the thread causes a user-mode data execution prevention (DEP) violation.
The second array element specifies the virtual address of the inaccessible data.
Comparing to your captured exception information, the first element being a flag for (illegal read / illegal write / NX violation) is entirely believable. The second element does not look much like a virtual address, however. Perhaps for EXCEPTION_STACK_OVERFLOW it gets reported relative to the thread stack base address.
|
69,395,029 | 69,395,125 | Phantom \.txt file in windows | It seems like it is possible to create a file \.txt in windows that can be read, but I'm not able to access it any other way or see if it exists. This seems to only work for \.txt since I can't create other files with backslashes in it such as a\.txt
string filename = "\\.txt";
// make file
ofstream writer(filename);
writer << "This file exists" << endl;
writer.close();
// read file
ifstream reader(filename);
string line;
getline(reader, line);
cout << line << endl;
reader.close();
When I use ls -lia in bash, this file doesn't show up at all, but the program above reads it fine (I can remove the part that creates the file and run it later so the file does persists), how does this work?
| On Windows, ofstream writer("\\.txt") creates a file named .txt in the root of the current drive. It is a perfectly valid file name.
ofstream writer("a\\.txt") tries to create a file named .txt in the a subdirectory of the current directory. The a directory must exist in order for it to succeed. Most likely it does not exist, therefore it fails for you.
To create a directory you can use either the mkdir function (which has compatibility problems with other OSes because Windows is not POSIX compatible), or the CreateDirectory WINAPI function, that is Windows specific. After calling CreateDirectoryA("a"), the "a\\.txt" path should work.
|
69,395,155 | 69,395,231 | Is it portable to self move a std::string? | std::string s = "y";
s = "x" + std::move(s) + "x";
Send(std::move(s));
Microsoft STL implementation checks for this, but is it mandated by the standard?
It looks more clean than insert + append or two variables approach.
Note: I know I can do Send(std::move("x" + std::move(s) + "x")), but real code is not so simple.
| There's no self-move here. A self-move is something like this:
s = std::move(s);
which means
s.operator=(std::move(s));
In other words, when operator= is called, this points to the same string as the argument.
In your code, "x" + std::move(s) will be evaluated first, which returns a std::string prvalue. In other words, not a reference to s, although it's possible that the concatenation might "steal" the buffer from s. Then the second + is evaluated, and another prvalue is returned. Finally, operator= is called. At this point, the prvalue on the right-hand side has to be materialized, because it's bound to the rvalue reference argument of operator=. So all we have is s being assigned from a temporary object, which might have stolen s's buffer. But no matter: s is an object of a standard library type, which means that it is in a "valid but unspecified state". Since s is in a valid state, and is not the same object as the RHS, there is no problem.
|
69,395,260 | 69,395,423 | Why I'm getting error: invalid operands to binary expression after overloaded += operand? | I'm trying to overload the += operator for a simple mathematical Vector class, to sum the elements of two vectors, like this:
vector1 += vector2
Part of Vector2D.h:
#ifndef _VECTOR2D_H_
#define _VECTOR2D_H_
class Vector2D
{
public:
Vector2D():x(0),y(0){}
~Vector2D(){}
/* All the mathematical operation ... */
// Overloading operators
Vector2D& operator+=(const Vector2D& rhs);
Vector2D& operator*=(const Vector2D& rhs);
Vector2D& operator/=(const Vector2D& rhs);
Vector2D& operator-=(const Vector2D& rhs);
private:
double x;
double y;
};
Then part of Vector2D.cpp:
#include "Vector2D.h"
Vector2D& Vector2D::operator+=(const Vector2D& rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
Now, in the .cpp class, I want to use the operator:
void MovingObject::move()
{
m_pVelocity += m_pAcceleration;
m_pVelocity->limit(m_fMax_speed);
m_pPosition += m_pVelocity();
m_pAcceleration->zero();
}
The variables m_pVelocity, m_pAcceleration and m_pPosition are all Vector2D* pointers.
When I try to compile, this is what I get from the compiler:
Why does this happen? I've read a lot of papers, and I've seen a lot of examples, and all of them work, but mine does not.
Am I missing something?
| It looks like on this line you have two pointers
m_pVelocity += m_pAcceleration;
so you'd need to dereference them to use this operator
*m_pVelocity += *m_pAcceleration;
|
69,395,803 | 69,396,071 | Check if there's duplicate element in an container in compile time with C++20 | One simple way of doing this prior to C++20 is to do a nested loop:
template<typename Container>
constexpr bool has_duplicate(Container&& container)
{
for (auto it1 = container.cbegin(); it1 != container.cend(); ++it1)
for(auto it2 = container.cbegin(); it2 != it1; ++it2)
if (*it1 == *it2)
return 1;
return 0;
}
With the addition of init-statement in range-based for loop, and the introduction of ranges::subrange, I believe this function could be rewritten with range-based for loop:
template<std::ranges::input_range Container>
constexpr bool has_duplicate(Container&& container)
{
for(auto it = container.cbegin(); const auto& obj1 : container)
for(const auto& obj2 : std::ranges::subrange(container.cbegin(), it++))
if(obj1 == obj2)
return 1;
return 0;
}
While it worked fine on gcc, it fails to compile with clang, unless I manually set it with libc++: https://godbolt.org/z/KM4a9zazs, with the following error:
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/12.0.0/../../../../include/c++/12.0.0/bits/iterator_concepts.h:982:13: error: no matching function for call to '__begin'
= decltype(ranges::__cust_access::__begin(std::declval<_Tp&>()));
Am I doing something wrong, or was it clang?
I've also tried:
template<std::ranges::input_range Container>
constexpr bool has_duplicate(Container&& container)
{
for(auto index = 0ull; const auto& obj1 : container)
for(const auto& obj2 : container | std::ranges::views::take(index++))
if(obj1 == obj2) return 1;
return 0;
}
Once again gcc worked with no problem, but clang failed with either libraries.
| Godbolt uses libstdc++ by default, even when compiling with Clang, which is somewhat confusing.
Whether Clang should actually fully support linking towards libstdc++ or not, I cannot say, but e.g. the following Clang bug report highlights the same issue:
Bug 46746 - Clang can't compile libstdc++ ranges
Minimal example from the bug report:
#include <ranges>
void foo() {
std::ranges::iota_view iota(2, 10);
iota.begin();
}
error: no matching function for call to '__begin'
|
69,395,818 | 69,901,405 | Use Boost as a git submodule with CMake | I want to use the Boost library for my C++ project (more precisely, I'm interested in the Boost Graph Library). I'd like it to be inside my git repository, as a git submodule, as it's done for every other dependency.
For example, if I want to start a project with fmt dependency as a git submodule, I do:
mkdir my_project
cd my_project
git init .
Then, I want to add fmt as a submodule, on tag 8.0.0:
mkdir deps
git submodule add https://github.com/fmtlib/fmt.git deps/fmt
cd deps/fmt
git checkout 8.0.0
Then, I go back to my project's root folder:
cd ../..
And I create the following files:
main.cpp
#include <fmt/format.h>
int main() {
fmt::print("Hello, World!\n");
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(test_boost)
add_subdirectory(deps/fmt)
add_executable(test_boost main.cpp)
target_link_libraries(test_boost fmt::fmt)
Then, we're able to build:
mkdir build
cd build
cmake ..
make
And the binary works fine, expectedly printing Hello, World!, which is great.
Now if I want to add boost, version 1.77.0:
git submodule add https://github.com/boostorg/boost deps/boost
git submodule update --init --recursive # To get Boost's own submodules.
cd deps/boost
git checkout boost-1.77.0
cd ../..
Now I want to use this boost folder as dependency of my project, and this is where it gets tricky. I read here that from version 1.77, I should be able to use find_package() to do this, as it obseletes the FindBoost thing:
find_package(Boost 1.77.0 REQUIRED CONFIG PATHS deps/boost/tools/boost_install)
But I get the following error:
-- Module support is disabled.
-- Version: 8.0.1
-- Build type: Debug
-- CXX_STANDARD: 11
-- Required features: cxx_variadic_templates
CMake Error at CMakeLists.txt:6 (find_package):
Could not find a configuration file for package "Boost" that is compatible
with requested version "1.77.0".
The following configuration files were considered but not accepted:
/home/me/tests/boost_so/my_project/deps/boost/tools/boost_install/BoostConfig.cmake, version: unknown
-- Configuring incomplete, errors occurred!
See also "/home/me/tests/boost_so/my_project/cmake-build-debug/CMakeFiles/CMakeOutput.log".
See also "/home/me/tests/boost_so/my_project/cmake-build-debug/CMakeFiles/CMakeError.log".
I tried other things as well, but I run into one of the following errors:
The same one as above.
CMake uses my Boost installation from /usr/local, which is not what I want.
I'm using CMake 3.17.2. Is it possible to do this or am I missing something ?
| I found a solution which seems quite simple. You can just add_subdirectory() as shown for fmt.
The complete CMakeLists.txt file looks like this:
cmake_minimum_required(VERSION 3.17)
project(test_boost)
add_subdirectory(deps/fmt)
add_subdirectory(deps/boost EXCLUDE_FROM_ALL)
add_executable(test_boost main.cpp)
target_link_libraries(test_boost fmt::fmt Boost::graph)
Then, you can see that the following compiles and runs fine:
#include <fmt/format.h>
#include <boost/graph/adjacency_list.hpp>
#include <array>
#include <utility>
#include <iostream>
int main() {
fmt::print("Hello, World!\n");
enum { topLeft, topRight, bottomRight, bottomLeft };
std::array<std::pair<int, int>, 4> edges{{
std::make_pair(topLeft, topRight),
std::make_pair(topRight, bottomRight),
std::make_pair(bottomRight, bottomLeft),
std::make_pair(bottomLeft, topLeft)
}};
typedef boost::adjacency_list<boost::setS, boost::vecS,
boost::undirectedS> graph;
graph g{edges.begin(), edges.end(), 4};
std::cout << boost::num_vertices(g) << '\n';
std::cout << boost::num_edges(g) << '\n';
g.clear();
return 0;
}
Which outputs
Hello, World!
4
4
|
69,396,146 | 69,396,193 | c++ - Destructor called on assignment | I'm still learning the basics of c++ so I may not have had the correct vocabulary to find the answer to my question but I couldn't find this mentioned anywhere.
If I have a class with a constructor and destructor why does the destructor get called on the new data when I am assigning to the class?
For example:
#include <iostream>
class TestClass {
public:
int* some_data;
TestClass() {
std::cout << "Creating" << std::endl;
some_data = (int*)malloc(10*sizeof(int));
}
~TestClass() {
std::cout << "Deconstructing" << std::endl;
free(some_data);
}
TestClass(const TestClass& t) : some_data{t.some_data} {
std::cout << "Copy" << std::endl;
}
};
int main() {
TestClass foo;
std::cout << "Created once" << std::endl;
foo = TestClass();
std::cout << "Created twice" << std::endl;
}
which prints:
Creating
Created once
Creating
Deconstructing
Created twice
Deconstructing
free(): double free detected in tcache 2
Aborted (core dumped)
So after following this in the debugger it appears the deconstructor is called on the newly created data which is confusing to me. Shouldn't the original data be freed once and then at the end of execution the new data should be freed? It seems like the original data is never freed like this.
| Your object owns a raw pointer to allocated memory, but does not implement a proper copy constructor that makes an allocation and copies the data behind the pointer. As written, when you copy an object, the pointer is copied, such that now two objects point to the same address (and the old one that the just-assigned-to object is leaked.)
When the temporary goes out of scope, it deletes its pointer but the copy (foo) still points to it. When foo goes out of scope, it deletes the same pointer again, causing this double free error you're seeing.
If you need to write a destructor to clean up, you almost always need to also provide copy and assignment operations, or disable them.
SUGGESTIONS:
hold the pointer in a std::unique_ptr which will fail to compile if you try to copy it. This forces you to deal with the issue. Also, malloc and free are mainly for C or low-level C++ memory management. Consider using new and delete for allocations instead. (unique_ptr uses delete by default, not free, and you must not mix them.)
alternately, delete the copy constructor and assignment operator
also, consider when you want to move from an xvalue (temporary or moved lvalue), you can pilfer the allocation from the right-hand-side. So this class is a good candidate for move constructor and move assignment.
|
69,396,459 | 69,396,719 | C++ default value initialization changes with input-output streams | I am researching an interesting behavior for two code segments, that give me unexpected behavior.
Describing The behavior
Code segment 1:
#include <iostream>
using namespace std;
int main()
{
long long n;
long long m;
// cin >> n;
cout << m;
return 0;
}
When I run this (for example in https://www.onlinegdb.com/online_c++_compiler), the value printed in the console (the value inside the variable m) is 0. This is expected and corresponds to the fact that the long long type has a default initialization to 0 (zero initialization).
Code segment 2:
#include <iostream>
using namespace std;
int main()
{
long long n;
long long m;
cin >> n;
cout << m;
return 0;
}
By uncommenting the line with cin and adding any value, I do not get 0, but rather a different value depending on the number I input for n. Other characteristics of this behavior are:
For different input values for n, we get different values in m.
Each time the same value is given for n, we get the same value in m.
Defining n or m static results in the expected behavior, which is m carrying the value 0.
The same behavior persists if m, n are ints
The unexpected behavior is thus that m does not have a default initialization to 0.
Discussion
My explanation
The uncommented line, cin >> n, creates a new thread for execution.
The new thread creates a new stack to which all local variables are copied.
Since m is not initialized in the original stack, the value it carries is indeterminate in the new stack. It depends on the state of the current stack. But the state of the stack is dependent on the state of the original copied stack, which, in turn, is dependent on the value of the input n.
Issues
My explanation is congruent with characteristic 3. Nevertheless, I do not know how to check for this using a single thread. Moreover, the reason might be something more than stack-related such that even with one and only one thread, the behavior persists. What do you think?
| C++ initialization is super complicated. However, this case is rather simple (confusing terminology aside ;). You are right that both m and n are default initialized. Though, immediately after that your interpretation is rather off. It starts with
This is expected and corresponds to the fact that the long long type has a default initialization to 0 (zero initialization).
Default initialization for long long int is not zero initialization. Actually it is no initialization at all. From cppreference:
Default initialization is performed in three situations:
when a variable with automatic, static, or thread-local storage duration is declared with no initializer;
[...]
and
The effects of default initialization are:
if T is a non-POD (until C++11) class type, [... long long is not a class type ...]
if T is an array type, [... long longis not an array type ...]
otherwise, no initialization is performed: the objects with automatic storage duration (and their subobjects) contain indeterminate values.
Reading an indeterminate value is undefined behavior. Adding or removing seemingly unrelated lines of code changing the output is typical effect of undefined behavior. The output of your code could be anything. It is undefined.
|
69,396,496 | 69,397,447 | Understanding the usage of the syntax "<DataType>" in C++ | I want to understand the usage of the "<DataType>" in C++.
As far as I read about, it is the syntax used for templates, which uses the specified data type for specialization of function or class instantiation.
Coming from python, I understand that all data types are by definition a class (correct me if it does not apply for C++), so if you look for the int implementation in python, you will find:
class int:
@overload
def __new__(cls: Type[_T], x: str | bytes | SupportsInt | SupportsIndex | _SupportsTrunc = ...) -> _T: ...
...
Which constructor is overloaded based in arguments. So why in C++ it does not use (dataType) instead of <dataType> and overload the constructor based on the type of the arguments?
Also, can I safely state that every time <DataType> appears, it is surely a template there?
some examples:
std::vector<int> x;
std::vector< std::vector<int> >& someVar;
cv::Mat opencvMat;
int x = static_cast<int>(opencvMat.at<float>(i, 3) * frameWidth);
| I'll use your examples:
std::vector<int> x;
x is a vector (dynamic-length array) that contains ints.
std::vector< std::vector<int> >& someVar;
someVar is a reference to a vector of vectors. The inner vectors holds ints. This would be a common way to make a reference to a two-dimensional dynamic array, where each row could have a different number of columns.
int x = static_cast<int>(opencvMat.at<float>(i, 3) * frameWidth);
This is how you do various styles of cast. I'll break it into two:
opencvMat.at<float>(i, 3)
I don't use this library, but the at method is probably a template, and it means you're going to receive a float.
The static_cast forces the calculated value to an int without a compiler warning for loss of precision.
As you've figured out, this is all related to templates, and you'll see templates are defined using <>. For instance:
template <class ObjectType>
class Foo:
public:
ObjectType value;
};
Foo<std::string> myFoo;
In this case, myFoo.value is a string.
|
69,396,523 | 69,396,664 | Difference between boost::asio::strand and boost::asio::io_context::strand | I'd like to serialize http post requests using strand, to avoid overlapping writes to network.
My approach was to call the post method from the strand object with the callback that send the data as can be shown in the following code :
void Send(
boost::beast::http::request<boost::beast::http::string_body> &req) {
strand_.post([=]() {
...
boost::beast::http::write(stream_, req);
...
}
However, from looking at some examples, I've noticed 2 types of strand definitions :
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::io_context::strand strand_;
Any idea what's the different between each type ?
| There's actually not much difference between them. In fact, they share a lot of code and that shows that one was created from the other.
See diff here (bosst 1.67).
However, boost::asio::strand es a class template originally intended to be used with asio::io_service:
template <typename Executor>;
class strand
{
public:
/// The type of the underlying executor.
typedef Executor inner_executor_type;
/// Default constructor.
/**
* This constructor is only valid if the underlying executor type is default
* constructible.
*/
strand()
: executor_(),
impl_(use_service<detail::strand_executor_service>(
executor_.context()).create_implementation())
{
}
The class boost::asio::io_context::strand is not a class template and is bound to the class boost::asio::io_context:
class io_context::strand
{
public:
/// Constructor.
/**
* Constructs the strand.
*
* @param io_context The io_context object that the strand will use to
* dispatch handlers that are ready to be run.
*/
explicit strand(boost::asio::io_context& io_context)
: service_(boost::asio::use_service<
boost::asio::detail::strand_service>(io_context))
{
service_.construct(impl_);
}
|
69,396,692 | 69,398,653 | Why can't I change the Qvariant value inside a QMap? | I'm trying to pass an object called QMap<QString, QVariant>* collect_row and then I'm going to fill the second element with a QVariant value. The current value in the second element is 0.
I'm using this code to connect to a database and then copy the row from the database into the QMap<QString, QVariant>* collect_row.
DATABASE_STATUS Database::get_row_from(const QString& table_name, const QString& at_column_name, const QString& where_value_is_equal_to, QMap<QString, QVariant>* collect_row){
/* Check if we are connected */
if(!getInstance()->qSqlDatabase.isOpen())
return DATABASE_STATUS_NOT_CONNECTED;
QSqlQueryModel qSqlQueryModel;
qSqlQueryModel.setQuery("SELECT * FROM " + table_name + " WHERE " + at_column_name + " = '" + where_value_is_equal_to + "'");
QSqlRecord record = qSqlQueryModel.record(0);
QList<QString> column_names = collect_row->keys();
QList<QVariant> values_holders = collect_row->values();
for(int i = 0; i < column_names.length(); i++){
QVariant value_holder = values_holders.at(i);
value_holder.setValue(record.value(record.indexOf(column_names.at(i))));
}
return DATABASE_STATUS_OK;
}
So here I have the column_names and I want to set QVariant values into the values_holders.
for(int i = 0; i < column_names.length(); i++){
QVariant value_holder = values_holders.at(i);
value_holder.setValue(record.value(record.indexOf(column_names.at(i))));
}
I want to write this code instead, but I cannot write values_holders.at(i).setValue() because that function does not exist.
for(int i = 0; i < column_names.length(); i++)
values_holders.at(i).setValue(record.value(record.indexOf(column_names.at(i))));
database.cpp:72:30: error: no matching member function for call to 'setValue'
qvariant.h:560:23: note: candidate function template not viable: 'this' argument has type 'const QVariant', but method is not marked const
So that means I cannot change the element, even if there is a function called .setValue?
| Use this code. Note that I changed the QMap pointer to reference. I believe the code should work though I have not tested it. But it is still super-ugly and very non-optimal. But I tried to do just minimal changes to your provided code.
DATABASE_STATUS Database::get_row_from(const QString& table_name, const QString& at_column_name, const QString& where_value_is_equal_to, QMap<QString, QVariant>& collect_row)
{
/* Check if we are connected */
if(!getInstance()->qSqlDatabase.isOpen())
return DATABASE_STATUS_NOT_CONNECTED;
QSqlQueryModel qSqlQueryModel;
qSqlQueryModel.setQuery("SELECT * FROM " + table_name + " WHERE " + at_column_name + " = '" + where_value_is_equal_to + "'");
QSqlRecord record = qSqlQueryModel.record(0);
QList<QString> column_names = collect_row.keys();
for(int i = 0; i < column_names.length(); i++){
QString column_name = column_names.at(i);
collect_row[column_name] = record.value(record.indexOf(column_name));
}
return DATABASE_STATUS_OK;
}
|
69,396,899 | 69,397,397 | Do I understand the semantics of std::memory_order correctly? | c++reference.com states about memory_order::seq_cst:
A load operation with this memory order performs an acquire operation, a store performs a release operation, and read-modify-write performs both an acquire operation and a release operation, plus a single total order exists in which all threads observe all modifications in the same order.
[ Q1 ]: Does this mean that the order goes straight down through every operation of all (others + this) atomic_vars with memory_order::seq_cst?
[ Q2 ]: And release , acquire and rel_acq are not included in "single total order" ?
I understood that seq_cst is equivalent to the other three with write, read and write_read operation, but I'm confused about whether seq_cst can order other atomic_vars too, not only the same var.
| cppreference is only a summary of the C++ standard, and sometimes its text is less precise. The actual standard draft makes it clear: The final C++20 working draft N4681 states in atomics.order, par. 4 (p. 1525):
There is a single total order S on all memory_order::seq_cst operations, including fences, that satisfies the following constraints [...]
This clearly says all seq_cst operations, not just all operations on a particular object.
And notes 6 and 7 further down emphasize that the order does not apply to weaker memory orders:
6 [Note: We do not require that S be consistent with “happens before” (6.9.2.1). This allows more efficient
implementation of memory_order::acquire and memory_order::release on some machine architectures.
It can produce surprising results when these are mixed with memory_order::seq_cst accesses. — end note]
7 [Note: memory_order::seq_cst ensures sequential consistency only for a program that is free of data races
and uses exclusively memory_order::seq_cst atomic operations. Any use of weaker ordering will invalidate
this guarantee unless extreme care is used. In many cases, memory_order::seq_cst atomic operation
|
69,397,010 | 69,397,101 | C++ problem where the value assigned to a variable is getting changed even though it hasn't been modified yet | Please help me with this strange problem where the input value is given as 4 (i.e. n = 4) and after a for loop the same value is getting displayed as 2, but why? It was not used anywhere (AFAIK) and it shouldn't get changed (I have no clue about it).
The original problem on HackerRank.
MY CODE >>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int arr[n];
cin >> n; // input given from stdin is 4
cout << n << "\n"; // outputs 4
for(int i=0; i<n; i++){
scanf("%d",&arr[i]);
}
cout << n << "\n"; // outputs 2 (but why?)
for(int i=n-1; i>=0; i--){
printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
}
return 0;
}
Thank you for any help!
| int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
First of all, that's not even legal in C++. As a gcc extension to support C style VLA's, what is the value of n when the array declaration is seen? You have not read it yet!!
Instead, use:
int n;
cin >> n;
std::vector arr(n);
Although this still is not the "C++ way" as you are pre-defining the entire collection and then assigning to each element in turn; as opposed to adding each element to the collection. This is not a big deal with an int but more generally you don't want dead unused items in a collection; rather they simply don't exist at all.
std::vector arr; // don't pre-allocate any size
for(int i=0; i<n; i++){
int val;
scanf("%d",&val); //<<< uhhhhhh. you know about `cin` why this?
arr.push_back(val);
}
|
69,397,469 | 69,397,520 | Overloading prefix operator+ | I am trying to make a custom type in C++
I am trying to overload the + operator
class MyClass {
....
int operator+(int i) {
....
}
}
That works with
int main() {
MyClass MC;
count << MC+1;
}
How can I get it to work with 1+MC
| This is what I did.
^ cat Foo.cpp
#include <iostream>
class MyClass {
public:
int value = 5;
};
int operator+(const int value1, const MyClass &value2) { return value1 + value2.value; }
int main() {
MyClass myClass;
int newValue = 1 + myClass;
std::cout << newValue << std::endl;
}
^ make Foo
g++ Foo.cpp -o Foo
^ Foo
6
You'll see that I made a free function for it.
|
69,397,543 | 69,397,741 | Passing functions with different number of parameters as argument in C++ | [Edited] Based on the feedback from comments, I have rephrased my question.
In C++, is it possible to create a function func that receives another function f as a parameter, if the number of arguments of f might change?
According to this thread, a syntax in C like
void func ( void (*f)(int) );
would help if I already know the number of arguments f receives, but that's not my case.
I want to use func with different functions f1, f2, etc., each of them may or may not have the same number of parameters. For example, f1 could take only one argument, but f2 could take two. That's why I'm trying to look for a way to pass f without specifying the number of arguments. Thanks!
| The Q&A you link is for C. In C++ you can pass a function pointer but not always this is the best alternative.
Your question leaves out the crucial part: How do you plan to call f in func when you don't know the number of parameters?
You can do type erasure and remove information of a type easily (eg number of arguments of a function), but latest when you call the function you need to know again how many parameters to pass.
As it isn't perfectly clear what you want to do with the fs that take different number of parameters I will interpret your question like this: Instead of passing functions of different arity to func you can pass a functor with overloaded operator(). Then you can call it with different number of parameters:
#include <iostream>
#include <string>
template <typename F>
void func(F f, int num_params){
if (num_params == 1){
f("Hello");
} else if (num_params == 2) {
f("Hello","World");
}
}
struct functor {
void operator()(const std::string& s){ std::cout << s << "\n";}
void operator()(const std::string& s1,const std::string& s2) { std::cout << s1 << " " << s2 << "\n";}
};
int main() {
func(functor{},1);
func(functor{},2);
}
However, my func is only valid for a functor type that has both, an operator() that can be called with one string literal, and an operator() that can be called with two string literals.
|
69,397,744 | 69,397,981 | Why does computing a formula with multiple unknowns not working? | I'm trying to compute the formula "V / I = R" in my program by asking the user to input values for V and I. Unfortunately my program does not compile and I'm not sure why.
#include <iostream>
using namespace std;
int main()
{
int V, I, R;
cout << "Please enter the voltage: " << endl;
cin >> V;
cout << "Please enter the curruent: " << endl;
cin >> I;
V / I = R;
cin >> R;
cout << "The value of the resistor is: " << R << endl;
system("PAUSE");
}
| C++ is not a system to solve linear equation, you must tell it what to do.
You need to replace:
V / I = R;
cin >> R;
with
R = V / I;
The knowledge you used, to flip the equation around, stays with you. The compiler needs instructions. Also note the = is not the symbol for equality. It is the symbol for assignment. It evaluates the right-hand side and assigns it to the variable on the left-hand side. Some other language write it := to make this clearer.
You should also use float instead of int if you want to be able to get fractional answers, like 0.5.
|
69,398,068 | 69,398,117 | How can C++ differentiate between () and {} when init a vector | #include <iostream>
#include <vector>
int main() {
std::vector<int> v1(10);
std::vector<int> v2{10};
for (int x : v1)
std::cout << x << ", ";
std::cout << std::endl;
for (int x : v2)
std::cout << x << ", ";
}
makes
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10,
How can C++ distinguish between () and {} when initialising a class?
And how can I create a constructor for both () and {} with different meanings?
|
How can C++ distinguish between () and {} when initialising a class?
Because they are using different syntaxes, so the compiler can parse them differently and behave accordingly.
how can I create a constructor for both () and {} with different meanings?
Define 2 constructors, making one of them take a std::initializer_list as a parameter. {} will call that constructor. () will call the other one.
|
69,398,507 | 70,039,088 | GMP mpz_t variable being set with incorrect value | I've been working on the Euler 29 problem for a few days and am having difficulty getting the mpz_t type to work correctly. The objective is to iterate through a^b for values of 2 <= a,b <= 100 and count the nonrepeat values.
Using vector I was able to store the values using pointers in an array like so:
mpz_t a;
mpz_init(a);
vector<mpz_t*> numbers;
numbers.push_back(&a);
However, when running the full program below you can see that after it inserts the first value 4, it doesn't insert any new values. This is because the temp value being compared to rop is not being set to what is already in the array, and instead is set to the value shared by rop.
#include <iostream>
#include <vector>
#include <chrono>
#include "gmp.h"
using namespace std;
int main()
{
auto start = std::chrono::high_resolution_clock::now();
int solution = 0;
bool found = false;
int r = 10;
mpz_t rop;
mpz_init(rop);
mpz_t temp;
mpz_init(temp);
vector<mpz_t*> numbers;
for(int a = 2; a <= 5; a++)
{
for(int b = 2; b <= 5; b++)
{
mpz_ui_pow_ui(rop, a, b);
for(int i = 0; i < numbers.size(); i++)
{
cout << "i: " << i << endl;
cout << "rop: ";
mpz_out_str(stdout,10,rop);
cout << endl;
mpz_set(temp,*(numbers.at(i)));
cout << " temp: ";
mpz_out_str(stdout,10,temp);
cout << endl;
r = mpz_cmp(rop,temp);
cout << " r: " << r << endl << endl;
if(r == 0)
{
found = true;
break;
}
}
if(found == false)
{
numbers.push_back(&rop);
solution++;
cout << "pushed! " << endl << endl;
}
found = false;
}
}
auto done = std::chrono::high_resolution_clock::now();
cout << "Solution: " << solution << endl << endl;
cout << "Program completed in " << std::chrono::duration_cast<std::chrono::milliseconds>(done - start).count() << " milliseconds." << endl;
}
This line of code should be setting temp equal to 4 at the start of the forloop, but instead sets it equal to rop:
mpz_set(temp,*(numbers.at(i)));
Since the problem clearly has to do with the fact I'm using pointers and passing the actual address in memory to store these mpz_t variables, how can I change the code so that it is able to work properly? I'm under the impression using the function mpz_clear(rop) after each push_back to the numbers vector wouldn't work as it releases the address from memory.
| I figured out that due to the way mpz_t variables work the mpz_set function does not work with a pointer to mpz_t type variables as a parameter.
Instead, I was able to get the program to work by assigning the mpz_get_str function to a string and pushing that to a vector of strings to check for repeat values.
mpz_t rop;
mpz_init(rop);
char * num;
vector<string> numbers;
num = mpz_get_str(num,10,rop)
numbers.push_back(num);
|
69,399,103 | 69,399,187 | character '\0' vs string "\0" | An online testing system expects my code to output the number 10.
It accepts:
printf("%d",10)
printf("%c%c\0", '1', '0')
printf("%c%c\0something", '1', '0')
printf("%c%c%s", '1', '0', "\0")
But rejects:
printf("%c%c%c", '1', '0', '\0')
printf("%c%c%c", '1', '0', 0)
putchar('1');putchar('0');putchar('\0');
putchar('1');putchar('0');putchar(0);
What is the difference between printing "\0" and '\0'?
| Your online testing system is expecting to see the character sequence {'1', '0'}, but you are sending it the sequence {'1', '0', NUL }. You're trying to print the string terminator in addition to the string characters.
The string "10" is internally represented as the character sequence {'1', '0', NUL}, but when you display it with printf( "%s", "10" );, that trailing 0 isn't written to the output stream. The terminator is only there to mark the end of the string - it's never displayed or copied.
|
69,399,702 | 69,425,956 | Colstore vs Rowstore for in-memory algorithms | I'm familiar with using a column- vs a row-store for how a databases internally persists data to disk. My question is whether, for a dataset is entirely in memory, and there's no storage to disk, if the row- vs column- orientation makes much of a difference?
The things I can think of that may make a difference would be:
For fields under 8 bytes, it would involve less memory accesses for columns than for rows.
Compression would also be easier on a column-store regardless of whether in memory or not (seems like a non-issue if not saving back to storage I suppose? does compression ever matter on in-memory operations?)
Possible to vectorize operations.
Much, much easier to work with a struct on a row-by-row basis of course.
Are both of those accurate, and are there any more? Given this, would there be substantial performance improvements on using an in-memory colstore vs rowstore on a read-only dataset, or just a marginal improvement?
|
I'm familiar with using a column- vs a row-store for how a databases internally persists data to disk. My question is whether, for a dataset is entirely in memory, and there's no storage to disk, if the row- vs column- orientation makes much of a difference?
A lot depends on the size of the dataset, what the contents of each row are, how you need to search in it, whether you want to add items to or remove items from the dataset, and so on.
There is also the CPU and memory architecture to consider; how big are your caches, what is the size of a cache line, and how intelligent is your CPU's prefetcher.
For fields under 8 bytes, it would involve less memory accesses for columns than for rows.
Memory is not accessed a register at a time, but rather a cache line at a time. On most contemporary machines, cache lines are 64 bytes.
Compression would also be easier on a column-store regardless of whether in memory or not
Not really. You can compress/decompress a column even if it is not stored in memory consecutively. It might be faster though.
does compression ever matter on in-memory operations?
That depends. If it's in-memory, then it's likely that compression will reduce performance, but on the other hand, the amount of data that you need to store is smaller, so you will be able to fit more into memory.
Possible to vectorize operations.
It's only loading/storing to memory that might be slower if data is grouped by rows.
Much, much easier to work with a struct on a row-by-row basis of course.
It's easy to use a pointer to a struct with a row-by-row store, but with C++ you can make classes that hide the fact that data is stored column-by-column. That's a bit more work up front, but might make it as easy as row-by-row once you have set that up.
Also, column-by-column store is often used in the entity-component-system pattern, and there are libraries such as EnTT that make it quite easy to work with.
Are both of those accurate, and are there any more? Given this, would there be substantial performance improvements on using an in-memory colstore vs rowstore on a read-only dataset, or just a marginal improvement?
Again, it heavily depends on the size of the dataset and how you want to access it. If you frequently use all columns in a row, then row-by-row store is preferred. If you frequently just use one column, and need to access that column of many consecutive rows, then a column-by-column store is best.
Also, there are hybrid solutions possible. You could have one column on its own, and then all the other columns stored in row-by-row fashion.
How you will search in a read-only dataset matters a lot. Is it going to be sorted, or is it more like a hash map? In the former case, you want the index to be as compact as possible, and possibly ordered like a B-tree as Alex Guteniev already mentioned. If it's going to be like a hash map, then you probably want row-by-row.
|
69,400,540 | 69,410,264 | C++ boost-asio-network in async callback, which one is better ? using lambda or boost::bind() | C++ lambda made me confusing.
bind functions for async read.
template<typename T>
class connection
: public boost::enable_shared_from_this<connection<T>>
, boost::noncopyable
{
public:
using err = boost::system::error_code;
protected:
boost::asio::ip::tcp::socket socket_;
...
// completion function
// read until meet '\n'
size_t on_read_completion(const err& error, size_t bytes)
{
if (error) { return 0; }
bool found = std::find(read_buffer_, read_buffer_ + bytes, '\n') < read_buffer_ + bytes;
return found ? 0 : 1;
}
// read message
void on_read(const err& error, size_t bytes)
{
if (!started_) { return; }
if (error)
{
std::cout << "[ERROR] async_read " << error.message();
stop();
}
std::string msg(read_buffer_, bytes);
// handle received message
on_message(msg);
}
This is async read() function.
void read()
{
if (!socket_.is_open())
{
std::cout << "[ERROR] socket_ is not open\n";
return;
}
std::fill_n(read_buffer_, MAX_MSG, '\0');
// it works
#if 0
async_read(socket_, boost::asio::buffer(read_buffer_),
boost::bind(&connection::on_read_completion, this->shared_from_this(), _1, _2),
boost::bind(&connection::on_read, this->shared_from_this(), _1, _2));
#else // not works
async_read(socket_, boost::asio::buffer(read_buffer_),
[this](const err& error, size_t bytes)->size_t
{
if (error) { return 0; }
bool found = std::find(read_buffer_, read_buffer_ + bytes, '\n') < read_buffer_ + bytes; return found ? 0 : 1;
},
[this](const err& error, size_t bytes)->void
{
if (!started_) { return; }
if (error)
{
std::cout << "[ERROR] async_read\n" << error.message();
return;
}
std::string msg(read_buffer_, bytes);
on_message(msg);
});
#endif
}
The problem is lambda [capture] that is not containing shared_ptr itself. So when it call on_read_completion(), lambda capture this is not pointing shared_from_this() that I want.
I need a wise advice for this. Help me please.
| You already figured out that this needs to be explicitly captured in addition to the shared pointer, the latter just for the lifetime guarantee.
However your original question is slightly more interesting than you knew! There's a subtle difference between lambda and bind expressions. If you use bind to bind to a generic handler, it may preserve asio_handler_invoke (or more modern get_associated_executor) semantics under the ADL rule.
This is rarely a concern at the end-user level, but if you mean to provide a generic library of composable operations you may care about this kind of detail for failing to preserve the invocation semantics could lead to bugs (e.g. when a composed handler is bound to a strand executor).
As a sidenote, in the case you showed, consider using the overload of async_read_until that take a string(view) or regex.
|
69,400,565 | 69,400,628 | A simple operator overloading program in C++ on codeblocks. Got an error at line 19. The same program runs perfectly on Turbo C++ | Got an error on line 19:
error : no 'operator++(int)' declared for postfix '++' [-fpermissive]
#include<bits/stdc++.h>
using namespace std;
class sample
{
int x,y;
public:
sample(){x=y=0;}
void display()
{
cout<<endl<<"x="<<x<<" and y= "<<y;
}
void operator ++(){x++;y++;}
};
int main()
{
sample s1;
sample s2;
s1++;
++s2;
++s1;
s1.display();
s2.display();
return 0;
}
Error on code line:
s1++;
| TURBO C++? Haven't heard that name in a LONG time. That is a compiler from an era before C++ was even standardized, and is not representative of C++ anymore.
Prefix increment and post-increment are different functions. You can't just overload one and expect both to work.
Also your signature is wrong. It should return a type matching the class it's called on. For example:
class sample
{
public:
...
// prefix
sample & operator ++() {x++; y++; return *this; }
// postfix (the int is a dummy just to differentiate the signature)
sample operator ++(int) {
sample copy(*this);
x++; y++;
return copy;
}
};
The value of the return type is the main difference between the two so it's pointless for your operator to return void. One returns a reference, since it represents the incremented object, while the postfix version returns a copy that is the state of the pre-incremented object.
|
69,400,617 | 69,400,688 | How to insert std::vector or array to a std::forward_list without using any loop? | forward_list<int> listOne;
forward_list<int> listTwo;
vector<int> arr = {2,4,3};
forward_list<int>::iterator it;
In the code mention above, I want to insert a std::vector in listOne and I tried using insert_after function.
it = listOne.begin();
listOne.insert_after(it,arr);
But it didn't work.
I want to know that, is there a way to add a std::vector or array in a std::forward_list without any loop ?
| You could use a std::copy with std::front_inserter
copy(arr.rbegin(), arr.rend(), front_inserter(listOne));
Working demo
|
69,400,860 | 69,402,941 | Many folders project Makefile | I have the following project structure:
common
|-- foo.cpp
|-- foo.h
exercise_1
|-- main.cpp
|-- bar_1.cpp
|-- bar_1.h
exercise_2
|-- main.cpp
|-- bar_2.cpp
|-- bar_2.h
...
How can one organize Makefile to build such project from the main directory e.g.:
make exercise_10
So that this command would build object files in common directory, in exercise_10 folder and link them all to executable in exercise_10. I started with the following:
COMPILER = g++
INCLUDE = -I common/
DEPS = common/*.o
OBJECTS := $(patsubst common/%.cpp, common/%.o, $(wildcard common/*.cpp))
common: $(OBJECTS)
exercise_%:
$(COMPILER) $@/main.cpp $(INCLUDE) -o $@/main $(DEPS)
But it's not working and I don't know what to do next.
Thanks!
| If you use GNU make you could define a macro to build any of your exercises. Something like the following:
EXERCISES := $(wildcard exercise_*)
MAINS := $(addsuffix /main,$(EXERCISES))
.PHONY: all
all: $(MAINS)
common-objs := $(patsubst %.cpp,%.o,$(wildcard common/*.cpp))
common-headers := $(wildcard common/*.h)
%.o: %.cpp $(common-headers)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -Icommon -c $< -o $@
# $(1): exercise directory
define BUILD_EXERCISE
.PHONY: $(1)
$(1): $(1)/main
$(1)-objs := $$(patsubst %.cpp,%.o,$$(wildcard $(1)/*.cpp))
OBJS += $$($(1)-objs)
$(1)-headers := $$(wildcard $(1)/*.h)
$$($(1)-objs): $$($(1)-headers)
$(1)/main: $$($(1)-objs) $$(common-objs)
$$(CXX) $$(CXXFLAGS) $$(LDFLAGS) -o $$@ $$^ $$(LDLIBS)
endef
$(foreach e,$(EXERCISES),$(eval $(call BUILD_EXERCISE,$(e))))
.PHONY: clean
clean:
rm -f $(MAINS) $(OBJS) $(common-objs)
It looks a bit complicated but it's not. The only trick is the $$ in the BUILD_EXERCISE macro. It is needed because the macro is expanded twice by make. Everything else is straightforward:
CXX, CPPFLAGS, CXXFLAGS, LDFLAGS and LDLIBS are Variables Used by Implicit Rules.
$@, $< and $^ are Automatic Variables.
wildcard, addsuffix, patsubst, foreach, eval and call are make functions.
Phony targets are declared as prerequisites of the .PHONY special target.
The foreach-eval-call construct is a way to programmatically instantiate make statements.
%.o: %.cpp... is a pattern rule.
|
69,401,556 | 69,401,636 | Is cin.get() reading multiple digit characters at once? | We were asked to write a simple C++ program by our teacher to add two numbers in the following format:
input: 12 14
output: m+n = 26
The program must also work for other inputs in the form:
input: Hello please add 12 and 14 !
output: m+n = 26
The solution that was given was:
#include <iostream>
using namespace std;
int main(){
int m,n;
char ch;
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>m;
break;
}
}
//cin.putback() restores the last character
//read by cin.get() back to the input stream
while(cin.get(ch)){
if(isdigit(ch))
{
cin.putback(ch);
cin>>n;
break;
}
}
cin.ignore(80,'\n');
cout<<"m + n = "<<m+n<<endl;
return 0;}
But now I need to know why this program also works for numbers that are not single digits. Shouldn't cin.get(char) just read one digit and cin.putback() return the same? Please help me I am a beginner.
| Yes, cin.get() will read only one character at a time.
The important part, where the number is actually read, is 4 lines below: cin>>m;. This will consume as many digits as possible and store the resulting integer in m.
Some more details:
// example with input 524 42
while(cin.get(ch)) // extract one character at a time
{ // ch='5', remaining input="24 42"
if(isdigit(ch)) // if it's a digit (0-9), then:
{
cin.putback(ch); // Put it back into the stream, "unread" it
// remaining input="524 42"
cin >> m; // extract an integer from stream
// m=524, remaining input="42"
break;
}
}
The reason for the loops seems to be to skip over any non-numeric input before a number appears. Note that there is a little bug here, since it will also ignore leading signs. (e.g. input -4 4 will output m + n = 8)
|
69,401,709 | 69,404,274 | Conditional jump or move depends on uninitialized value(s) with strcat in for loop | I have a file containing the strings of 3 chromosome, which I want to concatenate into one genome. And then I have to access this concatenated string across multiple threads (I use pthread_t). To to this I have to use pthread_mutex_lock when extracting the data, then I use strcat to concatenate the data which are extracted using the function fai_fetch using const char* and then I am saving the data as a char* (see below).
// genome_size the size of all the chromosomes together
// chr_total the number of chromosomes I wish to concatenate
char* genome = (char*) malloc(sizeof(char) * (genome_size+chr_total));
for (int i = 0; i < chr_total; i++){
pthread_mutex_lock(&data_mutex);
const char *data = fai_fetch(seq_ref,chr_names[i],&chr_sizes[i]);
pthread_mutex_unlock(&data_mutex);
//sprintf(&genome[strlen(genome)],data);
strcat(genome,data);
//sprintf(genome+strlen(genome),data); //All three gives conditional jump or move error
//sprintf(genome,data); // THIS SOLVES VALGRIND ISSUE ONE BUT DOES NOT GIVE A CONCATENATED CHAR*
}
All of this works, but then running valgrind I get
Conditional jump or move depends on uninitialized value(s) referring to the "strcat(genome,data); "
and Uninitialized value was created by a heap allocation referring to
"char* genome = (char*) malloc(sizeof(char) * (genome_size+chr_total));"
Based on other StackOverflow answers I tried sprintf(&genome[strlen(genome)],data); and sprintf(genome+strlen(genome),data); instead of strcat. However they too gives the same valgrind message.
The only thing that seems to alleviate this error is using sprintf(genome,data); however then i will not get the full genome but just a single chromosome.
Trying genome += sprintf(genome,data); gives me ./a.out': munmap_chunk(): invalid pointer: and ./a.out': free()
In regards to the "Uninitialized value was created by a heap allocation" error -> then my issue is that I am only able to free that memory after all of the threads are done running. So I am not sure how to initialize the values in the heap allocation when I am using malloc.
Is it possible to solve some of these specific valgrind errors?
| Using Valgrind to locate the problematic code
The "Conditional jump or move depends on uninitialised value(s)" message means Valgrind has determined that some result of your program depends on uninitialized memory.
Use the --track-origins=yes flag to track the origin of the uninitialized value. It might help you finding that value. From man 1 valgrind:
When set to yes, Memcheck keeps track of the origins of all uninitialised values. Then, when an uninitialised value error is reported, Memcheck will try to show the origin of the value. An origin can be one of the following four places: a heap block, a stack allocation, a client request, or miscellaneous other sources (eg, a call to brk).
More specifically in your program:
Problem 1: Using uninitialized genome
The line
char* genome = (char*) malloc(sizeof(char) * (genome_size+chr_total));
Allocates the genome buffer using malloc(2) and then consumes it in:
strcat(genome,data);
Please note that functions such as strlen(3) and strcat(3) works on C-strings, which are buffers that terminate with a null character ('\0').
malloc(2) just allocates memory and it doesn't initialize it so your allocated buffer may contain any value (and considered as uninitialized). You should avoid using string related functions with an uninitialized buffers as it results undefined behavior.
Fortunately calloc(2) does the trick - it allocates the buffer and initializes all of its bits to zero, resulting a valid 0 length C-string you can operate on. I suggest the following fix to ensure that genome is initialized:
char* genome = calloc(genome_size+chr_total+1, sizeof(char));
Also note that I've added +1 to the length of the allocated buffer. It is done to guarantee that the resulting genome will end with a null terminator (assuming that genome_size+chr_total is the total size of all the buffers returned from fai_fetch).
Also note that in terms of performance calloc is a bit slower than malloc (because it initializes the data) but for my opinion it is safer as it initializes the whole buffer. For the purposes of your specific program, you could save the performance burden by using malloc and initializing just the first byte:
char* genome = malloc(sizeof(char) * (genome_size + chr_total + 1));
if (NULL == genome) {
perror("malloc of genome failed");
exit(1);
}
// So it will be a valid 0 length c-string
genome[0] = 0;
We don't have to initialize the last byte to be 0 because strcat writes the terminating null character for us.
(Potential) Problem 2: Using potentially non-null terminated data with strcat
As you described in your question, the fai_fetch extracts some data:
const char *data = fai_fetch(seq_ref,chr_names[i],&chr_sizes[i]);
and then consumes it in the strcat line:
strcat(genome,data);
As I wrote above, because you use strcat, data should be null-terminated as well.
I'm not sure how fai_fetch is implemented but if it returns a valid C-string then you're all good.
If it doesn't then you should use strncat which works on buffers that are not null-terminated.
From man 3 strcat:
The strncat() function is similar, except that
it will use at most n bytes from src; and
src does not need to be null-terminated if it contains n or
more bytes.
I suggest the following fix:
// I'm not sure what type `&chr_sizes[i]` is, assuming it's `size_t`
size_t length = &chr_sizes[i];
const char *data = fai_fetch(seq_ref,chr_names[i], length);
// Use strcat
strncat(genome, used_data, length);
|
69,401,716 | 69,401,900 | Is optimizing small std::strings wiht c-style functions often pointless? | Let's say we've got the following piece of code and we've decided to optimise it a bit:
/// BM_NormalString
bool value = false;
std::string str;
str = "orthogonal";
if (str == "orthogonal") {
value = true;
}
So far we've come up with two pretty simple and straightforward strategies:
/// BM_charString
bool value = false;
char *str = new char[11];
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
value = true;
}
delete[] str;
/// BM_charStringMalloc
bool value = false;
char *str = (char *) std::malloc(11);
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
value = true;
}
free(str);
If we try and benchmark our three approaches we, quite surprisingly, won't see much of a difference.
Although bench-marking it locally gives me even more surprisingly disconcerting results:
| Benchmark | Time | CPU | Iterations |
|----------------------|------------------|-----------|---------------|
| BM_charString | 52.1 ns | 51.6 ns | 11200000 |
| BM_charStringMalloc | 47.4 ns | 47.5 ns | 15448276 |
| **BM_NormalString** | 17.1 ns | 16.9 ns | 40727273 |
Would you say then, that for such rather small strings there's almost no point in going 'bare metal' style (by using C-style string functions)?
| For small strings, there's no point using dynamic storage. The allocation itself is slower than the comparison. Standard library implementers know this and have optimised std::basic_string to not use dynamic storage with small strings.
Using C-strings is not an "optimisation".
|
69,401,732 | 69,402,214 | Ambiguity error accessing equality comparison operator in G++ | In case of multiple inheritance if all parent classes have their own equality comparison operator ==, and the child class has a (friend) function operator ==, as in the example:
struct A {
bool operator ==(const A&) const = default;
};
struct B {
bool operator ==(const B&) const = default;
};
struct C : A, B {};
constexpr bool operator ==(const C&, const C&) { return true; }
static_assert( C{} == C{} );
GCC prints the following error about ambiguity in an attempt to compare child objects:
error: request for member 'operator==' is ambiguous
13 | static_assert( C{} == C{} );
note: candidates are: 'bool B::operator==(const B&) const'
note: 'bool A::operator==(const A&) const'
Demo: https://gcc.godbolt.org/z/W3qer376d
This error looks surprising, since operator ==(const C&, const C&) shall be preferred as the most suitable to the actual arguments. Is it simply a defect in GCC?
| Indeed the global operator operator==(const C&, const C&) has priority. However the compiler "want to know" all the possibilities in order to decide: In other words: as soon as you try to use the operator== the compiler requires you to have no ambiguities, even if the required alternative is not between the ambiguous one.
struct C : A, B { using A::operator==; };
This resolves the ambiguity and allows you to use the global operator==
https://onlinegdb.com/nxMjPN4NC
#include <iostream>
struct A {
bool operator ==(const A&) const { std::cout << "A" << std::endl; return true; };
};
struct B {
bool operator ==(const B&) const { std::cout << "B" << std::endl; return true; };
};
struct C : A, B
{
//using A::operator==; // Uncomment this to make it work.
};
bool operator ==(const C&, const C&) { std::cout << "C" << std::endl; return true; }
int main()
{
C c1, c2;
c1==c2;
return 0;
}
Result (when resolved):
C
|
69,402,374 | 69,431,491 | MDI Tab names changing back... / Taskbar Preview not selecting | I'm creating an MDI application, WITHOUT the Document/View.
I am also using MDITabbedGroups.
I had a problem, because I have to name may tabs dynamically (names are in the DB and user created), meaning I couldn't use resources for the names.
I create all the tabs as 'Program name', then rename them by calling the following after create:
BEGIN_MESSAGE_MAP(CChildView, CWnd)
ON_COMMAND(ID_SET_COLOR, CCOnSetColor)
END_MESSAGE_MAP()
PostMessage(WM_COMMAND, (WPARAM)ID_SET_COLOR);
void CChildView::CCOnSetColor()
{
CMDIChildWndEx* pFrame = (CMDIChildWndEx*)GetParent();
CMFCTabCtrl* pTabCtrl = pFrame->GetRelatedTabGroup();
if (pTabCtrl != NULL)
{
pTabCtrl->SetTabBkColor(pTabCtrl->GetActiveTab(), GetTabCol());
pTabCtrl->SetTabLabel(pTabCtrl->GetActiveTab(), GetTabName());
pTabCtrl->RedrawWindow();
}
}
But the problem was that when I switched tabs the names would change back to 'Program Name'.
I managed to avoid this by skipping over CMDIChildWndEx in the OnMDIActivate call as so:
void CChildFrame::OnMDIActivate(BOOL bActivate, CWnd* activated, CWnd* disbled)
{
CWnd::OnMDIActivate(bActivate, activated, disbled);
}
I know, I know, bad. However:
This worked fine, all other functionality seemed to be working, tabs were switching, active window was correct etc etc...
Until I noticed that on mouse over of the task bar, I got a preview of all open tabs, and if I clicked on one of the inactive tabs things went wrong.
Now the active frame / view (GetActiveFrame() / GetActiveView() in MainFrame) was the one I click on, but it is not drawn and the tab not switched to.
So I tried:
void CChildFrame::OnMDIActivate(BOOL bActivate, CWnd* activated, CWnd* disbled)
{
CMDIChildWndEx::OnMDIActivate(bActivate, activated, disbled);
CMFCTabCtrl* pTabCtrl = GetRelatedTabGroup();
if (pTabCtrl != NULL)
{
pTabCtrl->SetTabBkColor(pTabCtrl->GetActiveTab(), m_wndView.GetTabCol());
pTabCtrl->SetTabLabel(pTabCtrl->GetActiveTab(), m_wndView.GetTabName());
// pTabCtrl->SetTabIcon(pTabCtrl->GetActiveTab(), 2);
pTabCtrl->RedrawWindow();
}
}
&&&
void CChildFrame::OnMDIActivate(BOOL bActivate, CWnd* activated, CWnd* disbled)
{
CMDIChildWndEx::OnMDIActivate(bActivate, activated, disbled);
m_wndView.PostMessage(WM_COMMAND, (WPARAM)ID_SET_COLOR);
if(disbled) ((CChildFrame*)disbled)->m_wndView.PostMessage(WM_COMMAND, (WPARAM)ID_SET_COLOR);
}
Now the tab switches correctly, but only the tab being activated gets the correct name, all inactive tabs go back to 'Program Name'
interestingly the color remains correct.
So the Question:
Can I permanently change the name some how / where.
I saw in MS Documentation that it can be set in CDocument, but I don't have a Document...
Alternatively what call / calls do I need to catch to set my name every time?
Also Bonus Q:
Can I make the Preview show only the 'Active' Tab, and not the others?
| After much hunting around in the AFX source files, I found this:
CString CMDIChildWndEx::GetFrameText() const
{
ASSERT_VALID(this);
CString strText;
GetWindowText(strText);
return strText;
}
& this
void CMDIFrameWnd::OnUpdateFrameTitle(BOOL bAddToTitle)
{
if ((GetStyle() & FWS_ADDTOTITLE) == 0)
return; // leave it alone!
... // rest of func
}
so it is as simple as removing the style flag the MS puts in automatically (via wizard create project), on the func BOOL PreCreateWindow(CREATESTRUCT& cs).
Then setting the title of the Frame via SetWindowText(title);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.