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 |
|---|---|---|---|---|
72,220,547 | 72,221,479 | C++ Read txt and put each line into Dynamic Array | I am trying to read input.txt file, and trying to put each line into the array as string (later on I will use each element of array in initializing obj that's why I am putting each line into the array).
string* ptr = new string;
// Read Mode for Input
fstream input;
input.open("input.txt", ios::in);
int size = 0;
if (input.is_open()) {
string line;
while (getline(input, line)) {
cout << line << endl;
ptr[size] = line;
size++;
}
input.close();
}
for (int i = 0; i < size-1; i++) {
cout << "array: " << ptr[i] << endl;
}
I am getting error as:
Proxy Allocated, drain it
| Don't use arrays; use std::vector. The std::vector behaves like an array and uses Dynamic Memory:
std::string s;
std::vector<std::string> database;
while (std::getline(input, s))
{
database.push_back(s);
}
Keep it simple. :-)
|
72,220,614 | 72,220,982 | Sort vector of custom template class | Suppose I have a template class ComplexNumber that looks like this:
template<typename T>
class ComplexNumber {
public:
ComplexNumber() : A(), B() {}
ComplexNumber(const T& r, const T& i) : A(r), B(i) {}
~ComplexNumber(){}
void setA(T A1);
void SetB(T B1);
T getA() const {return A;};
T getB()const {return B;};
ComplexNumber<T> operator+(const ComplexNumber<T> &C){
return ComplexNumber<T>( A + C.getA(), B + C.getB());
}
ComplexNumber<T> operator -(const ComplexNumber<T> &C) {
return ComplexNumber<T>(A - C.getA(), B - C.getB());
};
friend ostream & operator << (ostream &out, const ComplexNumber<T> &c)
{
out << c.A;
out << "+i" << c.B << endl;
return out;
}
private:
T A;
T B;
};
And a main() that constructs these complex numbers and stores them into a std::vector:
ComplexNumber<int> complex1(10, 3);
ComplexNumber<int> complex2(2, 56);
ComplexNumber<int> complex3(3, 55);
vector<ComplexNumber<int>> testVector;
testVector.push_back(complex1);
testVector.push_back(complex2);
testVector.push_back(complex3);
If I want to sort testVector from highest to lowest, comparing the real parts and then comparing the imaginary ones if the real parts are equal, how would I go about doing that?
I am unable to use the standard std::sort() function. I would like to do this using a method or functor.
EDIT: Trying to add it to a function:
//This method is outside the scope of the ComplexNumber class
auto compare_by_magnitude = [](const auto& a, const auto& b) {
return a.A*a.A + a.B*a.B < b.A*b.A + b.B*b.B;
};
void sortComplex(vector<ComplexNumber<int>> &c){
std::sort(c.begin(),c.end(),compare_by_magnitude);
}
My error messages:
FAILED: complexNumber.exe
cmd.exe /C "cd . && C:\PROGRA~1\JETBRA~1\CLION2~1.3\bin\mingw\bin\G__~1.EXE -g CMakeFiles/complexNumber.dir/main.cpp.obj CMakeFiles/complexNumber.dir/ComplexNumber.cpp.obj -o complexNumber.exe -Wl,--out-implib,libcomplexNumber.dll.a -Wl,--major-image-version,0,--minor-image-version,0 -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Program Files\JetBrains\CLion 2021.3.3\bin\mingw\bin/ld.exe: CMakeFiles/complexNumber.dir/ComplexNumber.cpp.obj: in function `ComplexNumber<int>::~ComplexNumber()':
C:/PROGRA~1/JETBRA~1/CLION2~1.3/bin/mingw/lib/gcc/x86_64-w64-mingw32/11.2.0/include/c++/bits/stl_heap.h:223: multiple definition of `sortComplex(std::vector<ComplexNumber<int>, std::allocator<ComplexNumber<int> > >&)'; CMakeFiles/complexNumber.dir/main.cpp.obj:C:/Users/elira/Desktop/complexNumber/complexNumber/ComplexNumber.h:51: first defined here
C:\Program Files\JetBrains\CLion 2021.3.3\bin\mingw\bin/ld.exe: CMakeFiles/complexNumber.dir/ComplexNumber.cpp.obj:C:/Users/elira/Desktop/complexNumber/complexNumber/ComplexNumber.h:48: multiple definition of `compare_by_magnitude'; CMakeFiles/complexNumber.dir/main.cpp.obj:C:/Users/elira/Desktop/complexNumber/complexNumber/ComplexNumber.h:48: first defined here
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
| In order to work with std::sort(), your class needs at least operator< defined:
bool operator< (const ComplexNumber<T>& other) const {
return A < other.A || (A == other.A && B < other.B);
}
It's also good practice to define operator==, but std::sort() will work with operator< alone.
When I make the above addition to your class, this main() sorts by real and then imaginary, in ascending order:
int main() {
vector<ComplexNumber<float>> vc = { {4, 5}, {1, 3}, {4, 2} };
copy(vc.begin(), vc.end(), ostream_iterator<ComplexNumber<float>>(cout, " "));
cout << endl;
sort(vc.begin(), vc.end());
copy(vc.begin(), vc.end(), ostream_iterator<ComplexNumber<float>>(cout, " "));
cout << endl;
}
But, you mentioned you want to sort in descending order. It's bad practice to define operator< in the reverse sense within the class, as you can imagine, so you can instead pass a comparison function to std::sort() that reverses the sense of the comparison:
sort(vc.begin(), vc.end(),
[](const ComplexNumber<float> &f1, const ComplexNumber<float> &f2)
{ return ! (f1 < f2); }
);
These compilation and semantic concerns aside, when I look at the errors you're posting, I see a link error, and it appears that your class is being defined multiple times. This suggests that the include file which defines your class is missing an include guard.
|
72,220,745 | 72,220,913 | is there a way of hosting a mysql database using only Qt? | I am trying to make a program that connect many computers into a local MySQL database hosted by a central computer, but the way I found to host a MySQL database is using an External program as Xampp or WampServer. I am Wodering if I can host a MySQL database using only Qt's classes like QTcpServer without the needing of external programs.
| No. MySQL needs a MySQL Server process to manage connections, permissions, SQL parsing, storage engines, caching, etc. You can't use a MySQL database without a MySQL Server.
You might like to explore using SQLite, which is a free embedded database that can be used without requiring a separate daemon process. SQLite is a different product than MySQL, so there will be differences in its implementation of some SQL language features. Be sure to study the SQLite documentation: https://sqlite.org/docs.html
I did a quick Google search (my search phrase was "qt with sqlite") and I found numerous blogs and tutorials about how to use SQLite in an application with Qt. Here's just the first result, but there are others: https://katecpp.github.io/sqlite-with-qt/
|
72,220,948 | 72,243,167 | Find place that causes segmentation fault without IDE | I'm studying one project in C++. It's quite big, build is created with cmake. After installing all dependencies and libs it's the build is done fine. But when I run it, I get Segmentation fault.
Here is the thing: There is no IDE, running this project with cmake in VS Code. I wonder if it's possible to find this place in code which causes Segmentation fault. I know that there is GDB debugger for such things. I run several commands and here's what I get:
gdb build/studpark
...
Reading symbols from build/studpark...
(gdb) run
Starting program: /Users/admin/Downloads/StudPark-develop/build/studpark
[New Thread 0x2503 of process 7316]
[New Thread 0x1903 of process 7316]
[New Thread 0x1a03 of process 7316]
warning: unhandled dyld version (17)
Thread 3 received signal SIGSEGV, Segmentation fault.
0x00007ff809bec6b2 in ?? ()
(gdb) backtrace
#0 0x00007ff809bec6b2 in ?? ()
#1 0x00007ff7bfeff510 in ?? ()
#2 0x0000000100002abe in main ()
Backtrace stopped: frame did not save the PC
The question is: Is it possible to trace and find exact place in code that causes segmentation fault?
EDIT: I compile my project with these flags:
set(CMAKE_CXX_FLAGS "-stdlib=libc++ -g")
My platform is Mac OS.
| I've found a solution for my case and here's what I've done:
Installed these VS Code Extensions - CodeLLDB
Added Configuration File: Run/'Add Configuration...'
The config file was at <root_dit>/.vscode/launch.json and looked like this:
{
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/build/main",
"args": [],
"cwd": "${workspaceFolder}"
}
]
}
In my case I only changed "program": "${workspaceFolder}/build/main" to show path to my executable file.
After doing these actions I was able to run my program in Debug mode with breakpoints which helped me to examine project and find errors in code.
|
72,221,687 | 72,222,374 | The configuration option popup for debugging a c++ project in Visual Studio Code does not appear | so I want to debug my .cpp program file but when I click on the Run and Debug button and proceed to select my debugging environment (C++ (GDB/LLDB)), the popup to select the configuration option does not even appear at all and the debugging just doesn't start.
This is before I click the environment popup:
and this is after:
Any help I can get for this problem is greatly appreciated as I can't seem to find any solutions at all on the internet, thank you very much!
p.s I've already tried uninstalling VS Code completely off my laptop and resetted all the settings and it didn't work.
| Are you sure you installed the C/C++ Studio Code extension? If you don't get the popup, try writing the json files manually.
Create a .vscode folder in your working directory. In there create a file launch.json in which you declare how you run the debugger
{
"configurations": [
{
"name": "Debug",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}\\test.exe",
"stopAtEntry": true,
"cwd": "${workspaceRoot}",
"preLaunchTask": "Build Debug",
"miDebuggerPath": "c:\\mingw64\\bin\\gdb.exe"
}
]
}
This runs the gdb debugger that came with MinGW. You need to provide the path to your debugger at miDebuggerPath.
This debugs an executable test.exe that needs to be created in debug mode. For this you have the preLaunchTask option. In .vscode create a file tasks.json in which you describe the debug task as
{
"tasks": [
{
"type": "cppbuild",
"label": "Build Debug",
"command": "g++",
"args": [
"${workspaceRoot}\\test.cpp",
"-g",
"-o",
"${workspaceRoot}\\test.exe"
],
}
],
"version": "2.0.0"
}
This uses the gcc or g++ compiler that also comes with MinGW to compile a single source file test.cpp into the test.exe binary. You can select the debug launch configuration in the lower left corner of Studio Code and click Run.
|
72,221,721 | 72,222,177 | Handling custom vector classes | I have come across many occasions where I want to have an item which is selected inside a vector, for this I have written the template class:
// a vector wrapper which allows a specific item to be currently selected
template<typename T>
class VectorSelectable
{
public:
VectorSelectable() {};
VectorSelectable(std::initializer_list<T> items) : m_Items(items) {};
void Add(const T& v) { m_Items.push_back(v); m_CurrentIndex = m_Items.size()-1; } // lvalue & refs
void Add(T&& v) { m_Items.push_back(std::move(v)); m_CurrentIndex = m_Items.size()-1; } // rvalue
void Remove(size_t index) {
assert(index < m_Items.size());
m_Items.erase(m_Items.begin() + index);
if(m_CurrentIndex != -1 && (int)index <= m_CurrentIndex)
m_CurrentIndex--;
}
void RemoveCurrent() { assert(m_CurrentIndex > -1 && m_CurrentIndex < (int)m_Items.size()); Remove(m_CurrentIndex); }
T& CurrentItem() { assert(m_CurrentIndex > -1 && m_CurrentIndex < (int)m_Items.size()); return m_Items[m_CurrentIndex]; }
T& operator [](size_t index) { assert(index < Size()); return m_Items[index]; }
// moves value of n_next onto n, and n_new onto n
void ItemSwap(size_t n, size_t n_Next) {
assert(n < m_Items.size());
assert(n_Next < m_Items.size());
T itemBuf = std::move(m_Items[n]);
m_Items[n] = m_Items[n_Next];
m_Items[n_Next] = std::move(itemBuf);
}
size_t Size() { return m_Items.size(); }
const std::vector<T>& Data() { return m_Items; }
std::vector<T>* DataPtr() { return &m_Items; }
T* ItemPtr(size_t index) { assert(index < m_Items.size()); return &m_Items[index]; }
void SetCurrentIndex(int index) { assert(index >= -1 && index < (int)m_Items.size()); m_CurrentIndex = index; }
int& CurrentIndex() { return m_CurrentIndex; }
bool HasItemSelected() { return m_CurrentIndex != -1; }
private:
std::vector<T> m_Items;
int m_CurrentIndex = -1;
};
I am also coming across many scenarios where I want a vector of unique_ptrs (generally for polymorphic classes), this looks like this:
template<typename T>
class Vector_UniquePtrs
{
public:
// Adds an Item (and returns a raw ptr to it)
// usage: v.Add() ... (equivelent to v.Add<base_class>())
template<typename... Args>
T* Add(Args... args) {
return Add<T>(args...);
}
// Adds a Polymorphic Item (and returns a raw ptr to it)
// usage: v.Add<sub_class>()
template<typename T2, typename... Args>
T* Add(Args... args) {
m_Items.push_back(std::unique_ptr<T>(new T2(args...)));
return m_Items.back().get();
}
// Remove Item
void Remove(size_t index) {
assert(index < m_Items.size());
m_Items.erase(m_Items.begin() + index);
}
T* operator [](size_t index) { assert(index < Size()); return m_Items[index].get(); }
size_t Size() { return m_Items.size(); }
private:
std::vector<std::unique_ptr<T>> m_Items;
};
My question is:
How can I handle a combination of these 2 class types (e.g. VectorSelectable<unique_ptr>) as one returns ptrs, the other returns references, is the only option to write an entirely new class?
| You mainly need to put the std::vector<std::unique_ptr<T>> in VectorSelectable and hide all the pointer stuff from the interface. With a few small changes to your class, it could look like this:
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>
#include <vector>
template <typename T>
class VectorPtrSelectable {
public:
VectorPtrSelectable() = default;
VectorPtrSelectable(std::initializer_list<T> items) :
m_CurrentIndex(items.size() - 1)
{
m_Items.reserve(items.size());
// fill `m_Items` from the initializer list ...
std::transform(items.begin(), items.end(), std::back_inserter(m_Items),
[](const T& item) {
// ... by creating a unique_ptr from each element (transformation)
return std::make_unique<T>(item);
});
};
template <class U, class... Args>
T& Add(Args&&... args) {
// make `Add` forward to `make_unique`
m_Items.emplace_back(std::make_unique<U>(std::forward<Args>(args)...));
m_CurrentIndex = m_Items.size() - 1;
// and return a reference instead
return *m_Items.back();
}
template <class... Args>
T& Add(Args&&... args) {
// forward to Add<U>
return Add<T>(std::forward<Args>(args)...);
}
void Remove(size_t index) {
m_Items.erase(std::next(m_Items.begin(), index));
if (m_CurrentIndex != static_cast<size_t>(-1) && index <= m_CurrentIndex)
m_CurrentIndex--;
}
T& operator[](size_t index) { return *m_Items[index]; }
const T& operator[](size_t index) const { return *m_Items[index]; }
T& CurrentItem() { return *m_Items[m_CurrentIndex]; }
const T& CurrentItem() const { return *m_Items[m_CurrentIndex]; }
void SetCurrentIndex(size_t index) { m_CurrentIndex = index; }
void RemoveCurrent() { Remove(m_CurrentIndex); }
bool HasItemSelected() { return m_CurrentIndex != static_cast<size_t>(-1); }
void ItemSwap(size_t n, size_t n_Next) {
// simplified swapping:
std::swap(m_Items[n], m_Items[n_Next]);
}
// make functions that does not change your instance const qualified:
size_t CurrentIndex() const { return m_CurrentIndex; }
size_t Size() const { return m_Items.size(); }
private:
std::vector<std::unique_ptr<T>> m_Items;
size_t m_CurrentIndex = static_cast<size_t>(-1); // size_t for the index
};
Example usage:
#include <iostream>
#include <string>
int main() {
VectorPtrSelectable<std::string> vs{"World", "Hello"};
std::cout << vs.CurrentItem() << '\n';
vs.ItemSwap(0, 1);
std::cout << vs.CurrentItem() << '\n';
vs.RemoveCurrent();
std::cout << vs.CurrentItem() << '\n';
std::cout << vs.Add("Add and get a reference") << '\n';
}
Output:
Hello
World
Hello
Add and get a reference
I made m_CurrentIndex a size_t because that's idiomatic but if you'd like to keep it as an int, that's fine too.
std::next(m_Items.begin(), index) will do the same as m_Items.begin() + index, but in cases where the iterator returned by m_Items.begin() is a plain pointer, using std::next avoids potential warnings about using pointer arithmetic.
Returning a reference instead of a pointer to the added element makes no difference other than making the interface more idiomatic. It's simply what a user of the class is likely to expect. Returning a pointer also opens up questions like "can it return nullptr?" etc.
The added const qualified functions makes those functions usable in const contexts too.
template<class T>
void foo(const VectorPtrSelectable<T>& vps) { // note: const&
if(vps.Size() > 0) {
std::cout << "the first element is " << vps[0] << '\n';
std::cout << "the current element is " << vps.CurrentItem() << '\n';
}
}
None of the three member functions used above could be used without the const qualified overloads.
|
72,222,054 | 72,222,088 | Overload == operator for a boost::variant | I have a boost::variant of a bunch of types (int, double, custom class etc) and need to implement an overload for the == operator. How do I go about this?
My error is wrt the == operator, complaining that "too few operators for this operation". What am I missing here? I do not see any errors for the << operator. It complies fine.
namespace xyz
{
typedef boost::variant<
int,
double,
Date,
std::vector<int>,
std::vector<double>,
std::vector<Date>,
> someVariant;
ostream& operator<<(ostream& out, const someVariant& rhs);
bool operator==(const someVariant& other);
}
| Your << operator takes two arguments, the stream and the variant.
Your operator== takes one argument. If you're defining a free function operator==, the signature should be bool operator==(const someVariant& lhs, const someVariant& rhs).
|
72,222,245 | 72,226,903 | Is there a more stringent version of std::stoi? | I just discovered (much to my surprise) that the following inputs do not cause std::stoi to throw an exception:
3.14
3.14helloworld
Violating the principle of least surprise - since none of these are valid format integer values.
Note, perhaps even more surprisingly 3.8 is converted to the value 3.
Is there a more stringent version of std::stoi which will throw when an input really is not a valid integer? Or do I have to roll my own?
As an asside, why does the C++ standard library implement std::stoi this way? The only practical use this function has is to desperately try and obtain some integer value from random garbage input - which doesn't seem like a very useful function.
This was my workaround.
static int convertToInt(const std::string& value)
{
std::size_t index;
int converted_value{std::stoi(value, &index)};
if(index != value.size())
{
throw std::runtime_error("Bad format input");
}
return converted_value;
}
| The answer to your question:
Is there a more stringent version of std::stoi?
is: No, not in the standard library.
std::stoi, as described here behaves like explained in CPP reference:
Discards any whitespace characters (as identified by calling std::isspace) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value. The valid integer value consists of the following parts: . . . . .
And if you want a maybe more robust version of std::stoi which fits your special needs, you do really need to write your own function.
There are that many potential implementations that there is not the ONE "correct" solution. It depends on your needs and programming style.
I just show you (one of many possible) example solution:
#include <iostream>
#include <string>
#include <utility>
#include <regex>
// Some example. Many many other different soultions possible
std::pair<int, bool> stoiSpecial(const std::string s) {
int result{};
bool validArgument{};
if (std::regex_match(s, std::regex("[+-]?[0-9]+"))) {
try {
result = stoi(s);
validArgument = true;
}
catch (...) {};
}
return {result, validArgument };
}
// Some test code
int main() {
std::string valueAsString{};
std::getline(std::cin,valueAsString);
if (const auto& [result, validArgument] = stoiSpecial(valueAsString); validArgument)
std::cout << result << '\n';
else
std::cerr << "\n\n*** Error: Invalid Argument\n\n";
}
|
72,222,249 | 72,222,309 | How can I get this code to make LEDs linked to my arduino flash at either the value the dial outputs, or no more than a determined value? | Before I get started I want to make it clear I am still a beginner in both C++ and Arduino electronics, so the answer may be painfully obvious to someone with even a week more experience than me.
But to me, it is a total mystery. Thank you for any help.
To begin this is the code:
int potPosition;
int delayTime;
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
}
void loop() {
potPosition = analogRead(A0);
Serial.println(potPosition);
if (potPosition < 16) {
delayTime == 16;
} else if (potPosition >= 16){
delayTime == analogRead(A0);
}
digitalWrite(13, HIGH);
digitalWrite(12, HIGH);
digitalWrite(11, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, HIGH);
delay(delayTime);
digitalWrite(13, LOW);
digitalWrite(12, LOW);
digitalWrite(11, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
delay(delayTime);
}
This is all written in the Arduino Genius IDE and I am outputting it to a Sparkfun electronics Arduino with 5 LEDs connected to it controlled by a potentiometer, which sets the on and then off delay by outputting a value I take as milliseconds of delay to make the LEDs flash. All the electronic wiring is correct, as when I remove the if statement and just run it as normal, everything works as I'd expect.
So you may be wondering, what's the issue? Well, currently when the potPosition exceeds a certain value - a delay value in ms - which is too low, the LEDs no longer appear to flash, as the delay is far to small for the flash to be visible. This is an expected outcome, as a delay of nearing 0ms is extremely small.
What I am trying to do with my if statement:
if (potPosition < 16) {
delayTime == 16;
} else if (potPosition >= 16){
delayTime == analogRead(A0);
}
is if the potPosition - the value of the dial which is the ms delay - goes below a certain number (the last value which is a long enough delay for a flashing effect to still be visible) set my delayTime back to that value and if the potPosition is that value or anything higher, then set the delayTime to whatever delay the potentiometer is outputting.
However, currently, when I download this code onto my Arduino all my lights appear dim (the same way they do when my delay time is extremely low) no matter what value my potentiometer is outputting, which is not what I want it to do, and I have no idea why my if statement is not resetting my delay time correctly.
I've never really coded C++ before starting on a Sparkfun electronics kit, and only ever used Python, so I may be missing a key aspect of programming in C++, but I have no idea what that would be.
Any help with this issue would be great, and I am more than happy to answer any questions.
| This delayTime == analogRead(A0); and this delayTime == 16; are comparisons, i.e. delayTime remains uninitialised and you get undefined behaviour.
I bet you want to write a value there, as in delayTime = analogRead(A0); or maybe delayTime = potPosition; (same for the other ==). The latter seems more plausible to me, so as to only have one analog read per loop iteration.
|
72,222,269 | 72,222,433 | What are the differences between a template and a function pointer for a Strategy design pattern in C++ | I'm implementing a Strategy Design Pattern in c++, and I've found a couple of different options I could take. One route would be to use a template, and might look like this:
namespace Strategies
{
struct IsEven
{
bool doSomething(int x) { return x % 2 == 0; }
};
struct IsOdd
{
bool doSomething(int y) { return y % 2 == 1; }
};
}
template<typename Strategy>
class Processor
{
public:
Processor() : _strat{ Strategy() }
{}
bool process(int num)
{
return _strat.doSomething(num);
}
private:
Strategy _strat;
};
int main()
{
Processor<Strategies::IsEven> templateOne{};
Processor<Strategies::IsOdd> templateTwo{};
std::cout << "Process 4 with One: " << (templateOne.process(4) ? "True" : "False") << std::endl;
std::cout << "Process 4 with Two: " << (templateTwo.process(4) ? "True" : "False") << std::endl;
}
Another route would be to use function pointers, and might look like this:
#include <functional>
class ProcessorTwo
{
public:
using StrategyFunction = std::function<bool(int)>;
static bool lessThanFive(int num) {
return num < 5;
}
static bool greaterThanFive(int num) {
return num > 5;
}
ProcessorTwo(StrategyFunction strat) : _strat{ strat }
{}
bool process(int num) {
return _strat(num);
}
private:
StrategyFunction _strat;
};
int main()
{
ProcessorTwo functionPointerOne{ ProcessorTwo::greaterThanFive };
ProcessorTwo functionPointerTwo{ ProcessorTwo::lessThanFive };
std::cout << "Process 4 with One: " << (functionPointerOne.process(4) ? "True" : "False") << std::endl;
std::cout << "Process 4 with Two: " << (functionPointerTwo.process(4) ? "True" : "False") << std::endl;
}
I will know the functions that will be used at compile time. I'm new enough to c++ that I don't really understand what the differences between these two approaches would be. I've heard function pointers add a layer of indirection, but wouldn't the same also be true of a struct holding the function? Is there a more "idiomatic" c++ option, or does it just come down to developer preference?
| The main difference is the template version uses "compile time polymorphism" meaning the selection of the strategy happens at compile time and the strategy is part of the type. Thus, the strategy a particular instance of Processor<T> uses must be known at compile time and cannot be changed dynamically after a Processor<T> is created.
You could add a member function, however, to make it so the strategy used by a ProcessorTwo can be changed dynamically. You could also write, say, a function that takes a std::function<bool(int)> as an argument and creates a ProcessorTwo with it in the function's body; you couldn't do this with a Processor<T> unless it was a function template.
So if you need that kind of dynamism a function pointer or std::function based approach is the way to go, but if you don't need it then the template version will be more efficient because calling the strategy will not involve runtime indirection.
|
72,222,917 | 72,223,186 | Private compile-time -> run-time adapter. Strange compilation error | Basically, this code fails with a very strange error:
<source>:75:29: error: cannot convert 'get_view<main()::<unnamed struct>, run_time::data_view>::operator()(const main()::<unnamed struct>&) const::View::code' from type 'int (get_view<main()::<unnamed struct>, run_time::data_view>::operator()(const main()::<unnamed struct>&) const::View::)() const' to type 'int'
75 | return data.code;
https://godbolt.org/z/T3h1a7zne
template <typename SourceT, typename ViewT>
struct get_view;
template <typename SourceT>
struct get_view<SourceT, SourceT>
{
constexpr decltype(auto) operator()(const SourceT &source) const
{
return source;
}
};
// api.h
#include <iostream>
class compile_time
{
public:
template <typename DataT>
void operator()(const DataT &data) const
{
std::cout << "compile-time: " << data.code << std::endl;
}
};
class run_time
{
// How to make data_view private?
// private:
public:
class data_view;
public:
template <typename DataT>
void operator()(const DataT &data) const
{
(*this)(get_view<DataT, data_view>{}(data));
}
private:
void operator()(const data_view &data) const;
};
class run_time::data_view
{
public:
virtual int code() const = 0;
protected:
~data_view() = default; // do not own this
};
template <typename DataT>
struct get_view<DataT, run_time::data_view>
{
// don't want to return std::unique_ptr<data_view>
auto operator()(const DataT &data) const
{
struct View : run_time::data_view {
const DataT& data;
View(const DataT &data)
: data(data)
{}
int code() const override
{
return data.code;
}
};
return View(data);
}
};
// .cpp
void run_time::operator()(const run_time::data_view &dataView) const
{
std::cout << "run-time: " << dataView.code() << std::endl;
}
// main.cpp
int main()
{
struct {
double irrelevant;
int code;
} data{42, 815};
compile_time{}(data);
run_time{}(data); // does not compile!!!
return 0;
}
I can't find an explanation for it.
Why does it say that data.code is of a function type?
Is it possible to make this work? I don't want data_view to be returned as std::unique_ptr.
What I expect:
Upon get_view partial specialization for run_time::data_view data_view is a complete type.
operator()(const DataT &) is specialized after main::<unnamed struct> (which is data) has been created, so it is also a complete type.
auto can be deduced: both data_view and DataT are complete
const run_time::data_view & is a public base of the returned local struct, so the object's reference is implicitly convertible
So can anyone explain the reason why it fails and how to make it work without resorting to heap allocations? (run_time::data_view should be private. I don't want it to be used anywhere outside the class or designated adapter get_view).
This worked:
template <typename DataT>
void operator()(const DataT &data) const
{
const data_view &view = get_view<DataT, data_view>{}(data);
(*this)(view);
}
I guess it causes a recursion because auto deduced from get_view is not of a type const data_view&. So the compiler gets confused on which operator()(data) to invoke. With explicit conversion to a reference it gets clear.
However, there is a question of why it decides to go with a template first, but not with an overload that takes a const reference.
| The problem was caused by an ambiguity during function resolutions:
get_view returns a deduced type by value that is a good candidate for
template <typename DataT> operator()(const DataT &), thus ignoring the existing overload operator()(const data_view &).
Providing an explicit cast before operator's invocation solves the problem.
template <typename DataT>
void operator()(const DataT &data) const
{
const data_view &view = get_view<DataT, data_view>{}(data);
(*this)(view);
}
|
72,223,257 | 72,223,338 | Template arguments can't be deduced for shared_ptr of class derived from templated base | I'm running into a case where I thought that the compiler would obviously be able to do template argument deduction, but apparently can't. I'd like to know why I have to give explicit template args in this case. Here's a simplified version of what's going on.
I have an inheritance hierarchy where the base class is templated and derived classes are concrete implementations of the base:
template <typename T> class Base {};
class Derived : public Base<int> {};
Then I have a templated function which accepts a shared pointer of the base class:
template <typename T> void DoSomething(const std::shared_ptr<Base<T>> &ptr);
When I try to call this method, I have to explicitly provide the template arguments:
std::shared_ptr<Derived> d = std::make_shared<Derived>();
DoSomething(d); // doesn't compile!
DoSomething<int>(d); // works just fine
In particular, I get this error message if I don't use explicit template arguments:
main.cpp:23:18: error: no matching function for call to ‘DoSomething(std::shared_ptr&)’
23 | DoSomething(d);
| ^
main.cpp:10:28: note: candidate: ‘template void DoSomething(const std::shared_ptr >&)’
10 | template <typename T> void DoSomething(const shared_ptr<Base<T>> &ptr)
| ^~~~~~~~~~~
main.cpp:10:28: note: template argument deduction/substitution failed:
main.cpp:23:18: note: mismatched types ‘Base’ and ‘Derived’
23 | DoSomething(d);
| ^
What's even more confusing to me is that template arguments can be deduced if I don't use shared_ptr:
template <typename T> void DoSomethingElse(const Base<T> &b);
Derived d;
DoSomethingElse(d); // doesn't need explicit template args!
So obviously I need to specify the template arguments for DoSomething. But my question is, why? Why can't the compiler deduce the template in this case? Derived implements Base<int> and the type can be deduced in DoSomethingElse, so why does sticking it in a shared_ptr change the compiler's ability to figure out that T should be int?
Full example code which reproduces the issue:
#include <iostream>
#include <memory>
template <typename T> class Base {};
class Derived : public Base<int> {};
template <typename T> void DoSomething(const std::shared_ptr<Base<T>> &ptr)
{
std::cout << "doing something" << std::endl;
}
template <typename T> void DoSomethingElse(const Base<T> &b)
{
std::cout << "doing something else" << std::endl;
}
int main()
{
std::shared_ptr<Derived> d = std::make_shared<Derived>();
// DoSomething(d); // doesn't compile!
DoSomething<int>(d); // works just fine
Derived d2;
DoSomethingElse(d2); // doesn't need explicit template args!
return 0;
}
| Derived is a derived class of Base<int>, but std::shared_ptr<Derived> isn't a derived class of std::shared_ptr<Base<int>>.
So if you have a function of the form
template <typename T> void f(const Base<T>&);
and you pass a Derived value to it, the compiler will first notice that it can't match up Base<T> against Derived, and then try to match up Base<T> against a base class of Derived. This then succeeds since Base<int> is one of the base classes.
If you have a function of the form
template <typename T> void f(const std::shared_ptr<Base<T>>&);
and you pass a std::shared_ptr<Derived>, then the compiler will fail to match that against std::shared_ptr<Base<T>> and then try with base classes of std::shared_ptr<Derived>. If the latter has any base classes at all, they are internal to the standard library, and not related to std::shared_ptr<Base<T>>, so deduction ultimately fails.
What you are asking the compiler to do here is to say: "aha! std::shared_ptr<Derived> can be converted into std::shared_ptr<Base<int>>, which matches the function parameter!" But the compiler won't do that, because in general, there is no algorithm that the compiler can use in order to make a list of all types that a given type can be converted to.
Instead, you must help the compiler by telling it explicitly what to convert to. This can be done like so:
template <typename T>
Base<T> get_base(const Base<T>*); // doesn't need definition
template <typename T> void DoSomething(const std::shared_ptr<Base<T>> &ptr);
template <typename D, typename B = decltype(get_base((D*)nullptr))>
void DoSomething(const std::shared_ptr<D>& ptr) {
DoSomething(static_cast<std::shared_ptr<B>>(ptr));
}
Here, when the second DoSomething overload is called with an argument of type std::shared_ptr<D>, the get_base helper function will be used to determine the base class of D itself that has the form Base<T>. Then, the std::shared_ptr<D> will be explicitly converted to std::shared_ptr<Base<T>> so that the first overload can be called. Finally, note that if D isn't a derived class of any Base<T>, the second overload will be removed from the overload set, potentially enabling some other overload to handle the argument type.
|
72,223,866 | 72,231,172 | gdb <error reading variable> for any string object | Lets take this very simple program here for example:
// test.cpp
#include <string>
#include <iostream>
using namespace std;
int main() {
string str = "Hello";
cout << str << endl;
return 0;
}
now I compile this code with g++ compiler:
g++ -g test.cpp -o test.exe
now I am trying to debug this with gdb:
gdb test.exe
after I set breakpoint on main and then reach the line return 0, I try to see what is in the string str. But I cannot print it in the console. It says <error reading variable>. Not only in gdb console, even Visual Studio Code UI using gdb gives the same output.
Here is a screenshot of my console:
I have searched for this everywhere and the only relevant question I found was this, which did not work.
I also found this post on github VS Code repo issues. The fix suggested there might work I am not sure, I cannot find the setting that he suggested on my Windows 11 machine.
How do I read the value in the string in debug mode?
Edit
After @ssbssa suggested me to update my gcc, I used MSYS2 to get the latest gcc, g++, and gdb versions. Now I have gdb 12.1. Now it is not showing the old error anymore but now it says "Converting character sets: Invalid argument". Still struggling to get it to work.
| First run your program with gdb like so:
gdb test.exe
Now inside the command line interface run the command:
set charset UTF-8
This should temporarily fix your problem. The only inconvenience might be that you need to run this line every time you debug on your command prompt with GDB.
I noticed that you are also using Visual Studio Code. You can install C++ extensions for VS Code and there you can add the command set charset UTF-8 in the launch.json setupCommands array as shown here. This way you can debug your application faster.
|
72,224,463 | 72,226,010 | Passing an rvalue to a function | I read a lot of information about rvalue links, I understood everything, but I met this example:
template<class T, class Arg>
T* make_raw_ptr(Arg &&arg)
{
return new T(arg);
};
If you pass rvalue to the make_raw_ptr function without using the my_forward function, when using new T, there will be a copy constructor, not a move constructor. I understand that arg will be lvalue, despite the fact that it is an rvalue reference, but I have one question. Why make a static_cast arg to an rvalue link when it is already an rvalue link, while using a static_cast<A&&> to arg, the move constructor will be called?
| arg itself is an expression that represents an object referred to by arg and its value category is lvalue. It doesn't matter what the type of arg actually is. A name of a variable / function parameter itself is always an lvalue expression.
static_cast<A&&>(arg) is an expression that represents the very same object as arg, but its category is rvalue (and xvalue). When you use this expression as the constructor argument, the move constructor will be preferred. The same effect is with std::move(arg).
|
72,224,660 | 72,224,865 | Compilation error - defining a concrete implementation of templated abstract class | I have an abstract class in my header file:
template <class T>
class IRepository {
public:
virtual bool SaveData(Result<T> &r) = 0;
//virtual Result<T> & GetData()const = 0;
virtual ~IRepository() {}
};
I inherit it in the header file itself:
template <class T>
class Repo1 :public IRepository<T>
{
public:
bool SaveData(Result<T> &r)override;
//Result<T> & GetData() const override;
private:
std::mutex mx;
std::queue<T> m_q;
};
I am trying to define SaveData in the cpp file:
template <class T>
bool Repo1::SaveData(Result<T> &r)
{
std::lock_guard<std::mutex> lock(mx);
if (m_q.size() > 10)
{
m_q.pop();
}
m_q.push(r);
return true;
}
The compiler complains:
'twsensors::Repo1': use of class template requires template argument list
The compiler doesn't complain about the following:
template <class T>
bool SaveData(Result<T> &r)
{
std::lock_guard<std::mutex> lock(mx);
if (m_q.size() > 10)
{
m_q.pop();
}
m_q.push(r);
return true;
}
The problem with this is if I create class Repo2 :public IRepository<T>, then both of them will have their Save method point to the same definition.
What's the reason behind the compilation error?
| While implementing the template class method outside the class definition, the template class requires template arguments:
template <class T>
bool Repo1<T>::SaveData(Result<T> &r)
|
72,224,881 | 72,225,569 | IMG_Load() with jpg returns "unsupported image format" | I'm trying to load images using SDL2-image, it works when I try to load a .png, but it fails to recognize a .jpg
My imports:
#include <SDL2/SDL.h>
#undef main
#include <SDL2/SDL_image.h>
#include "logger.hpp"
And my code:
int main(int argc, char **argv) {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
logger::Log(logger::DEBUG, "Could not initialize SDL (%s)", SDL_GetError());
}
int flags = IMG_INIT_JPG | IMG_INIT_PNG;
int initRes = IMG_Init(flags);
if (initRes & flags != flags) {
logger::Log(logger::DEBUG, "IMG_Init: Failed to init required jpg and png support!");
logger::Log(logger::DEBUG, "IMG_Init: %s", IMG_GetError());
}
else logger::Log(logger::DEBUG, "JPG AND PNG SUPPORTED");
SDL_Surface* surface = IMG_Load("image.jpg");
if (!surface) {
logger::Log(logger::DEBUG, "surface error: %s", IMG_GetError());
}
else {
logger::Log(logger::DEBUG, "LOADED");
}
...
}
Which gives me
JPG AND PNG SUPPORTED
surface error: Unsupported image format
There are installed and integrated via vcpkg: SDL2-image, libjpeg-turbo, libpng and zlib, so I basically have no idea why this is happening
| Due to operator precedence initRes & flags != flags is equivalent to initRes & (flags != flags) which will always be false. You need to use (initRes & flags) != flags instead.
Jpeg support is an optional feature, you need to enable libjpeg-turbo.
|
72,225,300 | 72,225,530 | Generating compile time functions string for formatting strings with libfmt | I want to create a nice table in stdout. The table has a lot of headers that are mainly compiletime strings. For example:
std::cout << fmt::format("|{0:-^80}|\n", "File Information");
The above prints:
|-----------------------------File Information------------------------------|
I have lots of different type of fills and align widths. I decided to make some helper functions:
constexpr static
std::string_view
headerCenter(const std::string& text, const int width, const char fill) {
// build fmt string
const std::string_view format = "{:" + 'fill' + '^' + toascii(width) + '}';
return fmt::format(format, text);
}
I got this error while compiling:
Constexpr function never produces a constant expression
What is it that I am doing wrong, and how to do it correctly?
| The type of the format string and the return type of the function cannot be string_view since the format string is constructed dynamically, using string_view will result in a dangling pointer.
In addition, fmt::format requires that the format string must be a constant expression. Instead, you need to use fmt::vformat. This should work
static std::string
headerCenter(const std::string& text, const int width, const char fill) {
// build fmt string
std::string format = fmt::format("|{{0:{}^{}}}|", fill, width);
return fmt::vformat(format, fmt::make_format_args(text));
}
Demo
|
72,225,697 | 72,225,838 | How can I encapsulate code dealing with matrices and make it reusable? | At my course we are getting tasks that always start with filling a random matrix size nxm with random numbers.
I want to create(a library?, a class?) some structure so than any time I want to generate a matrix A I would need just to input the desired size nxm.
In other words, change all this code for something like #include <myrandommatrixgenerator>.
int n, m;
cout << "Enter number of rows (n): ";
cin >> n;
cout << "Enter number of columns (m): ";
cin >> m;
//matrix b with random numbers
srand(time(NULL));
int max = 9, min = -9;
int *b = new int[n*m];
for (int i = 0; i<n; i++)
{
for (int j = 0; j<m; j++)
{
b[i*m + j] = min + ((rand() % max) + 1);
}
}
//print matrix b
cout << "\nMatrix b:" << endl;
for (int i = 0; i<n; i++)
{
for (int j = 0; j<m; j++)
{
cout << setw(5) << b[i*m + j];
}
cout << endl;
}
I do not have a broad overview of the possibilities with C++, so what is the structure that allow me to do that?
| Below is an outline of what you can do to achieve that:
Define a class e.g. MyMatrix. A class can encapsulate data and operations related to it. The class can be placed in separate files (h and cpp). A friendly guide: C++ Classes and Objects - w3schooles.
This class should use e.g. a std::vector to hold the data (better than using raw pointers like in your code).
This class should have public methods for getting the metadata (n,m) and data.
This class should have a public method, e.g.: InitRandom(int n, int m), to initialize the MyMatrix object to a matrix size n x m with random values.
In another part of your program you can #include your class h file, and then instantiate a MyMatrix object, and use InitRandom to do what you need.
You can see here a discussion about implementing a matrix class: https://codereview.stackexchange.com/questions/155811/basic-matrix-class-in-c
|
72,225,918 | 72,226,378 | How to judge whether the incoming buffer is valid in C++? | In my function, a memory pointer and its size are passed as parameters:
int myFun(uintptr_t* mem_ptr, int mem_size) {
// Code here
}
Is there any way to tell if this chunk of memory is really valid?
(The Operating System is CentOS Linux release 7.9.2009.)
| Don't. Just don't.
Even if you could find a way to check whether the pointer can safely be dereferenced, that doesn't mean it points where you think it does! It might point into your call stack, into your read-only code segment, into the static variables of some library that you're using, or any other place in memory that your program happens to have access to.
The responsibility of passing a valid pointer should be with the caller of the function. To make it harder for the caller to do something stupid, consider passing a std::vector & or std::vector const & instead.
|
72,226,065 | 72,226,203 | Is placement new on a const variable with automatic storage duration legal? | Is the following code legal according to the standard?
#include <new>
int main() {
const int x = 3;
new ((void *)&x) int { 15 };
}
It seems to me that as long as there is no use of a reference to x it should be valid.
As per the c++ standard basic.life 8:
a pointer that pointed to the original object, a reference that
referred to the original object [...]
the type of the original
object is not const-qualified, and, if a class type, does not contain
any non-static data member whose type is const-qualified or a
reference type
PS : if the answer could contain a reference to the standard it would be much appreciated
|
Is the following code legal according to the standard?
The behaviour of the program is undefined:
[basic.life]
Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.
|
72,226,451 | 72,356,738 | A windows app calls two C++ DLLs with same name and APIs linking to another DLL | I'm trying to let my C# app run two different version of C++ DLLs at the same time.
The two DLLs with same file name and APIs are located in different directories:
App -> V1/A.dll -> V1/B.dll
-> V2/A.dll -> V2/B.dll
From Dynamic-Link Library Search Order, I've learned how to make one A.dll call the B.dll in the same directory by LoadLibraryEx() and SetDllDirectory().
It works fine if my app calls the two version separately:
SetDllDirectory("V1");
v1 = LoadLibraryEx("V1/A.dll", null, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
SetDllDirectory(null);
v1.open();
v1.runall();
v1.close();
SetDllDirectory("V2");
v2 = LoadLibraryEx("V2/A.dll", null, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
SetDllDirectory(null);
v2.open();
v2.runall();
v2.close();
But it goes wrong (divide-by-zero exception) if the two version run frame-by-frame:
SetDllDirectory("V1");
v1 = LoadLibraryEx("V1/A.dll", null, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
SetDllDirectory(null);
SetDllDirectory("V2");
v2 = LoadLibraryEx("V2/A.dll", null, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_USER_DIRS);
SetDllDirectory(null);
v1.open();
v2.open();
foreach (frame in frames)
{
v1.run(frame);
v2.run(frame); // divide-by-zero exception occurs
}
v1.close();
v2.close();
Since it's likely that v2 calls something wrong in A.dll or B.dll, I added some test APIs in the DLLs:
A.dll:
int _a = 0;
void set_var(int a, int b) {
_a = a;
set_var_b(b);
}
void get_var(int *a, int *b) {
*a = _a;
*b = get_var_b();
}
B.dll:
int _b = 0;
void set_var_b(int b) {
_b = b;
}
int get_var_b() {
return _b;
}
It seems that v1 and v2 share the same data memory of global variables in B.dll, but they doesn't in A.dll:
int a1, b1;
int a2, b2;
v1.get_var(&a1, &b1); // a1 = 0, b1 = 0
v2.get_var(&a2, &b2); // a2 = 0, b2 = 0
v1.set_var(1, 2);
v2.get_var(&a2, &b2); // a2 = 0, **b2 = 2**
v2.set_var(3, 4);
v1.get_var(&a1, &b2); // a1 = 1, **b1 = 4**
My questions:
Can an app call two DLLs (A.dll) with same file name and APIs which linking to another DLL (B.dll)?
If answer to 1 is yes, is using global variables in B.dll allowed? If it isn't, what is the reason?
| Thanks for Hans Passant's comment.
In my previous case, the two different version of A.dll call the same B.dll:
App -> V1/A.dll |-> V1/B.dll
-> V2/A.dll | V2/B.dll
Manifests can be a solution to this:
Create manifest file for A.dll project
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<file name="B.dll" />
</assembly>
Add the manifest file into properties of A.dll project: Manifest Tool -> Input and Output -> Additional Manifest Files
See Also:
How can I specify that my DLL should resolve a DLL dependency from the same directory that the DLL is in?
|
72,226,515 | 72,226,772 | What is the equivalent to JavaScript setInterval in C++? | The following code prints the argument passed to the function foo in every 5 second interval.
function foo(arg) {
console.log(arg);
}
setInterval(() => foo(5), 5000);
I found this answer: https://stackoverflow.com/a/43373364/13798537 that calls a function at periodic interval, but I couldn't figure out how to call a function at periodic interval that takes argument as shown in the javascript code.
Is there an equivalent to the javascript code in C++?
Thanks.
| You actually can get pretty close to the javascript syntax:
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <memory>
#include <atomic>
using cancel_token_t = std::atomic_bool;
template<typename Fnc>
void set_interval(Fnc fun, std::chrono::steady_clock::duration interval,
std::shared_ptr<cancel_token_t> cancel_token=nullptr)
{
std::thread([fun=std::move(fun), interval, tok=std::move(cancel_token)]()
{
while (!tok || !*tok) // Call until token becomes true (if it is set)
{
auto next = std::chrono::steady_clock::now() + interval;
fun();
std::this_thread::sleep_until(next);
}
}).detach();
}
void foo(int n)
{
std::cout << "Hello from foo("<<n<<")!\n";
}
int main()
{
using namespace std::chrono_literals;
auto cancel = std::make_shared<cancel_token_t>(false);
int x = 2;
// Ordinary rules for lambda capture apply so be careful
// about lifetime if captured by reference.
set_interval([x]{foo(5+x);}, 1000ms, cancel);
//set_interval([x]{foo(5+x);}, 1000ms); // Without token, runs until main exits.
std::this_thread::sleep_for(3s);
*cancel=true;
}
I've modified the linked question and added a cancellation token which cooperatively cancels the thread when set to true. There is of course some delay between *cancel=true and the loop check.
I made the token optional, if not used, the thread will die when process exits after return from main. Although this is not guaranteed by C++, it works on common platforms.
std::chrono enforces correct usage of time units.
Feel free to ask if I should explain anything.
|
72,226,671 | 72,226,870 | How to initiate multiple structs | I'm fairly new to C++.
Have a struct Bbox with a constructor with two arguments x and y which I have just added. Before when the constructor had no arguments I could initiate multiple instances of Bbox by doing this and num_components was the number of instances I wanted to create:
Bbox list [num_components];
But how can I do that now when the constructor require arguments?
struct Bbox {
int
left,
top,
right = 0,
bottom = 0,
mat_width,
mat_height;
Bbox(int x, int y):
left(std::numeric_limits<int>::max()),
top(std::numeric_limits<int>::max()),
mat_width(x),
mat_height(y)
{}
};
The arguments to initiate the list of Bbox are always the same. Lets say x=10 and y=20 but don't want to add default values to the construtor because the values can vary
| And, to build on @anoop's (excellent) answer, if you use std::vector instead of a C-style array (and you should!), then you can do this:
std::vector <Box> make_boxes (int num_boxes)
{
return std::vector <Box> (num_boxes);
}
And you would call it thus:
auto my_boxes = make_boxes (10);
But make_boxes is so trivial that it's hardly worth factoring it out, really.
If you want make_boxes to construct boxes with a size specified by the caller, then this would do the job:
std::vector <Box> make_boxes (int num_boxes, int x, int y)
{
std::vector <Box> boxes;
boxes.reserve (num_boxes);
for (int i = 0; i < num_boxes; ++i)
boxes.emplace_back (x, y);
return boxes;
}
and then:
auto boxes = make_boxes (10, 10, 20);
|
72,226,737 | 72,227,434 | up to 20% Numerical error or Bug in ten line code block | Rewriting a single tiny block of code of an application has yielded a considerable performance improvement. The code is 100% sequential, thus there should be no hidden perturbations to the values stored in memory.
Double-checking that the results after computation are the same has shown an up-to 20% relative error in the results, so the question is if this can be explained by numerical error in the algorithm or there is an error in the algorithm itself and the two blocks are not equivalent.
Conceptually, the main modification has been replacing this
for m=0,...
result += gradient * temp[m]
with this
for m=0,...
sum_temp += temp[m]
result = gradient * sum_temp
While in the process dealing with the process of defining new arrays and initializing them.
EDIT: (for clarity) so-called 'result' in the code below are SoGrSca and SoGrSca's elements
EDIT: typical values for (final) result are +-1e-8
Actual code is as follows (C++, weird-named nested arrays have been kept untouched at the expense of clarity)
// Three relevant macros for tidyness
//
#define FOR_I3 for (int i = 0; i < 3; ++i)
#define LOOP_n_N(NUM) for (int n = 0; n < NUM; n++)
#define LOOP_m_N(NUM) for (int m = 0; m < NUM; m++)
// Toy definitions for eye-friendlyness
// on Stackoverflow
//
const int NDIM = 6;
const int ORDER = 20;
// More definitions...
//
// 1) Arrays of doubles
//
// SoGrSca, SoGrVec, PrimSca, Jaco_Sol, PrimVec, mat_der_sol
//
// 2) Arrays of integers
//
// mat_co1, mat_co2
// Version 1 of the code
//
FOR_I3 SoGrSca[0][nk + l][i] = 0.0;
FOR_I3 FOR_J3 SoGrVec[0][nk + l][j][i] = 0.0;
//
LOOP_n_N(NDIM) LOOP_m_N(ORDER) {
int idof1 = ORDER*mat_co1[NDIM*l + n] + m;
int idof2 = mat_Gr[ndof*n + ORDER*mat_co2[NDIM*l + n] + m ];
double grp_temp = mat_der_sol[idof1]*GsGm1*PrimSca[1][nk + idof2]/PrimSca[0][nk + idof2];
FOR_I3 SoGrSca[0][nk + l][i] += Jaco_Sol[nk + l][n][i]*grp_temp;
FOR_J3 {
double grp_temp = mat_der_sol[idof1]*PrimVec[0][nk + idof2][j];
FOR_I3 SoGrVec[0][nk + l][j][i] += Jaco_Sol[nk + l][n][i]*grp_temp;
}
}
// Store SoGrSca and SoGrVec values ...
// Version 2 of the code
//
FOR_I3 SoGrSca[0][nk + l][i] = 0.0;
FOR_I3 FOR_J3 SoGrVec[0][nk + l][j][i] = 0.0;
//
double grp_temp_A_v[NDIM];
double grp_temp_B_v[NDIM][3];
LOOP_n_N(NDIM){
grp_temp_A_v[n] = 0.0;
FOR_I3 grp_temp_B_v[n][i] = 0.0;
}
LOOP_n_N(NDIM) LOOP_m_N(ORDER) {
int idof1 = ORDER * mat_co1[NDIM*l + n] + m;
int idof2 = mat_Gr[ndof*n + ORDER*mat_co2[NDIM*l + n] + m ];
grp_temp_A_v[n] += mat_der_sol[idof1] * GsGm1*PrimSca[1][nk + idof2]/PrimSca[0][nk + idof2];
FOR_J3 grp_temp_B_v[n][j] += mat_der_sol[idof1] * PrimVec[0][nk + idof2][j];
}
LOOP_n_N(NDIM) {
FOR_I3 SoGrSca[0][nk + l][i] += Jaco_Sol[nk + l][n][i] * grp_temp_A_v[n];
FOR_J3 {
FOR_I3 SoGrVec[0][nk + l][j][i] += Jaco_Sol[nk + l][n][i] * grp_temp_B_v[n][j];
}
}
// Compare SoGrSca and SoGrVec...
//
// ERROR: they are different
Comparing algorithm is, given y_old and y_new,
( abs( y_old - y_new ) / ( abs(y_old) + z ) ) < epsilon // 'true' means equality
where z protects against zero division errors,
z=1e-10
and epsilon required to pass is huge, i.e. epsilon=0.2
While it should be closer to e.g. 1e-7
FUN EDIT: just another example of joining a project with already-well-established macros lol
| Floating point number arithmetic is not distributive. That means there are cases where the following statement is true
x * (a + b) != x * a + x * b;
If you move the multiplication out of your loop and expect the exact same result, you assume that the distributive law is always true, which it is not.
As an example I came up with this godbolt snippet.
|
72,226,792 | 72,226,948 | Why std::string relational operator comparison result is different for a template and a function? | In the following code, both the template and the function compare two strings and return which one is bigger. However, despite the same code (definition body), the result is different. Now, it might have something to do with taking a string vs string of characters (is it a C++ bug?) - but why is there a difference for a template though?
#include <iostream>
#include <string>
std::string getBiggerStr(std::string a, std::string b);
template <class T>
T getBigger(T a, T b);
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl;
std::cout << "\t" << getBigger("Amber", "John") << std::endl;
return 0;
}
std::string getBiggerStr(std::string a, std::string b) {
if(a > b) return a;
return b;
}
template <class T>
T getBigger(T a, T b) {
if(a > b) return a;
return b;
}
result:
John
Amber
Why is it different? Template definition body is copy pasted from function!
| The type of the arguments (and thus of the template parameter) in the getBigger("Amber", "John") function call is const char*. Thus, the comparison in that function just compares two pointers, which is not how to properly compare (lexicographically) two C-style strings.
In order to force the use of std::string as the argument/template type, you can append the operator ""s suffix to the literals:
using namespace std::string_literals;
int main() {
std::cout << "\t" << getBiggerStr("Amber", "John") << std::endl; // Automatic conversion to std::string
std::cout << "\t" << getBigger("Amber"s, "John"s) << std::endl; // Here, we need to explicitly specify
return 0;
}
Alternatively, if you don't have a C++14-compliant compiler (required for the operator ""s), then you can explicitly construct two std::string objects as the arguments:
std::cout << "\t" << getBigger(std::string{ "Amber" }, std::string{ "John" }) << std::endl;
|
72,227,208 | 72,227,528 | CGAL: Hole Filling .exe file is stuck | This is my terminal(result) after running the .exe file. Click the link for the terminal.
It doesn't stop or gives an error. It's stuck like this for hours.
I got my code from here code, but this is the data (.off) I used.
| You are probably trying to fill a hole that is too large or that cannot be filled using the 3D Delaunay triangulation search space (which can happen also if you have pinched holes). In CGAL 5.5 (not yet released but available in master), we added the option do_not_use_cubic_algorithm() (doc here) to not use the cubic search space to fill such holes.
|
72,227,314 | 72,346,923 | [UE4]error LNK2005 on linking libprotobuf | Having a small issue with conflicting libraries while packaging an Unreal Engine 4.27 project.
My project contains this gRPC library from google and I followed these steps to build it with CMake and after include it in my Unreal Project.
In addition my project requires enabling PixelStreaming plugin. However it seems that this plugin imported another version of protobuf which, on packaging is conflicting with the one included in gRPC.
The error is the following:
libprotobuf.lib(coded_stream.obj) : error LNK2005: "public: __cdecl google::protobuf::io::CodedOutputStream::CodedOutputStream(class google::protobuf::io::ZeroCopyOutputStream *,bool)" (??0CodedOutputStream@io@protobuf@google@@QEAA@PEAVZeroCopyOutputStream@123@_N@Z) already defined in webrtc.lib(coded_stream.obj)
appearing for different objs.
I came across similar issues as such but disabling gRPC is not a feasible solution for me.
Could anyone advise on how to "instruct" the built gRPC to use the existing protobuf library from Pixel Streaming plugin?
Which steps do I need to take to properly configure these conflicting libraries?
| What solved my issue was migrating to UE5.
Using the same steps with aforementioned grpc project, in UE5 new project. Having a libprotobuf.lib in ThirdPary folder within UE5 project the packaging process worked with no LINK conflicts. Not sure why UE packaging did not complain this time but what works, works!
|
72,227,738 | 72,227,841 | Cant cout item in container with std::any | This script
#include <iostream>
#include <unordered_map>
#include <any>
using namespace std;
int main() {
unordered_map<int, any> test;
test[5] = "Hey!";
cout << test[5];
return 0;
}
Why does it not work?
candidate function not viable: no known conversion from 'std::__ndk1::unordered_map<int, std::__ndk1::any, std::__ndk1::hash<int>, std::__ndk1::equal_to<int>, std::__ndk1::allocator<std::__ndk1::pair<const int, std::__ndk1::any> > >::mapped_type' (aka 'std::__ndk1::any') to 'const void *' for 1st argument; take the address of the argument with &
basic_ostream& operator<<(const void* __p);
Sorry if this sounds a little stupid
| Just add a any_cast to test[5]. The main reason for this cast, is to tell the compiler which overloaded function of << is to be called for test[5], << doesn't have any function defined for std::any. Hence, we told the compiler to call const char * or std::string overload function of <<.
Always, make sure that sizeof of allocation of test[n] must match the sizeof type-cast.
For an example:
sizeof(std::string) = 32 bytes
sizeof(const char *) = 8 bytes
That's why we first need to allocate test[5] using std::string("Hey!");, instead of just "Hey!".
But, sizeof(int *) is equal to sizeof(char *), if you did this, it can cause 3 problems:
segfault
undefined behavior
Exception: std::bad_any_cast
Fix
std::cout << std::any_cast<const char *>(test[5]);
or std::string
test[5] = std::string("Hey!");
std::cout << std::any_cast<std::string>(test[5]);
|
72,227,756 | 72,228,064 | Having problem Understanding fork() hierarchy tree | I have this Code that I can't understand. I understood the basics of fork() but I don't understand the Hierarchical tree for this process.
The code is like this:
main()
{
fork();
if(fork()){
printf("A");
}
else{
printf("B");
}
}
The output is A A B B. How does this happen? I get it why A is printed twice but why is B printed? How does the hierarchical tree work here?
| Okay lets "draw" the process tree created by this program (using P for parent process, and C for child process):
fork()
^
/ \
| |
P C
| |
/------------/ \------------\
| |
fork fork
^ ^
/ \ / \
| | | |
P C P C
| | | |
/-----/ \----\ /-----/ \----\
| | | |
printf("A") printf("B") printf("A") printf("B")
First there's a fork() without condition. That means the parent and child processes both continue on the same path through the program.
Then comes the second fork() call. Both the original parent and child does this fork. In the new fork, the new parent processes will have a non-zero return value, meaning the condition is true and they will print "A". The new child processes will have a zero return value, which is false and they will go on to print "B".
The exact order the processes will run is unspecified, and therefore the exact output will be unpredictable. But it will print "A" twice and "B" twice.
|
72,227,859 | 72,227,897 | How to call a function at periodic interval that takes in an object as argument in C++? | I want to execute a function at periodic interval that takes an object as argument.
I tried this answer: https://stackoverflow.com/a/72226772/13798537 that calls a function at periodic interval which takes an integer as argument, but I couldn't figure out how to call a function at periodic interval that takes an object as argument.
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <memory>
#include <atomic>
#include "window.h" // Contains the declaration of Window class
using cancel_token_t = std::atomic_bool;
template<typename Fnc>
void set_interval(Fnc fun, std::chrono::steady_clock::duration interval,
std::shared_ptr<cancel_token_t> cancel_token=nullptr)
{
std::thread([fun=std::move(fun), interval, tok=std::move(cancel_token)]()
{
while (!tok || !*tok) // Call until token becomes true (if it is set)
{
auto next = std::chrono::steady_clock::now() + interval;
fun();
std::this_thread::sleep_until(next);
}
}).detach();
}
void foo(Window &window)
{
// Do something with the window object
}
int main()
{
Window window;
using namespace std::chrono_literals;
auto cancel = std::make_shared<cancel_token_t>(false);
// Ordinary rules for lambda capture apply so be careful
// about lifetime if captured by reference.
set_interval([window]
{
foo(window);
}, 1000ms, cancel);
//set_interval([window]{foo(window);}, 1000ms); // Without token, runs until main exits.
std::this_thread::sleep_for(3s);
*cancel = true;
}
I get the following error when I compile:
'void foo(Window &)': cannot convert argument 1 from 'const Window' to 'Window &'
How can I achieve this?
Thanks.
| operator() of non-mutable lambda is const.
As you capture by copy, you cannot then mutate your captured "member".
You probably want to capture by reference instead:
set_interval([&window] { foo(window); }, 1000ms, cancel);
or if you really want copy, make the lambda mutable:
set_interval([window] mutable { foo(window); }, 1000ms, cancel);
|
72,227,898 | 72,228,011 | Passing and Returning a 2D array of unknown size in C++ | I want to pass and return a 2D array of unknown size but I donot know how to do it. I know how to only return array of unknown size only (array of pointers). I know how to pass array of unknown size(templates) , but passing and returning a 2D array of unknown size at the same time is not working for me. I have the following code
template<typename Value_t, size_t FirstDim, size_t SecondDim>
int** FooTakes2D_ArrayRef_to_Print(Value_t (&array2d)[FirstDim][SecondDim])
{
for(size_t i=0; i<FirstDim; ++i)
{
for(size_t j=0; j<SecondDim; ++j)
{
std::cout<<array2d[i][j]<<' ';
}
std::cout<<"\n";
}
return array2d;
}
int main()
{
double arr_d[][3]= { {1,2,3}, {4,5,6} };
int** arr=FooTakes2D_ArrayRef_to_Print(arr_d);
return 0;
}
| The problem is that the return type of your function is int** but you are returning array2d which decays to a double (*)[3] due to type decay. Thus, there is a mismatch in the specified return type of the function and the type you're actually returning.
To solve this you can either use std::vector or use the placeholder type auto as shown below:
template<typename Value_t, size_t FirstDim, size_t SecondDim>
//auto used here
auto FooTakes2D_ArrayRef_to_Print(Value_t (&array2d)[FirstDim][SecondDim]) -> decltype(array2d)
{
for(size_t i=0; i<FirstDim; ++i)
{
for(size_t j=0; j<SecondDim; ++j)
{
std::cout<<array2d[i][j]<<' ';
}
std::cout<<"\n";
}
return array2d;
}
int main()
{
double arr_d[][3]= { {1,2,3}, {4,5,6} };
//auto used here
auto arr=FooTakes2D_ArrayRef_to_Print(arr_d);
}
Working demo
|
72,227,992 | 72,232,113 | How does boost graph dijkstra_shortest_paths pick the shortest path when there are multiple shortest paths between a specific pair of nodes? | I have an unweighted, undirected network of around 50000 nodes, from this network I need to extract the shortest path between any pair of nodes. I used the dijkstra_shortest_paths function from the boost library and it worked fine. Later I realised that between a given pair of nodes A and B, there can be more than one shortest path. In this case, how does the Dijkstra function pick among these shortest paths? Is it dependent on the node ids or the order of how these nodes are stored in the memory?
I found a few questions asking about how to extract all of the shortest paths between two nodes as normally only one of them is extracted, for example this question and this question. However, I don't want to extract all of the shortest paths between two nodes. Instead, I want to know how exactly the very path returned by the function is picked up among other shortest paths that have the same length.
I tried to have a deeper look into the related source code within the boost library, but it seems it is too advanced for me and I got lost soon. Also, I couldn't find an answer by googling, so I ask here.
| The exact algorithm is documented:
DIJKSTRA(G, s, w)
for each vertex u in V (This loop is not run in dijkstra_shortest_paths_no_init)
d[u] := infinity
p[u] := u
color[u] := WHITE
end for
color[s] := GRAY
d[s] := 0
INSERT(Q, s)
while (Q != Ø)
u := EXTRACT-MIN(Q)
S := S U { u }
for each vertex v in Adj[u]
if (w(u,v) + d[u] < d[v])
d[v] := w(u,v) + d[u]
p[v] := u
if (color[v] = WHITE)
color[v] := GRAY
INSERT(Q, v)
else if (color[v] = GRAY)
DECREASE-KEY(Q, v)
else
...
end for
color[u] := BLACK
end while
return (d, p)
In the linked page it highlights where events happen.
It follows that the order in which vertices are discovered dictates your answer.
You can achieve other tie-breakers without modifying the graph by specifying a custom comparison (CompareFunction).
|
72,228,010 | 72,228,823 | Return a lambda from a lambda | I want to use a lambda to evaluate (switch-case) some conditions and return a lambda accordingly.
const auto lmb1 = []() {
printf("1\n");
};
const auto lmb2 = []() {
printf("2\n");
};
const auto select = [](auto const &ref) {
switch(ref) {
case 1: return lmb1;
case 2: return lmb2;
}
};
std::function foo = select(1);
foo();
Sadly things aren't working.
What I am doint wrong?
| The problem is that a lambda, by default, deduce (as an auto function) the returned type and in your lambda you return two different lambdas. Every lambda has a different type, so the compiler can't choose a type for the returned lambda
[](auto const &ref) {
switch(ref) {
case 1: return lmb1; // decltype(lmb1)
case 2: return lmb2; // != decltype(lmb2)
}
};
You can solve the problem in different ways.
You can explicit the lambda returned type, using a type that both lmb1 and lmb2 can be converted to (in this example, std::function<void()> or also void(*)()). When that type is available
// -----------------vvvvvvvvvvvvvvvvvvvvvvvv
[](auto const &ref) -> std::function<void()> {
switch(ref) {
case 1: return lmb1;
case 2: return lmb2;
}
};
You can explicitly convert the returned values to a common type. Again: when a common type is available
[](auto const &ref)
{
switch(ref) { // --V
case 1: return +lmb1; // with the '+', lmb1 is converted to a void(*)()
case 2: return +lmb2; // with the '+', lmb2 is converted to a void(*)()
} // --------------^
If the ref argument can be a template value, starting from c++20 you can define a template lambda and, using if constexpr, you can return different types from different lambdas. This works also when there isn't a common type (but require a compile-time known argument)
const auto selct = []<int REF>(std::integral_constant<int, REF>) {
if constexpr ( 1 == REF )
return lmb1;
else
return lmb2;
};
auto foo = selct(std::integral_constant<int, 1>{});
|
72,228,883 | 72,229,038 | can you help me to fix this code about bubble sort? | i am newbie, i don't know how to fix it?
i don't know how to call function void bubblesort
#include<iostream>
using namespace std;
void bubbleSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = n - 1; j > i; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
}
int main() {
int a[]={1,4,7,2,6,5,3,9,8,10};
bubbleSort(a[], sizeof(a));
for (size_t i=0;i<10;i++)
{
cout<< a[i];
}
}
| When you pass an array as an argument into a function, you simply pass it as if it were a variable. In this case, simply just a would do. This is because arrays "decay" into pointers so a is a "pointer" to your array.
In addition, I recommend dividing by the sizeof(a[0]) to get the full length as the sizeof function returns the size in bytes
bubbleSort(a, sizeof(a)/sizeof(a[0]));
|
72,229,332 | 72,229,448 | Left Join C++ MYSQL library | I'm trying to access "category" table with LEFT JOIN. I need to retrieve the field "name" in this table.
This is my code:
void Product::read(MYSQL *connection)
{
MYSQL_RES *result;
MYSQL_ROW row;
if(mysql_query(connection, "SELECT * FROM product LEFT JOIN category ON product.category=category.category_id"))
std::cout<<"Query failed!!"<<mysql_error(connection)<<std::endl;
else
result=mysql_store_result(connection);
if(result->row_count>0)
{
while(row=mysql_fetch_row(result))
{
std::cout<<"Name: "<<row[1]<<" Brand: "<<row[3]<<" Price: "<<row[4]<<" Category: "<<row[5]<<" Amount: "<<row[6]<<std::endl;
}
}
mysql_free_result(result);
}
And this is the result of the query:
Name: Oneplus Nord 2 5G Brand: Oneplus Price: 299.99 Category: 1 Amount: 3
Name: Acer Swift 3 Brand: Acer Price: 899.99 Category: 2 Amount: 5
Name: Bose SoundLink Revolve Brand: Bose Price: 100.23 Category: 1 Amount: 3
How can I show the name of the category?
| You can be more specific about what columns are you selecting and their order. Rather than * you can specify the table_name.column_name (or just column_name if you have no overlaps, or alias_name.column_name if you want to use aliases), so you could try something like:
SELECT product.name, product.brand, product.price, category.name, product.amount FROM product LEFT JOIN category ON product.category=category.category_id
I am assuming how columns are named.
This way the following code will be more predictable, because indices would be based on what you've written in select.
std::cout<<"Name: "<<row[1]<<" Brand: "<<row[3]<<" Price: "<<row[4]<<" Category: "<<row[5]<<" Amount: "<<row[6]<<std::endl;
|
72,229,562 | 72,268,206 | Compiling a JNI file with c++ postgresql in command prompt getting fatal error | Command executed:
g++ -I"C:\Program Files\Java\jdk-16.0.2\include" -I"C:\Program Files\Java\jdk-16.0.2\include\win32" -I"C:\Program Files\libpqxx\include\pqxx" -shared -o hello.dll HelloJNI.cpp
pqxx file dir - C:\Program Files\libpqxx\include
I have included the path with -I .
I am using C++ for the backend connection for my Java program using JNI and unable to compile the cpp file, getting error as:
HelloJNI.cpp:4:10: fatal error: pqxx/pqxx: No such file or director
4 | #include <pqxx/pqxx>
| ^~~~~~~~~~~
compilation terminated.
The executed code is:
#include <jni.h> // JNI header provided by JDK
#include <iostream> // C++ standard IO header
#include "HelloJNI.h" // Generated
#include <pqxx/pqxx>
#include <string>
using namespace std;
// Implementation of the native method sayHello()
JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj)
{
try
{
std::string connectionString = "host=localhost port=5432 dbname=postgres user=postgres password =caNarain@2002";
pqxx::connection connectionObject(connectionString.c_str());
pqxx::work worker(connectionObject);
pqxx::result response = worker.exec("SELECT * FROM books ORDER BY BOOK_ID");
for (size_t i = 0; i < response.size(); i++)
{
std::cout << response[i][0] << " " << response[i][1] << " " << response[i][2] << " " << response[i][3] << " " << response[i][4] << " " << response[i][5] << std::endl;
}
return;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
system("pause");
}
| Compile the file in visual studio.
Add the paths to the respective fields like additional include directories, linker files in the property.
conclude the JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj)
inside a int main() method to compile since visual studio cannot compile the files without main method.
you can follow same as cmdline if your program doesn't have postgresql.
|
72,230,142 | 72,231,029 | How to find the center and radius of an any dimensional sphere giving dims+1 points | given a vector of N-dimensional points. The vector will be of size N+1.
Is there a generalized algorithm to find the center and radius of the ND sphere using those points where the sphere intersects every single one of those points?
| The same question has been asked on the mathematics stackexchange and has received a constructive answer:
Does a set of n+1 points that affinely span R^n lie on a unique (n-1)-sphere?
Here is an implementation in python/numpy of the algorithm described at that answer.
import numpy as np
def find_sphere_through_points(points):
n_points, n_dim = points.shape
if (n_points != n_dim + 1):
raise ValueError('Number of points must be equal to 1 + dimension')
a = np.concatenate((points, np.ones((n_points, 1))), axis=1)
b = (points**2).sum(axis=1)
x = np.linalg.solve(a, b)
center = x[:-1] / 2
radius = x[-1] + center@center
return center, radius
To test this method, we can generate random points on the surface of a sphere, using the method described in this related question:
Generate a random sample of points distributed on the surface of a unit spher
import numpy as np
def sample_spherical(npoints, ndim=3, center=None):
vec = np.random.randn(npoints, ndim)
vec /= np.linalg.norm(vec, axis=1).reshape(npoints,1)
if center is None:
return vec
else:
return vec + center
n = 5
center = np.random.rand(n)
points = sample_spherical(n+1, ndim=n, center=center)
guessed_center, guessed_radius = find_sphere_through_points(points)
print('True center:\n ', center)
print('Calc center:\n ', guessed_center)
print('True radius:\n ', 1.0)
print('Calc radius:\n ', guessed_radius)
# True center:
# [0.18150032 0.94979547 0.07719378 0.26561175 0.37509931]
# Calc center:
# [0.18150032 0.94979547 0.07719378 0.26561175 0.37509931]
# True radius:
# 1.0
# Calc radius:
# 0.9999999999999997
|
72,230,186 | 74,203,195 | clang-14: warning: cannot compress debug sections (zlib not installed) [-Wdebug-compression-unavailable] while using address sanitizer | I have a sample C++ program that would cause an obvious segmentation fault.
test.cxx:
int main()
{
int* ptr{nullptr};
*ptr = 3;
}
So I am using address sanitizer to debug it:
metal888@ThinkPad:~$ clang++ -g -fsanitize=address -fno-omit-frame-pointer -gz=zlib test.cxx -o vimbin && ./vimbin
clang-14: warning: cannot compress debug sections (zlib not installed) [-Wdebug-compression-unavailable]
AddressSanitizer:DEADLYSIGNAL
=================================================================
==42036==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x0000004dbeb1 bp 0x7ffd802e9310 sp 0x7ffd802e92f0 T0)
==42036==The signal is caused by a WRITE memory access.
==42036==Hint: address points to the zero page.
error: failed to decompress '.debug_aranges', zlib is not available
error: failed to decompress '.debug_info', zlib is not available
error: failed to decompress '.debug_abbrev', zlib is not available
error: failed to decompress '.debug_line', zlib is not available
error: failed to decompress '.debug_str', zlib is not available
error: failed to decompress '.debug_addr', zlib is not available
error: failed to decompress '.debug_line_str', zlib is not available
error: failed to decompress '.debug_rnglists', zlib is not available
error: failed to decompress '.debug_str_offsets', zlib is not available
error: failed to decompress '.debug_aranges', zlib is not available
error: failed to decompress '.debug_info', zlib is not available
error: failed to decompress '.debug_abbrev', zlib is not available
error: failed to decompress '.debug_line', zlib is not available
error: failed to decompress '.debug_str', zlib is not available
error: failed to decompress '.debug_loc', zlib is not available
error: failed to decompress '.debug_ranges', zlib is not available
#0 0x4dbeb1 in main (/home/metal888/vimbin+0x4dbeb1)
#1 0x7f5165493082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee)
#2 0x41c30d in _start (/home/metal888/vimbin+0x41c30d)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (/home/metal888/vimbin+0x4dbeb1) in main
==42036==ABORTING
So it says zlib is not installed. So I tried to install zlib. It produces this result:
metal888@ThinkPad:~$ sudo apt install zlib1g zlib1g-dev
Reading package lists... Done
Building dependency tree
Reading state information... Done
zlib1g is already the newest version (1:1.2.11.dfsg-2ubuntu1.3).
zlib1g-dev is already the newest version (1:1.2.11.dfsg-2ubuntu1.3).
0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.
So that means zlib is actually installed but clang cannot find it. This is my clang version:
metal888@ThinkPad:~$ clang --version
clang version 14.0.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /opt/clang14/bin
So how can I tell clang how and where to find zlib? I installed clang by downloading binary release of clang-14 from llvm-releases.
Note that the zlib related errors don't occur if I use g++ instead of clang++.
metal888@ThinkPad:~$ g++ -g -fsanitize=address -fno-omit-frame-pointer -gz=zlib test.cxx -o vimbin && ./vimbin
AddressSanitizer:DEADLYSIGNAL
=================================================================
==44183==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5601ea2f41d8 bp 0x7ffc8f97d9d0 sp 0x7ffc8f97d9c0 T0)
==44183==The signal is caused by a WRITE memory access.
==44183==Hint: address points to the zero page.
#0 0x5601ea2f41d7 in main /home/metal888/test.cxx:4
#1 0x7fb073a17082 in __libc_start_main ../csu/libc-start.c:308
#2 0x5601ea2f40cd in _start (/home/metal888/vimbin+0x10cd)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /home/metal888/test.cxx:4 in main
==44183==ABORTING
| What I found out is that the prebuilt versions of clang-14 (and versions that came later) that's found in the LLVM download page are not built properly. The -g compiler flag doesn't include any debug symbols in the binary. And sanitizer needs debug symbols to work. That's why I was getting those errors. So you have 3 options left if you want to use the latest clang release that works perfectly.
Download clang+llvm-13.0.0 if you are on ubuntu 20.04. This one works just fine.
Build LLVM and clang (and lldb etc etc, all that you find necessary) in your machine yourself like I did.
Install clang from the official package repository. Although currently clang-12 is the most latest one that's available.
|
72,230,284 | 72,230,452 | Different values for integer | Trying to insert values of square and cube of a number in set st and st1. (Let n = 10^7).
After printing, set st is having negative values due to limit of integer but there are no negative values in set st1 even though both 'i' and 'temp' are integers.
int n;
cin >> n;
int temp = 2;
set<int> st;
set<int> st1;
while ((temp * temp) < n)
{
st.insert(temp * temp);
if ((temp * temp * temp) < n)
{
st.insert(temp * temp * temp);
}
temp++;
}
for(int i=1;i*i<n;i++){
st1.insert(i * i);
}
for(int i=1;i*i*i<n;i++){
st1.insert(i* i * i);
}
for(auto ss : st){
cout<<ss<<" ";
}
cout<<"\n\n";
for(auto s : st1){
cout<<s<<" ";
}
}
| The behaviour of temp * temp < n is undefined if temp * temp overflows the type. Wraparound to negative is commonly observed but even with architectures that do that, optimising compilers are permitted to assume that if a + c < b + c for a constant c then a < b.
temp < n / temp is a common refactoring that does not suffer from that overflow. You do of course need to check for non-zero temp.
|
72,230,477 | 72,251,972 | Visible order of operations with acquire/release fence in C++ | I have a following program which uses std::atomic_thread_fences:
int data1 = 0;
std::atomic<int> data2 = 0;
std::atomic<int> state;
int main() {
state.store(0);
data1 = 0;
data2 = 0;
std::thread t1([&]{
data1 = 1;
state.store(1, std::memory_order_release);
});
std::thread t2([&]{
auto s = state.load(std::memory_order_relaxed);
if (s != 1) return;
std::atomic_thread_fence(std::memory_order_acquire);
data2.store(data1, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
state.store(2, std::memory_order_relaxed);
});
std::thread t3([&]{
auto d = data2.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (state.load(std::memory_order_relaxed) == 0) {
std::cout << d;
}
});
t1.join();
t2.join();
t3.join();
}
It consists of 3 threads and one global atomic variable state used for synchronization. First thread writes some data to a global, non-atomic variable data1 and sets state to 1. Second thread reads state and if it's equal to 1 it modifies assigns data1 to another global non-atomic variable data2. After that, it stores 2 into state. This thread reads the content of data2 and then checks state.
Q: Will the third thread always print 0? Or is it possible for the third thread to see update to data2 before update to state? If so, is the only solution to guarantee that to use seq_cst memory order?
| I think that t3 can print 1.
I believe the basic issue is that the release fence in t2 is misplaced. It is supposed to be sequenced before the store that is to be "upgraded" to release, so that all earlier loads and stores become visible before the later store does. Here, it has the effect of "upgrading" the state.store(2). But that is not helpful because nobody is trying to use the condition state.load() == 2 to order anything. So the release fence in t2 doesn't synchronize with the acquire fence in t3. Therefore you do not get any stores to happen-before any of the loads in t3, so you get no assurance at all about what values they might return.
The fence really ought to go before data2.store(data1), and then it should work. You would be assured that anyone who observes that store will thereafter observe all prior stores. That would include t1's state.store(1) which is ordered earlier because of the release/acquire pair between t1 and t2.
So if you change t2 to
auto s = state.load(std::memory_order_relaxed);
if (s != 1) return;
std::atomic_thread_fence(std::memory_order_acquire);
std::atomic_thread_fence(std::memory_order_release); // moved
data2.store(data1, std::memory_order_relaxed);
state.store(2, std::memory_order_relaxed); // irrelevant
then whenever data2.load() in t3 returns 1, the release fence in t2 synchronizes with the acquire fence in t3 (see C++20 atomics.fences p2). The t2 store to data2 only happened if the t2 load of state returned 1, which would ensure that the release store in t1 synchronizes with the acquire fence in t2 (atomics.fences p4). We then have
t1 state.store(1)
synchronizes with
t2 acquire fence
sequenced before
t2 release fence
synchronizes with
t3 acquire fence
sequenced before
t3 state.load()
so that state.store(1) happens before state.load(), and thus state.load() cannot return 0 in this case. This would ensure the desired ordering without requiring seq_cst.
To imagine how the original code could actually fail, think about something like POWER, where certain sets of cores get special early access to snoop stores from each others' store buffers, before they hit L1 cache and become globally visible. Then an acquire barrier just has to wait until all earlier loads are complete; while a release barrier should drain not only its own store buffer, but also all other store buffers that it has access to.
So suppose core1 and core2 are such a special pair, but core3 is further away and only gets to see stores after they are written to L1 cache. We could have:
core1 core2 L1 cache core3
===== ===== ======== =====
data1 <- 1
release data1 <- 1
state <- 1
(still in store buffer)
1 <- state
acquire
1 <- data1
data2 <- 1 data2 <- 1
1 <- data2
acquire
0 <- state
release state <- 1
state <- 2 state <- 2
The release barrier in core 2 does cause the store buffer of core 1 to drain and thus write state <- 1 to L1 cache, but by then it is too late.
|
72,231,235 | 72,231,511 | c++ queue implementation not working as expected | Today I am looking to make my own dequeue in c ++ using pointers. Well, in the program, I want to create two dequeues in which to add different elements. Unfortunately, this is not what happened. On screen i got 6 5 insted only 6. Why?I'm not sure exactly how to make two separate dequeues? I think one of my problems are *L = NULL, * R = NULL but i am not sure?
So my code so far -
#include <iostream>
struct elem
{
int key;
elem* next;
}*L = NULL, * R = NULL;
void push_l(int n, elem*& p)
{
p = L;
L = new elem;
L->key = n;
L->next = p;
if (R == NULL)
R = L;
}
int pop_l(int& n, elem*& p)
{
if (L)
{
p = L;
n = L->key;
L = L->next;
if (L == NULL)
R = NULL;
delete p;
return 1;
}
else
{
return 0;
}
}
int main()
{
int k;
elem* p = new elem;
elem* q = new elem;
push_l(5, p);
push_l(6, q);
while (pop_l(k, q))
{
std::cout << k<< " ";
}
}
I am not sure how can i print only 6 on the screen because this element is only pushed to the dequeue ? Also these are just some of the features for dequeue because I want to understand it from the beginning !
| Such a class might look like this:
class /* or struct, if you really want to... */ Dequeue
{
public:
void push(int value);
bool pop(int& value); // if you return 1 for success and 0 for error
// bool is the more appropriate type...
private:
struct elem // it's an implementation detail, so recommendable
// to have it as a nested class...
{
// just as you had before...
// you might additionally provide a constructor:
// this makes creating new instances easier/simpler
elem(int k, elem* n) : key(k), next(n) { }
};
elem* m_head = nullptr;
elem* m_tail = nullptr;
}
void Dequeue::push(int value)
{
// auto tmp = new elem;
// tmp->key = value;
// tmp->next = m_head;
// m_head = tmp;
// with constructor:
m_head = new elem(value, m_head);
if(!m_tail)
m_tail = m_head;
}
bool Dequeue::pop(int& value)
{
// transform analogously using m_head and m_tail instead of L and R
// return true and false instead of 1 and 0
}
You'll notice that the function looks just as before – however as now a member function, it accesses the class member of the instance upon which the function is called:
Dequeue d1;
Dequeue d2;
// each of these have their own, separate m_head and m_tail pointers!
d1.push(12);
d2.push(10);
// now pushed to separate instances
Side note: untested code, if you find a bug, please fix yourself...
|
72,232,083 | 72,232,154 | Holder class (Having some objects references) compile error: 'Can not be referenced -- it is a deletted funciton' | I need a "holder" class. It is supposed to store objects references.
Like: holder.A = a; // Gets a reference!
Sample code bellow including the compiler error:
class A
{
};
class Holder
{
public:
A& MyA; // I want to store a reference.
};
int main()
{
A testA;
Holder holder; // Compiler error: the default constructor of "Holder" cannot be referenced -- it is a deleted function
holder.A = testA; // I was hopping to get testA reference.
}
| The problem is that since your class Holder has a reference data member MyA, its default constructor Holder::Holder() will be implicitly deleted.
This can be seen from Deleted implicitly-declared default constructor that says:
The implicitly-declared or defaulted (since C++11) default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:
T has a member of reference type without a default initializer (since C++11).
(emphasis mine)
To solve this you can provide a constructor to initialize the reference data member MyA as shown below:
class A
{
};
class Holder
{
public:
A& MyA;
//provide constructor that initialize the MyA in the constructor initializer list
Holder( A& a): MyA(a)//added this ctor
{
}
};
int main()
{
A testA;
Holder holder(testA); //pass testA
}
Working Demo
|
72,232,317 | 72,233,089 | C++ change parent class based on option | There is a Student class inherited from Person.
And there is Student class inherited from University.
I want to change the parent class Person, University based on the option without rewriting Student such as Student1 and Student2 (because student class is very complicated).
Here is the example code.
class Person {
void f() {printf("I'm person")}
};
class University {
void f() {printf("I'm university")}
};
class Student1 : public Person {
void g() {f()}
};
class Student2 : public University {
void g() {f()} // I don't wan't to rewrite this!
};
if (option.person) {
Student1 student;
}
else {
Student2 student;
}
| Since we can't know what option.person is at compile-time, we need to find a way to work around that at runtime.
One option for doing so is std::variant, which can store any number of different types; but does so at the cost of always having the same size as the largest templated type.
As an example, if I did this:
std::variant<char, int> myVariant = '!';
Even though myVariant holds a char (1 byte), it uses 4 bytes of RAM because an int is 4 bytes.
Using Variants
Rather than inheriting from different objects that do not share a common base at compile-time, we can maintain the 'base' type as a variable within Student instead.
#include <iostream>
#include <variant>
#include <concepts>
class Person {
public:
void f()
{
std::cout << "I'm a person!\n";
}
};
class University {
public:
void f()
{
std::cout << "I'm a university!\n";
}
};
class Student {
public:
using variant_t = std::variant<Person, University>;
variant_t base;
// Here we accept an rvalue of any type, then we move it to the 'base' variable.
// if the type is not a Person or University, a compiler error is thrown.
Student(auto&& owner) : base{ std::move(owner) } {}
void g()
{
// METHOD 1: Using std::holds_alternative & std::get
// This has the advantage of being the simplest & easiest to understand.
if (std::holds_alternative<Person>(base))
std::get<Person>(base).f();
else if (std::holds_alternative<University>(base))
std::get<University>(base).f();
// METHOD 2: Using std::get_if
// This has the advantage of being the shortest.
if (auto* person = std::get_if<Person>(&base))
person->f();
else if (auto* university = std::get_if<University>(&base))
university->f();
// METHOD 3: Using std::visit
// This has the advantage of throwing a meaningful compiler error if-
// -we modify `variant_t` and end up passing an unhandled type.
std::visit([](auto&& owner) {
using T = std::decay_t<decltype(owner)>;
if constexpr (std::same_as<T, Person>)
owner.f(); //< this calls `Person::f()`
else if constexpr (std::same_as<T, University>)
owner.f(); //< this calls `University::f()`
else static_assert(false, "Not all potential variant types are handled!");
}, base);
}
};
In this example, I showed 3 different methods of accessing the underlying value of base.
As a result, the output is:
Further reading:
std::variant
std::get
std::get_if
std::visit
|
72,232,384 | 72,232,486 | Parameter pack iteration | Why this code doesn't compile ?
#include <iostream>
#include <typeinfo>
template <typename ...Ts>
void f();
template <typename T>
void f() {
std::cout << typeid(T).name() << std::endl;
}
template <typename T, typename U, typename ...Ts>
void f() {
std::cout << typeid(T).name() << ", ";
f<U, Ts...>();
}
int main(int argc, char** argv)
{
f<int, float, char>();
}
MSVC compiler error:
error C2668: 'f': ambiguous call to overloaded function
Expected output:
int, float, char
Side question: would there be a more modern way to do the same thing ?
EDIT
I've found a way to accept zero template pack:
#include <typeinfo>
#include <iostream>
#include <type_traits>
template <typename ...Ts>
using is_empty_pack = std::enable_if_t<sizeof ...(Ts) == 0>;
template <typename ...Ts, typename = is_empty_pack<Ts...>>
void f() {}
template <typename T, typename ...Ts>
void f() {
std::cout << typeid(T).name();
if constexpr (sizeof ...(Ts) > 0) std::cout << ", "; else std::cout << std::endl;
f<Ts...>();
}
int main(int argc, char *argv[])
{
f<>();
f<int>();
f<int, float>();
}
Any other suggestion?
| Compiling with g++ gives a pretty clear explanation of what's happening:
prog.cc: In function 'int main(int, char**)':
prog.cc:20:24: error: call of overloaded 'f<int, float, char>()' is ambiguous
20 | f<int, float, char>();
| ~~~~~~~~~~~~~~~~~~~^~
prog.cc:5:6: note: candidate: 'void f() [with Ts = {int, float, char}]'
5 | void f();
| ^
prog.cc:13:6: note: candidate: 'void f() [with T = int; U = float; Ts = {char}]'
13 | void f() {
You've provided three different templated functions f, two of which could match what you've written here.
EDIT: Maybe you thought the first one was a declaration and the other two are specializations, but that's not how templates work. Specialization means specializing the type or value of a particular template argument, not specializing the number of template arguments.
Deleting
template <typename ...Ts>
void f();
will make the program compile and run with the expected behavior.
|
72,232,396 | 72,232,569 | Is it possible to determine if a pointer points to a valid object, and if so how? | I was reading C++ Is it possible to determine whether a pointer points to a valid object? and the correct answer in this thread is that no, you can't do that, but the thread is quite old now and I wanted to know if anything has changed. I read that with smart pointers that would be possible. So how could that be achieved?
|
Is it possible to determine if a pointer points to a valid object
No, it isn't generally possible to determine whether a pointer points to a valid object.
I wanted to know if anything has changed
Nothing has changed in this regard.
I read that with smart pointers that would be possible. So how could that be achieved?
Unless you misuse it in a bad way, a smart pointer is never invalid. As such, there is no need to check whether it is valid or not. It should either be null or point to a valid object.
Weak pointer is a special kind of smart pointer that doesn't own an object directly, but it points to an object owned by shared pointer(s). The pointed object may be destroyed when no shared pointer points to it anymore. It's possible to ask the weak pointer whether that has happened or not. This state is somewhat analogous to being invalid, except the state is verifiable.
So how could that be achieved?
You can std::make_unique or std::make_shared to create a dynamic object owned by a smart pointer. The choice between them depends on what kind of ownership you need: unique or shared. Weak pointers can be created only from shared pointers.
|
72,232,484 | 72,233,716 | C++ - Reading a line without getline | I am trying to read user entered data from the stream and then store it in a custom String class.
To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class.
My code looks like this:
String street();
std::cout << "Street: "; std::cin >> std::noskipws;
char c='\0';
while(c!='\n'){
std::cin >> c;
street=street+c;
}std::cin >> std::skipws;
int bal=0;
std::cout << "Balance: "; std::cin >> bal;
|
To my best knowledge, std::getline() can route data only to std::string , that is why I need to come up with something else, as my project is not allowed to use std::string class.
Note that std::getline and std::istream::getline are two separate functions. The former will work with std::string while the latter will work with C-style strings (i.e. sequences of characters that are terminated by a null character).
Therefore, if you are not allowed to use std::string, then you can still use std::istream::getline, for example like this:
char line[200];
String street;
std::cout << "Street: ";
if ( std::cin.getline( line, sizeof line ) )
{
//the array "line" now contains the input, and can be assigned
//to the custom String class
street = line;
}
else
{
//handle the error
}
This code assumes that your custom class String has defined the copy assignment operator for C-style strings.
If it is possible that the lines will be larger than a fixed number of characters and you want to support such lines, then you could also call std::istream::getline in a loop:
char line[200];
String street;
std::cout << "Street: ";
for (;;)
{
std::cin.getline( line, sizeof line );
street += line;
if ( std::cin.bad() )
{
//TODO: handle error and break loop, for example by
//throwing an exception
}
if ( !std::cin.fail() || std::cin.eof() )
break;
std::cin.clear();
}
This code assumes that operator += is defined for class String.
This loop will continue forever until
getline succeeds (i.e. it is able to extract (but not store) the newline character), or
end-of-file is reached (eofbit is set), or
an error occurs (badbit is set).
|
72,232,792 | 72,238,950 | Covariant return type on Eigen Matrix for base class method | Suppose that I have two different solvers that both will be called at run time.
I want to call solvers' api and get resulted Eigen matrix through the base class pointer.
The solved matrix size are selected from a few known values depending on some runtime variable. I need to use compiled time fixed size matrix in this case.
The solver derived class definitions are as follow.
template <int VarSize>
class SolverA : Solver {
public:
SolverA() {}
bool Solve() override {
// SolverA specific implementations.
}
const Eigen::Matrix<double, VarSize, 1>& solution() override {
return solution_;
}
private:
Eigen::Matrix<double, VarSize, 1> solution_;
}
template <int VarSize>
class SolverB : Solver {
public:
SolverB() {}
bool Solve() override {
// SolverB specific implementations.
}
const Eigen::Matrix<double, VarSize, 1>& solution() override {
return solution_;
}
private:
Eigen::Matrix<double, VarSize, 1> solution_;
}
Now the problem is how I can write the base class solution() method to get the resulted Eigen matrix, since the template parameter VarSize are not known in the base declaration.
class Solver {
public:
virtual bool Solve() = 0;
// not covariant type, won't compile.
// virtual const Eigen::VectorXd& solution() = 0;
}
constexpr int kEasyProbSize = 5;
constexpr int kHardProbSize = 20;
int main() {
Solver* solver;
if (GetComplexity() > 30) {
solver = &SolverB<kHardProbSize>();
} else {
solver = &SolverA<kEasyProbSize>();
}
solver->Solve();
std::cout << solver->solution() << std::endl;
}
Some thoughts:
Eigen::Matrix<double, VarSize, 1> does not derive from Eigen::VectorXd so it cannot override.
I also cannot use const Eigen::MatrixBase<Derived>& since there is no that derived information and virtual method won't allow template.
I need to call from base class pointer so I cannot make the base class a template class.
The solved solution_ is already allocated and doesn't make sense to return a copy or converted to a dynamic size matrix.
Is this fixed size matrix getting from base class pointer even possible?
| The easiest solution would be to just store a VectorXd solution_; inside Solver itself. But if you insist on storing the actual solution vector only in the derived classes, you can have solution() return an Eigen::Ref<const Eigen::VectorXd> which can be created with just moving a pointer and a few integers:
class Solver {
public:
virtual bool Solve() = 0;
// not covariant type, won't compile.
using VecRef = Eigen::Ref<const Eigen::VectorXd> const;
virtual VecRef solution() = 0;
};
template <int VarSize>
class SolverA : public Solver {
public:
SolverA() {}
bool Solve() override {
// SolverA specific implementations.
return true;
}
Solver::VecRef solution() override {
return solution_;
}
private:
Eigen::Matrix<double, VarSize, 1> solution_;
};
template <int VarSize>
class SolverB : public Solver {
public:
SolverB() {}
bool Solve() override {
// SolverB specific implementations.
return true;
}
VecRef solution() override {
return solution_;
}
private:
Eigen::Matrix<double, VarSize, 1> solution_;
};
Godbolt demo: https://godbolt.org/z/MqaofsoK9
|
72,233,035 | 72,233,722 | Get temp path with file name | I want to get path to file like this > %ENV%/%FILE_NAME%.docx
But c++ doesn't make sense at all and nothing works..
I would use std::string but it's not compatible so I tried multiple ways of converting it to char[] or char* but none of them works and I'm also pretty sure this is unsafe..
My code so far (I know it's the worst code ever..)
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len + 2];
strcpy(ret, array);
ret[len] = a;
ret[len + 1] = '\0';
return ret;
}
const char* getBaseName(std::string path)
{
std::string base_filename = path.substr(path.find_last_of("/\\") + 1);
std::string::size_type const p(base_filename.find_last_of('.'));
std::string file_without_extension = base_filename.substr(0, p);
return file_without_extension.c_str();
}
int main()
{
char szExeFileName[MAX_PATH];
GetModuleFileName(NULL, szExeFileName, MAX_PATH);
const char* file_name = getBaseName(std::string(szExeFileName));
char* new_file = getenv("temp");
new_file = appendCharToCharArray(new_file, '\\');
for (int i=0;i<sizeof(file_name)/sizeof(file_name[0]);i++)
{
new_file = appendCharToCharArray(new_file, file_name[i]);
}
new_file = appendCharToCharArray(new_file, '.');
new_file = appendCharToCharArray(new_file, 'd');
new_file = appendCharToCharArray(new_file, 'o');
new_file = appendCharToCharArray(new_file, 'c');
new_file = appendCharToCharArray(new_file, 'x');
std::cout << new_file << std::endl;
}
| Using appendCharToCharArray() is just horribly inefficient in general, and also you are leaking lots of memory with the way you are using it. Just use std::string instead. And yes, you can use std::string in this code, it is perfectly "compatible" if you use it correctly.
getBaseName() is returning a char* pointer to the data of a local std::string variable that goes out of scope when the function exits, thus a dangling pointer is returned. Again, use std::string instead.
And, you should use the Win32 GetTempPath/2() function instead of getenv("temp").
Try something more like this:
#include <iostream>
#include <string>
std::string getBaseName(const std::string &path)
{
std::string base_filename = path.substr(path.find_last_of("/\\") + 1);
std::string::size_type const p(base_filename.find_last_of('.'));
std::string file_without_extension = base_filename.substr(0, p);
return file_without_extension;
}
int main()
{
char szExeFileName[MAX_PATH] = {};
GetModuleFileNameA(NULL, szExeFileName, MAX_PATH);
char szTempFolder[MAX_PATH] = {};
GetTempPathA(MAX_PATH, szTempFolder);
std::string new_file = std::string(szTempFolder) + getBaseName(szExeFileName) + ".docx";
std::cout << new_file << std::endl;
}
Online Demo
That being said, the Win32 Shell API has functions for manipulating path strings, eg:
#include <iostream>
#include <string>
#include <windows.h>
#include <shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
int main()
{
char szExeFileName[MAX_PATH] = {};
GetModuleFileNameA(NULL, szExeFileName, MAX_PATH);
char szTempFolder[MAX_PATH] = {};
GetTempPathA(MAX_PATH, szTempFolder);
char new_file[MAX_PATH] = {};
PathCombineA(new_file, szTempFolder, PathFindFileNameA(szExeFileName));
PathRenameExtensionA(new_file, ".docx");
std::cout << new_file << std::endl;
}
Or, if you are using C++17 or later, consider using std::filesystem::path instead, eg:
#include <iostream>
#include <filesystem>
#include <windows.h>
namespace fs = std::filesystem;
int main()
{
char szExeFileName[MAX_PATH] = {};
GetModuleFileNameA(NULL, szExeFileName, MAX_PATH);
char szTempFolder[MAX_PATH] = {};
GetTempPathA(MAX_PATH, szTempFolder);
fs::path new_file = fs::path(szTempFolder) / fs::path(szExeFileName).stem();
new_file += ".docx";
// alternatively:
// fs::path new_file = fs::path(szTempFolder) / fs::path(szExeFileName).filename();
// new_file.replace_extension(".docx");
std::cout << new_file << std::endl;
}
Online Demo
|
72,233,118 | 72,233,251 | C++ unpack variadic template arguments with the next function returns nothing | I'm trying to expand arguments to a variadic function. Code below works perfectly fine
template<typename T>
int printMy (const T& f)
{
cout << f << endl;
}
template<typename... Types>
void print (Types... args)
{
auto i = {printMy(args)...};
}
int main() {
std::string s("world");
print(7.5, "hello", s);
return 0;
}
However, I don't really want to return anything from the function. I actually want it to be void. However, when I have code like below, it doesn't work
template<typename T>
void printMy (const T& f)
{
cout << f << endl;
}
template<typename... Types>
void print (Types... args)
{
{printMy(args)...};
// same thing if I remove the brackets
// printMy(args)...;
}
It gives me an error on the line "{printMy(args)...};". The error is "Expression contains unexpanded parameter pack 'args'"
| You can use fold expression with C++17 to compute the result of using a binary operator over all the arguments of the parameter pack, to solve the problem as shown below. The shown program uses unary right fold to achieve the desired effect.
template<typename... Types>
void print (Types... args)
{
(printMy(args), ...);//uses fold expression in C++17
}
Demo
|
72,233,203 | 72,233,250 | Should you always put join() after launching a thread? | I wonder if there is any advantage putting join() not immediately after launching a thread?
std::thread t(func);
// some code ...
t.join();
does it give you any advantage or it's always preferable to use it after a thread launch?
std::thread t(func);
t.join();
// some code ...
| If you use join() right after starting the new thread then it will block (wait) execution on the join() call until the new thread is finished running (defeating the whole purpose of the parallelization you get from starting the new thread). Therefore, if you want to execute "some code" on the main thread while thread t is executing, join() should come after "some code".
|
72,233,769 | 72,233,809 | Is there a way to find exact location ( adress ) of file on disk? | I'm developing a software using C++ for Windows/Linux.
I want to create a file (txt, json, license, you name it) at runtime, and save it somewhere. Is it possible in C++ to get the exact position of that file on disk, so that if I restart the app and read that address (or other), I'll be able to access its data?
The purpose of this would be that if someone copied the software to another OS, or created an image of the OS, and tried to run it, the address would not be valid anymore and it would fail. This is an attempt to add another layer (on top of license management) to protect against software copy.
| An image of a disk copies it byte by byte, meaning that all addresses (locations) on disk stay exactly the same. So your copy protection won't actually work - you can still easily clone the disk while preserving your special copy protection file. Additionally, a file may not even have a defined location on disk: It may be split up into many fragments and scattered across the entire disk. You can't find an address that doesn't exist. The filesystem may also just move the file around whenever it feels like it so the address doesn't stay the same even on the same system. (This is what defragmentation does. Windows, for example, moves files around like that on a fixed schedule to make the filesystem faster.)
TL;DR this is not going to work.
|
72,234,002 | 72,234,106 | cannot convert 'LinkedList::filter(void (*)(Node*))::<lambda(Node*)>' to 'void (*)(Node*)' | Im trying to implement a simple LinkedList class, but this error shows up and I don't understand why.
struct Node {
public:
int val;
Node* next;
Node(int v) : val(v), next(nullptr) {}
};
struct LinkedList {
public:
Node* head;
Node* tail;
LinkedList() : head(nullptr), tail(nullptr) {}
void append(int value) {
Node* new_node = new Node(value);
if (head == nullptr) {
head = new_node;
tail = new_node;
} else {
tail->next = new_node;
tail = new_node;
}
}
void traverse(void (*callback)(Node* node)) {
Node* cur = head;
while (cur != nullptr) {
callback(cur);
cur = cur->next;
}
}
LinkedList filter(bool (*filter_function)(Node* node)) {
LinkedList new_list = LinkedList();
traverse([&](Node* node) { if(filter_function(node)) new_list.append(node->val); });
return new_list;
}
};
error is in this line
traverse([&](Node* node) { if(filter_function(node)) new_list.append(node->val); });
cannot convert 'LinkedList::filter(void (*)(Node*))::<lambda(Node*)>' to 'void (*)(Node*)'
| As mentioned in the comments, a capturing lambda is not the same as a function pointer. Instead, behind the scenes, it is a fully-fledged object (because it has state).
Fortunately, there's an easy fix - you can use the magical powers of std::function to abstract away all the messy details. To do this, all you have to do is #include <functional> and change this:
void traverse(void (*callback)(Node* node)) {
to this:
void traverse (std::function <void (Node* node)> callback) {
and you are golden.
|
72,234,300 | 72,234,423 | What is differnece between CreateWindowEx, CreateWindowExA, CreateWindowExW? | I read the documentation about CreateWindowEx CreateWindowExA CreateWindowExW and they all are seem to be identical to each other.
if there is not difference why they all even exist?
| Firstly, CreateWindowEx is a macro, which expands to either CreateWindowExA or CreateWindowExW based on whether UNICODE has been defined. Many WinAPI functions work this way: they have a macro which switches between the appropriate functions based on UNICODE, then have the A and W versions.
Now, the difference with the A and W versions is fairly simple.
The "A" version handles text based on Windows code pages, while the "W" version handles Unicode text.
-- Source: https://learn.microsoft.com/en-us/windows/win32/intl/code-pages
From Microsoft documentation:
The winuser.h header defines CreateWindowEx as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
|
72,234,443 | 72,234,632 | I need a function to delete certain characters from a char array in c++ without using any index | for example:
if the user enters :
( 23+22+43)
I want the function to do exactly the following :
for(int i =0; i <strlen(x);i ++)
{
if (x[i]=='+')
{
deletfunc(x[i]);
deletfunc(x[i+1]);
cout<<x;
}
}
so that the output will be (2323)
without using index ----> without knowing the exact number of the char in the array for example I couldn't say deletefunc[3] , I don't know if + is the 3rd or 4rth or 2nd element and so on and the + maybe repeated more than once.
Please if anyone can help I had been trying do this task for 4 days now
| Usually when working with a C style string and the instructor says, "No indexes!" they want you to use a pointer.
Here is one way you could use a pointer
char * p = x; // point p at start of array x
while (*p) // loop until p points to the null terminator - the end of the string
{
if (*p=='+') // if value at p is +
{
deletfunc(p - x); // distance between p and x is index
if (*(p+1)) // make sure there is a p+1 to erase
{
deletfunc(p+1 - x);
}
}
p++; // advance pointer to next character in array x
}
cout << x; // print revised string
|
72,234,470 | 72,234,572 | Is there a simpler way to write a concept that accepts a set of types? | Essentially, is there a shorter/cleaner way to define Alphabet than using a bunch of std::same_as/std::is_same?
struct A {};
struct B {};
struct C {};
...
template <typename T>
concept Alphabet =
std::same_as<T, A> ||
std::same_as<T, B> ||
std::same_as<T, C> ||
...
You could accomplish this (sort of) by defining a base class and using std::is_base_of, but for the sake of this question let's assume A, B, C, etc. cannot be modified.
| Using Boost.Mp11, this is a short one-liner as always:
template <typename T>
concept Alphabet = mp_contains<mp_list<A, B, C>, T>::value;
Or could defer to a helper concept (or a helper variable template or a helper whatever):
template <typename T, typename... Letters>
concept AlphabetImpl = (std::same_as<T, Letters> or ...);
template <typename T>
concept Alphabet = AlphabetImpl<T, A, B, C>;
However, note that any other implementation other than the painfully rote one:
template <typename T>
concept Alphabet = same_as<T, A> or same_as<T, B> or same_as<T, C>;
Leads to differing behavior with regards to subsumption. This probably doesn't matter, but it might:
template <Alphabet T> void f(T); // #1
template <same_as<A> T> void f(T); // #2
f(A{}); // with the repeated same_as or same_as or ..., this calls #2
// with any other nicer implementation, ambiguous
|
72,234,507 | 72,349,335 | How can I remove the title bar / undecorate the window in FLTK on Linux? | I have been doing some things with FLTK on Linux lately, and now I've wondered how I can remove the title bar / undecorate the window. The target Operating System is Linux, but it would be preferrable if it runs on wayland as well as on xorg.
| There are two functions that can be used: border(int b) and clear_border().
The border(int b) function tells to the window manager to show or not the border: see here the documentation. This can be used during the execution.
The other useful function is clear_border(): calling it before the Fl_Window::show() function makes the window manager hide the border. See here the documentation.
The (simple) code below shows how to use these functions.
#include <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Button.H>
void borderHide(Fl_Widget* w, void* p){
Fl_Double_Window* win = (Fl_Double_Window*) p;
// When the input of border() is 0 it tells to the window manager to hide the border.
win->border(0);
}
void borderShow(Fl_Widget* w, void* p){
Fl_Double_Window* win = (Fl_Double_Window*) p;
// When the input of border() is nonzero it tells to the window manager to show the border.
win->border(1);
}
int main(){
Fl_Double_Window* W = new Fl_Double_Window(200, 200,"Test");
// Hide the border from the first execution.
W->clear_border();
// Button which implements the border() function for showing the border.
Fl_Button* S = new Fl_Button(80,150,100,30,"Border on");
S -> callback(borderShow,W);
// Button which implements the border() function for hiding the border.
Fl_Button* H = new Fl_Button(80,100,100,30,"Border off");
H -> callback(borderHide,W);
W->end();
W->show();
return Fl::run();
}
|
72,235,131 | 72,235,238 | Expand variadic template template parameters for use in e.g. std::variant<T...> | This will be a hard nut to crack. I don't even know if it's possible.
My goal is to create a receive function that listens to multiple queues and pastes the object received via the particular queue (that responds first) to the stack in the return statement. This will be done via std::variant. The tricky bits are types: Every queue holds different types, so the variant inside multireceive() needs to be constructed from the template parameters used for the queues passed into it as varargs. Of course in the end the queue objects should only be passed as references.
Here's my approach so far, but you can see I'm very unclear about how to write the pack expansions. I think I'm probably scratching the limits of C++ with this:
#include <array>
#include <variant>
template <typename T>
struct queue
{
T queue_[100];
T receive()
{
return queue_[0];
}
};
// doesn't compile!
template <template <typename... T> class Q>
std::variant<T...> multireceive(Q<T>&... Arg)
{
std::array<std::variant<Arg*...>, sizeof...(T)> queues = { (&Arg )... };
do {
for (size_t i=0; i < sizeof...(T); ++i) {
if (queues[i]->receive()) {
return *queues[i];
}
}
} while(1) // busy wait
}
int main() {}
Clearly this doesn't even remotely compile, its just me trying to show intent. The queue is of course also just a stub. Afaik you can't even grab the template template parameter by name (T) which is very unfortunate. Has someone smarter than me already figure out how to solve that problem?
Note:
The way I did it until now is via dynamic dispatch over a non-templated base_struct. This solution however loses type information and my plan is to dispatch the variant via std::visit at the callsite of multireceive. This would then be a very neat solutions to dispatch directly from queue events.
| Since all your queues use the same template (queue<...>), you don't need a template template parameter (in which, by the way, the name of the nested parameter (T in your case) is ignored). You just need a type pack: typename ...T.
I also got rid of the variant array, and instead opted to iterate over the arguments directly, using a lambda in a fold expression. Though this makes extracting the return value harder, so I've put it into an optional:
#include <array>
#include <optional>
#include <variant>
template <typename T>
struct queue
{
T queue_[100];
T receive()
{
return queue_[0];
}
};
template <typename ...P>
std::variant<P...> multireceive(queue<P> &... args)
{
std::optional<std::variant<P...>> ret;
while (true)
{
// For each `args...`:
([&]{
// Do something with `args` (the current queue).
if (args.receive())
{
ret.emplace(args.queue_[0]);
return true; // Stop looping over queues.
}
return false;
}() || ...);
if (ret)
break;
}
return *ret;
}
int main()
{
queue<int> a;
queue<float> b;
std::variant<int, float> var = multireceive(a, b);
}
|
72,235,156 | 72,249,468 | Provide run time environment variable path (e.g. LD_LIBRARY_PATH) to third party dependency in bazel | In the code base I am working with we use the oracle instant client library as a third party dependency in Bazel as follows:
cc_library(
name = "instant_client_basiclite",
srcs = glob(["*.so*"]),
visibility = ["//visibility:public"],
)
The library looks as this:
$ bazel query 'deps(@instant_client_basiclite//:instant_client_basiclite)'
@instant_client_basiclite//:instant_client_basiclite
@instant_client_basiclite//:liboramysql.so
@instant_client_basiclite//:libociicus.so
@instant_client_basiclite//:libocci.so.21.1
@instant_client_basiclite//:libocci.so
@instant_client_basiclite//:libnnz21.so
@instant_client_basiclite//:libclntshcore.so
...
It works as far as linking is concerned, but it seems that the path to the library is still needed because otherwise I get a run time error (oracle error 1804). The error can be solved by setting any of the environment variables ORACLE_HOME or LD_LIBRARY_PATH. In fact for the IBM WebSphere MQ there is the same need (character encoding table files need to be found).
ldd on a binary points to .../bazel-bin/app/../../../_solib_k8/_U@instant_Uclient_Ubasiclite_S_S_Cinstant_Uclient_Ubasiclite___U/libocci.so.21.1
How can I set those needed path variables so that bazel test, bazel run and Bazel container image rules work?
| One possibility is to add the following command line option:
--test_env=ORACLE_HOME="$(bazel info output_base)/external/instant_client_basiclite"
It is a pity that it cannot be put in .bazelrc.
|
72,235,463 | 72,235,700 | Aliasing a SSBO by binding it multiple times in the same shader | Playing around with bindless rendering, I have one big static SSBO that holds my vertex data. The vertices are packed in memory as a contiguous array where each vertex has the following layout:
| Position (floats) | Normal (snorm shorts) | Pad |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P.x | P.y | P.z | N.x | N.y | N.z | |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| float | float | float | uint | uint |
Note how each vertex is 20 bytes / 5 "words" / 1.25 vec4s. Not exactly a round number for a GPU. So instead of doing a bunch of padding and using uneccessary memory, I have opted to unpack the data "manually".
Vertex shader:
...
layout(std430, set = 0, binding = 1)
readonly buffer FloatStaticBuffer
{
float staticBufferFloats[];
};
layout(std430, set = 0, binding = 1) // Using the same binding?!
readonly buffer UintStaticBuffer
{
uint staticBufferUInts[];
};
...
void main()
{
const uint vertexBaseDataI = gl_VertexIndex * 5u;
// Unpack position
const vec3 position = vec3(
staticBufferFloats[vertexBaseDataI + 0u],
staticBufferFloats[vertexBaseDataI + 1u],
staticBufferFloats[vertexBaseDataI + 2u]);
// Unpack normal
const vec3 normal = vec3(
unpackSnorm2x16(staticBufferUInts[vertexBaseDataI + 3u]),
unpackSnorm2x16(staticBufferUInts[vertexBaseDataI + 4u]).x);
...
}
It is awfully convenient to be able to "alias" the buffer as both float and uint data.
The question: is "aliasing" a SSBO this way a terrible idea, and I'm just getting lucky, or is this actually a valid option that would work across platforms?
Alternatives:
Use just one buffer, say staticBufferUInts, and then use uintBitsToFloat to extract the positions. Not a big deal, but might have a small performance cost?
Bind the same buffer twice on the CPU to two different bindings. Again, not a big deal, just slightly annoying.
| Vulkan allows incompatible resources to alias in memory as long as no malformed values are read from it. (Actually, I think it's allowed even when you read from the invalid sections - you should just get garbage. But I can't find the section of the standard right now that spells this out. The Vulkan standard is way too complicated.)
From the standard, section "Memory Aliasing":
Otherwise, the aliases interpret the contents of the memory
differently, and writes via one alias make the contents of memory
partially or completely undefined to the other alias. If the first alias is a host-accessible subresource, then the bytes affected are those written by the memory operations according to its addressing scheme. If the first alias is not host-accessible, then the bytes
affected are those overlapped by the image subresources that were
written. If the second alias is a host-accessible subresource, the
affected bytes become undefined. If the second alias is not
host-accessible, all sparse image blocks (for sparse
partially-resident images) or all image subresources (for non-sparse
image and fully resident sparse images) that overlap the affected
bytes become undefined.
Note that the standard talks about bytes being written and becoming undefined in aliasing resources. It's not the entire resource that becomes invalid.
Let's see it this way: You have two aliasing SSBOs (in reality just one that's bound twice) with different types (float, short int). Any bytes that you wrote floats into became valid in the "float view" and invalid in the "int view" the moment you wrote into the buffer. The same goes for the ints: The bytes occupied by them have become valid in the int view but invalid in the float view. According to the standard, this means that both views have invalid sections in them; however, neither of them is fully invalid. In particular, the sections you care about are still valid and may be read from.
In short: It's allowed.
|
72,235,485 | 72,240,702 | Clarification about modern CMake structure | I am not an expert C or C++ programmer, but I have to write a C and a C++ application for two course projects. To start off on the right foot, I was reading a guide about how to structure the code of a CMake project.
I would like to clarify the meaning and usage of the include directory:
If the project is a library, is the include directory meant to contain the API functions that the users of the library can include in their code and invoke? If so, what directory should be used for headers containing declarations of internal functions? Should such headers be put together with the source code (which is contained in the src directory)?
If the project is an application, is the include directory meant to contain the header files of the source code? If so, what is the advantage of separating headers from sources? Is it just a matter of preference of organization?
Thank you for any insight.
| If you are writing an application, you can put stuff wherever you want. The user mostly expects you to have a bin subdirectory with your binary executables. Oh, and please support the CMAKE_INSTALL_PREFIX: in-source builds are evil, as far as I'm concerned.
If you are writing a library, the user expects subdirectories include and lib in the install prefix location. For nice unix-y stuff you can include man if you know how to generate troff.
About the include directory. You can put your mylib.h file directly there, but if your library has at all a common name, say format, that may give name clashes, so these day many package organize it as /home/mylibinstallation/include/mylibrary/mylib.h. You would then export MYLIBINC=/home/mylibinstallation/include and the program would `#include "mylibrary/mylib.h". That extra level is also good if you have multiple includes.
|
72,235,611 | 72,235,952 | Initialize array based on C++ version and compiler | In C++11 or higher regardless of compiler int myArray[10] = { 0 }; would initialize to all elements to zero. The question is would this also work in C++98 and could the compiler not decide to initialize all elements to zero? In other words could C++98 with a given compiler ignore the assigning zero to all elements?
I found this page: https://en.cppreference.com/w/cpp/language/zero_initialization which lists C++98 defects about zero initialization.
| All elements would be zero. Quotes from C++98:
[dcl.init.aggr]
If there are fewer initializers in the list than there are members in the aggregate, then each member not
explicitly initialized shall be default-initialized (8.5)
[dcl.init]
To default-initialize an object of type T means:
if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is
ill-formed if T has no accessible default constructor);
if T is an array type, each element is default-initialized;
otherwise, the storage for the object is zero-initialized.
The meaning of default initialisation was radically different in C++98 compared to its meaning starting from C++03 where the old default initialisation essentially was renamed value initialisation and the new default initialisation became to mean "no initialisation" for trivial types.
Note that int myArray[10] = {}; would achieve the same goal. It's unnecessary to explicitly provide a value for the first element.
|
72,236,508 | 72,237,025 | Returning MIME data from a function in Qt | I am trying to create a class with drag and drop. I want it to be used as a base class for future derived classes. I want derived classes to specify MIME data for Drag and Drop. I made a function that returns MIME data as a pointer, I am not sure if it is safe to do so. Is it possible that it will cause memory leak or other problems? It works now and doesn't show any warnings. I am new to Qt and don't have much experience with pointers in C++, so sorry if it is a stupid question.
QMimeData* BasicGraphicsObject::setObjectMimeData()
{
QMimeData *mime = new QMimeData;
mime->setImageData(itemToImage());
mime->setText("BasicItem");
return mime;
}
Drag implementation function:
void BasicGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
// This prevents mouse jitter noise, drag starts only if distance is sufficient
if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton))
.length() < QApplication::startDragDistance()) {
return;
}
//initialising drag event
QDrag *drag = new QDrag(event->widget());
//setting mime data with setObjectMimeData function
drag->setMimeData(setObjectMimeData());
//setting cursor as an image of the item being dragged
drag->setPixmap(itemToImage().scaled(boundingRect().size().toSize()));
drag->setHotSpot(QPoint(15,20));
drag->exec();
setCursor(Qt::OpenHandCursor);
}
| The man page for QDrag::setMimeData() says that “ownership of the QMimeData object is transferred to the QDrag object”, which is another way of saying that the QDrag object will delete the QMimeData object when it is done with it. Therefore you should not experience any memory leak of the QMimeData object (unless you somehow never call setMimeData() with it)
|
72,236,837 | 72,236,900 | Problem: Assigning a group number to elements near eachother where groups are separated from spaces | We have a room divided of 6x5 possible seats, every place in the 6x5 matrix could be a seat or could be empty.
We have the Matrix with all the seats already assigned on their location, and every seat has an unique code which is the actual Column(A,B,C,D,E)Row(1,2,3,4,5,6) position.
Unique code Example could be: A1, C4, E2, ....
The request is to assign the same group to all the seats that are next to each other:
Example: enter image description here
In this example the result is marked by the red color showing 3 groups.
The groups are assigned from 1 to N where the first top left will always be the first group.
There's no limitation on what to use; Arrays, Matrix, Lists, Trees, Graphs.
I would like to know if somebody here can find an efficient algorithm to execute the exercise on any seats configuration.
| This is a classical neighbourhood-search scenario. See BFS / DFS algorithms.
You can instantiate the graph as a simple array or a two-dimensional array and have implicit edges between each two neighbouring cells that both have a seat assigned.
For example:
std::array<std::array<std::optional<unsigned>,7>,8> matrix;
As you can see, the matrix is two columns and two rows too large. If you leave these cells as sentinels you can save a lot performance. You implement a function that identifies all neighbours of a particular cell and use that to drive your BFS / DFS. You can initialise all cells containing seats to 0 and empty cells are automatically initialised to std::nullopt.
If you want to be slightly lazy and you have a very dense matrix, you could conceivably also go for union find.
|
72,236,995 | 72,237,085 | Object Oriented Programming - Inheritance C++, Code does not compile | Source Code
#include <iostream>
using namespace std;
class A
{
private:
long int a;
public:
long int b,x;
void set_a(){
cout<<"Enter variable A's value (integer) \nAnswer: ";
cin>>a;
x=a;
}
void display_a(){
cout<<"\n value for Variable A: "<<x<<endl;
}
void getdata(){
cout<<"Enter variable B's value (integer) \nAnswer: ";
cin>>b;
}
};
class B:public A
{
private:
long int prod;
public:
void prod(){
prod = x*b;
}
void display(){
cout<<"Displaying product of variables A and B \nProduct: "<<prod<<endl;
}
};
int main()
{
A obj;
B obj2;
obj.set_a();
obj.display_a();
obj2.display();
}
Complier Error Message
37 | }
| ^
main.cpp:31:16: note: previous declaration ‘long int B::prod’
31 | long int prod;
| ^~~~
I have just started learning Inheritance functions from Object Oriented programming so I am quite the novice. I believe the program lies within the Inheritance function sub class but I am not too sure.
Also, I am pretty sure there is a method to checking the solution to error messages from the compiler but I don't know what it is or where to look, so some assistance would be helpful
| There are 2 problems with your code described below.
Problem 1
You have a method prod with the same name as the data member prod in class B.
To solve this change, you can either change the name of the method or the data member so that they're not the same as shown below.
Problem 2
The code has undefined behavior because you're using the value of the uninitialized data member b.
To solve this make sure that b is initialized(or assigned) before using its value as shown below. Similarly, prod is uninitialized.
Additionally, you were creating a separate object obj and calling the member functions on that object. That obj is different from the subobject A inside B object obj2. This has been fixed and highlighted using comments in the below program so that you can see what changes have been made.
class A
{
private:
long int a;
public:
long int b,x;
void set_a(){
std::cout<<"Enter variable A's value (integer) \nAnswer: ";
std::cin>>a;
x=a;
}
void display_a(){
std::cout<<"\n value for Variable A: "<<x<<std::endl;
}
void getdata(){
std::cout<<"Enter variable B's value (integer) \nAnswer: ";
std::cin>>b;
}
};
class B:public A
{
private:
long int prod;
public:
//-------vvvvvvv------------->name changed to product so that it is different from prod data member
void product(){
//call these methods here inside product instead of calling them outside on a separater `A` object
set_a();
getdata();
display_a();
prod = x*b;
}
void display(){
std::cout<<"Displaying product of variables A and B \nProduct: "<<prod<<std::endl;
}
};
int main()
{
//no need to create a separate `A` object
B obj2;
obj2.product();
obj2.display();
}
Demo
In the above program the call to member functions set_a, getdata and dispaly_a is made from inside the member function product instead of calling them on a separate A object.
|
72,237,424 | 72,237,467 | Issue overloading the operator c++ | I keep getting the following errors
Error (active) E0349 no operator "<<" matches these operands
Error C2678 binary '<<': no operator found which takes a left-hand operand of type 'std::ostream' (or there is no acceptable conversion)
I know the issue is that there's something going wrong or missing when I try to overload the operator and I think its something small at this point, but I have no idea anymore. Any help would be appreciated.
.h file
#include <iostream>
#include <string>
#include <ostream>
using namespace std;
#ifndef ACCOUNT_H
#define ACCOUNT_H
class account {
private:
int acct_ID;
string acct_name;
float acct_balance;
static int next_id;
public:
account();
account(account& rhs);
~account();
account(int acct_ID, string acct_name, float acct_balance);
void set_ID(int acct_ID);
int get_ID()const;
void set_name(string acct_name);
void input();
void set_balance(float acct_balance);
ostream& display(ostream& stream);
};
ostream& operator<<(ostream& stream, account& Account); //!!!!!!!!!!!!!!!!!!!
#endif
.cpp file
#include "Account.h"
account::account(): acct_ID{0},acct_name{0},acct_balance{ 0 }{}
account::account(account& rhs): acct_ID{ rhs.acct_ID }, acct_name{ rhs.acct_name }, acct_balance{ rhs.acct_balance }{}
account::account(int ID, string name, float balance) :acct_ID{ ID }, acct_name{ name }, acct_balance{ balance } {
}
int account::next_id = 0;
account::~account() {}
void account::set_ID(int ID) {
acct_ID = ID;
}
int account::get_ID()const {
int acct_ID = 0;
return acct_ID;
}
void account::set_name(string name) {
acct_name = name;
}
void account::input() {
cout << "Enter the name: ";
cin >> acct_name;
float x;
cout << "Enter the balance: ";
cin >> x;
acct_balance += x;
acct_ID = next_id;
next_id++;
}
//!!!!!!!!!!!!!!!!!!!!!!!
ostream& account::display(ostream& stream) {
stream << "Account name: " << this->acct_name;
stream << "Account balance: " << this->acct_balance;
stream << "Account ID: " << this->acct_ID;
return stream;
}
ostream& operator<<(ostream& stream,account& Account) {
stream << Account.display(stream);
return stream;
} //!!!!!!!!!!!!!!!
void account::set_balance(float balance)
{
acct_balance = balance;
}
| The problem is that you've used:
stream << Account.display(stream);
inside the overloaded operator<<. This is a problem because account::display returns a std::ostream and there is no overload of operator<< that takes a std::ostream as a parameter.
Method 1
To solve this you can add a friend declaration for the overloaded operator<< inside the class and change the implementation of operator<< to as shown below:
class account
{
//other members as before
//friend declaration for overloaded operator<<
friend std::ostream& operator<<(std::ostream& stream, account& Account);
};
//implementation of operator<<
std::ostream& operator<<(std::ostream& stream,account& Account) {
stream << Account.acct_ID<<" "<< Account.acct_name<<" "<<Account.acct_balance<<" "<<Account.acct_ID;
return stream;
}
Working demo
Method 2
Another way to solve this is to replace stream << Account.display(stream); with return Account.display(stream); as shown below:
std::ostream& operator<<(std::ostream& stream,account& Account) {
return Account.display(stream); //changed this
}
Demo
|
72,237,709 | 72,237,791 | how to initialize a class object reference in C++ to simulate NRVO? | I meet a course programming problem, which asks me to initialize the A a using passing by reference (initialize the A a in the func). How can I call A's constructor by A's reference?
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
cout << "default constructor" << endl;
x = 1;
}
A(int x)
{
cout << "constructor with param = " << x << endl;
this->x = x;
}
~A() {
cout << "destructor" << endl;
}
void print() {
cout << x << endl;
}
};
void fun(A& a)
{
a.A::A(10); // error!
return;
}
int main()
{
A a;
fun(a);
a.print();
return EXIT_SUCCESS;
}
There is a background of this problem. The teacher want us to replicate the NRVO(named return value optimization) result.
#include <iostream>
using namespace std;
class A
{
public:
int x;
A()
{
cout << "default constructor" << endl;
x = 1;
}
A(int x)
{
cout << "constructor with param = " << x << endl;
this->x = x;
}
~A() {
cout << "destructor" << endl;
}
void print() {
cout << x << endl;
}
};
A fun() {
A a = A(10);
return a;
}
int main()
{
A a = fun();
return EXIT_SUCCESS;
}
default g++ compiler:
constructor with param = 10
destructor
if we close the NRVO:
g++ test.cpp -fno-elide-constructors
constructor with param = 10
destructor
destructor
destructor
destructor
The teacher want us to replicate the NRVO(named return value optimization) result by passing by reference.
| The syntax a.A::A(10); is incorrect.
Constructor is used to create an object of a class, you cannot call it on an already existing object. Even a constructor cannot be explicitly called. It is implicitly called by the compiler.
From general-1.sentence-2:
Constructors do not have names.
Thus, you cannot call a constructor explicitly. The compiler will automatically call the constructor when an object of that class-type is created.
|
72,237,872 | 72,237,946 | Modifying a member variable | I'm having an issue with modifying a member of a class. I overloaded the operators and I think that I am calling the member correctly to modify it but am getting the issue that the "expression must be a modifiable l-value.
Any help would be appreciated
.h file
public:
account& operator+= (float x);
account& operator-= (float y);
float set_balance();
.cpp file
account& account::operator+=(float x)
{
this->acct_balance += x;
return *this;
}
account& account::operator+=(float y)
{
this->acct_balance -= y;
return *this;
}
float account::set_balance()
{
return this->acct_balance;
}
main file
//deposit
else if (imput == 2)
{
float deposit;
cout << "Please enter the amount to deposit: ";
cin >> deposit;
user1.set_balance() += deposit;
}
//withdrawl
else if (imput == 3)
{
float withdraw;
cout << "Please enter the amount to deposit: ";
cin >> withdraw;
user1.set_balance() += withdraw;
}
| Your set_balance function doesn't set anything. You probably want this:
float& account::get_balance()
{
return this->acct_balance;
}
Then you can do user1.get_balance() += withdraw;.
This get_balance function gets the balance as a modifiable l-value, which is what you need.
Since you have an operator+=, you could also just do user1 += withdraw;.
|
72,238,228 | 72,240,852 | BOOST request sending JSON data | I want to transfer json data into request of json boost in cpp.
If i take json in boost
int outer=2;
value data = {
{"dia",outer},
{"sleep_time_in_s",0.1}
};
request.body()=data;
like above i want to send data from boost client to server , but it's through error
is any one understand below error suggest me .
error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
C:\Boost\boost/beast/core/multi_buffer.hpp(360,25): message : could be 'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(const boost::beast::basic_multi_buffer<std::allocator<char>> &)'
2>C:\Boost\boost/beast/core/multi_buffer.hpp(345,5): message : or 'boost::beast::basic_multi_buffer<std::allocator<char>> &boost::beast::basic_multi_buffer<std::allocator<char>>::operator =(boost::beast::basic_multi_buffer<std::allocator<char>> &&)'
2>C:\Development\qa-cal\sysqa_cpp\src\guiClient\boostHttpClient.cpp(90,31): message : while trying to match the argument list '(boost::beast::basic_multi_buffer<std::allocator<char>>, std::string)'
| C++ is strongly typed. You cannot assign a json::value to something else. In this case your body() is likely something like std::string.
Assuming that value is boost::json::value you should write something like:
request.body() = serialize(data);
Where boost::json::serialize serializes the data value into string representation.
Live Demo
#include <boost/beast.hpp>
#include <boost/json.hpp>
#include <boost/json/src.hpp>
#include <iostream>
namespace http = boost::beast::http;
int main() {
using boost::json::value;
http::request<http::string_body> request(
http::verb::post, "/some/api", 11);
{
int outer = 2;
value data = {
{"dia", outer},
{"sleep_time_in_s", 0.1},
};
request.body() = serialize(data);
}
request.prepare_payload();
std::cout << request;
}
Prints
POST /some/api HTTP/1.1
Content-Length: 32
{"dia":2,"sleep_time_in_s":1E-1}
|
72,238,972 | 72,239,020 | emplace and try_emplace with copy constructor | I have an issue with emplace and try_emplace as they always use the copy constructors when moving an object in.
#include <iostream>
#include <unordered_map>
#include <map>
using namespace std;
class Too {
public:
Too(int x, int y):x_(x), y_(y) {
cout << "init " << x_ << endl;
}
Too(const Too& too):x_(too.x_+1), y_(too.y_+1) {
cout << "Copy happen: x = " << x_ << endl;
}
~Too() {
cout << "delete too " << x_ << endl;
}
private:
int x_, y_;
};
std::map<int, Too> v;
int main()
{
v.emplace(100, Too{ 100,23 });
v.try_emplace(12, 12, 13);
Too t = Too(10, 11);
v.try_emplace(11, std::move(t));
}
output
init 100
Copy happen: x = 101
delete too 100
init 12
init 10
Copy happen: x = 11
delete too 10
delete too 101
delete too 12
delete too 11
As you can see, only v.try_emplace(12, 12, 13) do not use the copy constructor.
both v.emplace(100, Too{ 100,23 }) and v.try_emplace(11, std::move(t)) invoke the copy constructor.
So how can it be even when I use std::move(t)?
Any suggestion would be highly appreciated.
Thanks,
| Since you've provided a copy constructor for your class, the move constructor Too::Too(Too&&) will not be implicitly generated by the compiler.
Moreover, when there is no move constructor available for a class, the copy constructor can be used.
For using the move constructor you have to explicitly provide an appropriate user-defined move constructor Too::Too(Too&&), then you will get the desired result.
You can add the move constructor either by adding Too(Too&&) = default; or writing your own move constructor which will do the initialization in the constructor initializer list.
|
72,239,021 | 72,239,154 | Passing an array in struct initialization | I would like to create a struct which contains both an int and an array of int. So I define it like
struct my_struct {
int N ;
int arr[30] ;
int arr[30][30] ;
}
Then I would like to initialize it with an array which I have already defined and initialized, for example
int my_arr[30] ;
for (int i = 0; i < 30; ++i)
{
my_arr[i] = i ;
}
Then I thought I could initialize a struct as
my_struct A = {30,my_arr}
but it doesn't seem to work (gives conversion error).
P.s. and how would it work with a 2d array?
| Arrays cannot be copy-initialised. This isn't particular to the array being member of a class; same can be reproduced like this:
int a[30] = {};
int b[30] = a; // ill-formed
You can initialise array elements like this:
my_struct A = {30, {my_arr[0], my_arr[1], my_arr[2], //...
But that's not always very convenient. Alternatively, you can assign the array values using a loop like you did initially. You don't have to write the loop either, there's a standard algorithm for this called std::copy.
|
72,239,263 | 72,239,359 | Expression does not evaluate to a constant | I've just started to learn C++ and I don't understand this error:
std::string AFunction(const std::string& str) {
size_t s = str.length();
char inProgress[s];
return std::string();
}
I get the error:
error C2131: expression does not evaluate to a constant
Here: char inProgress[s];
What do I have to do the set inProgress size with the length of str?
| The problem is that in standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program:
size_t s = str.length();
char inProgress[s]; //not standard C++ because s is not a constant expression
Better would be to use std::vector as shown below:
std::string AFunction(const std::string& str) {
size_t s = str.length();
std::vector<char> inProgress(s); //create vector of size `s`
return std::string{};
}
|
72,239,570 | 72,239,597 | How to construct a class from a pack in C++? | I am trying to initialize a class with a pack passed as an argument to my function. Here is what I got so far:
struct Vec3
{
float x, y, z;
};
template<typename _Ty, typename... Args>
__forceinline _Ty construct_class(Args&&... arguments)
{
return _Ty(arguments...);
}
// here I am trying to construct a Vec3 by calling construct_class
Vec3 vec = construct_class<Vec3>(10.f, 20.f, 30.f);
Unfortunately I get the following compiler error in visual studio: C2440 '<function-style-cast>': cannot convert from 'initializer list' to '_Ty'
I have seen people doing this:
template<typename _Ty, typename... Args>
__forceinline _Ty construct_class(Args&&... arguments)
{
return _Ty(std::forward<Args>(arguments)...);
}
But this also doesn't work for me, I get the exact same compiler error as before.
So my question is how should I use the pack/intializer list inside construct_class to construct the _Ty class (in this case Vec3)? I am not familiar with packs in C++.
| You could replace return _Ty(arguments...) with return _Ty{arguments...} as shown below:
//---------------v--------------------- v----->removed the underscore
template<typename Ty, typename... Args> Ty construct_class(Args&&... arguments)
{
//-----------v------------v------------------->used curly braces instead of parenthesis
return Ty{arguments...};
}
Working Demo
Also, note that the given program will work with C++20 without having to use curly braces.
Also, What are the rules about using an underscore in a C++ identifier? might come in handy when using leading underscore for names.
|
72,240,126 | 72,242,127 | MISRA 5-0-15 - Pointer Arithmetic - Rule Violation | The following code violates the MISRA C++ rule 5-0-15: Array indexing shall be the only form of pointer arithmetic.
(1)
void doSomething(const uint8_t *&ptr, size_t num) {
ptr += num;
}
Incrementing any pointer also violates the above rule:
(2)
const uint8_t *ptr = ... ;
*ptr++;
I found a very similar question here, but there the questioner uses arrays. I use pointers.
Is there an alternative notation or other method to add numbers to (1)/ increment (2) pointers to get around this violation?
|
Array indexing
So use array indexing.
void doSomething(const uint8_t ptr[], size_t num) {
const uint8_t *ptr2 = &ptr[num];
}
Incrementing any pointer
Increment and decrement operators can be used by exception. Doing dereference with incrementing is invalid. There have to be two expressions.
const uint8_t *ptr = somearray;
++ptr;
uint8_t val = *ptr;
|
72,240,387 | 72,240,549 | Why is std::reverse_iterator slower than a direct iterator? | I noticed that std::reverse_iterator always decrements a copy of internal iterator before dereference:
_GLIBCXX17_CONSTEXPR reference
operator*() const
{
_Iterator __tmp = current;
return *--__tmp;
}
This is the implementation in GNU standard C++ library. cppreference.com implements it the same way.
The question: wouldn't it be more efficient to decrement it just one time in reverse iterator constructor instead of decrementing it at every dereference step?
|
The question: wouldn't it be more efficient to decrement it just one time in reverse iterator constructor instead of decrementing it at every dereference step?
Efficiency is irrelevant when it's not possible to implement reverse iterator that way. Consider a reverse iterator representing rend. In order to get to it, you would have to decrement the internal iterator so that it points before the first element. That's not possible, so the decrement must be delayed until indirection where the impossibility is fine because end iterators are not dereferencible.
|
72,240,404 | 72,240,861 | Big O notation calculation for nested loop | for ( int i = 1; i < n*n*n; i *= n ) {
for ( int j = 0; j < n; j += 2 ) {
for ( int k = 1; k < n; k *= 3 ) {
cout<<k*n;
}
}
}
I am facing an issue with this exercise, where I need to find the big O notation of the following code, but I got O(n^5) where the first loop is n^3, 2nd loop n, and the 3rd loop is n and I am not sure if I am correct or not. Can someone help me please?
| Your analysis is not correct.
The outer loop multiplies i by n each ietration,starting from 1 till n^3.
Therefore there will be 3 iterations which is O(1).
The middle loop increments j by 2 each iteration, starting from 0 till n.
Therefore there will be n/2 iterations which is O(n).
The inner loop multiplies k by 3, from 1 till n.
Therefore there will be log3(n) iterations, which is O(log(n)).
If this step is not clear, see here: Big O confusion: log2(N) vs log3(N).
The overall time complexity of the code is a multiplication of all the 3 expressions above (since these are nested loops).
Therefore is it: O(1) * O(n) * O(log(n)), i.e.: O(n*log(n)).
|
72,240,611 | 72,274,597 | D3D : hardware mip linear blending is different from shader linear blending | I have a d3d application that renders a mip mapped cubemap in a fullscreen quad pixel shader.
I stumbled on a weird behavior, and wrote the following test to illustrate the issue.
This shader outputs the absolute difference between hardware mip map filtering and HLSL equivalent.
TextureCube Tex_EnvMap : register(ps, t0);
SamplerState Sampler_EnvMap : register(ps, s0);
void FragmentMain(in SFragmentInput fInput, out SFragmentOutput fOutput)
{
// ...
// Not shown:
// Mip is an uniform set by the application
// dir is the sampling direction setup from pixel coord.
// ...
float fl = floor(Mip);
float fr = frac(Mip) ;
float3 c0 = Tex_EnvMap.SampleLevel(Sampler_EnvMap, dir, fl).rgb;
float3 c1 = Tex_EnvMap.SampleLevel(Sampler_EnvMap, dir, fl + 1.).rgb;
float3 c = lerp(c0, c1, fr);
float3 cref = Tex_EnvMap.SampleLevel(Sampler_EnvMap, dir, Mip).rgb;
fOutput.outColor = float4 (abs(c-cref), 1);
}
On one computer, this test renders black across all mip values (0 - 10), which is expected. The base application (display of the cubemap) has a perceptually linear blend across all mip values.
On another computer, the test is black on integer mips (obviously), and otherwise renders like this (the two ways of filtering are clearly different). The base application has a perceptually more step-like blending but still, it has some blending. As if the fractional part of mip was smoothstepped.
Pix capture on the machine having the issue shows expected values for my resources:
Sampler:
Filter ANISOTROPIC
AddressU CLAMP
AddressV CLAMP
AddressW CLAMP
MipLODBias 0.00000f
MaxAnisotropy 16
ComparisonFunc 0
BorderColor
MinLOD 0.00000f
MaxLOD 10.0000f
Image:
Format: R16G16B16A16_FLOAT
Dimensions: 1024⨯1024
# of Mip Levels: 11
Sample Count: 1
Dimensions: 1024⨯1024
Mip Levels: 0-10
Array Slices: 0-5
ResourceMinLODClamp: 0
What could lead to this? I'm looking for some filtering related parameter set by my application that could explain the discrepancy between in-shader filtering and d3d sampler filtering, like anisotropic filtering (but this is not a candidate as I use explicit LOD sampling). Then finding why my application set this differently on 2 hardwares shouldn't be too hard.
I don't think that this is a driver issue, but I'm not an expert here. I use some higher level rendering API interface, so I was albe to do the same test with OGL or vulkan and the issue shows too.
Thanks a lot! :-)
| I was writing "but anisotropic filtering is not a candidate as I use explicit LOD sampling)".
It turns out that this statement it wrong. To my understanding, anisotropic filtering should not affect sampling with textureLOD, however, it seems that in some implementations, it does, ex: https://forum.unity.com/threads/tex2dlod-and-anisotropic-filtering.585955/ I'm still curious why exactly and would appreciate more references.
Setting the sampler to not use anisotropic filtering solved the issue.
|
72,241,045 | 72,242,048 | Ternary operator applied to class with conversion operator and delete constructor causes ambiguity | struct A {
A();
A(int) = delete;
operator int();
};
int main() {
true ? A{} : 0;
}
Compile with C++20, Clang accepts it, but GCC and MSVC reject it with similar error messages
<source>(8): error C2445: result type of conditional expression is ambiguous: types 'A' and 'int' can be converted to multiple common types
<source>(8): note: could be 'A'
<source>(8): note: or 'int'
int doesn't seem to be convertible to A since the constructor is delete, but I'm not sure why GCC/MSVC still thinks it can. Which compiler is right?
(Demo)
| This seems to be a variant of CWG issue 1895.
Before its resolution (in 2016 with C++17) the relevant wording asked whether either operand could be "converted" to the target type formed from the other operand's type.
Going by the issue description, it seems this original wording, as well as the wording around it, were somewhat ambiguous in whether or not deletedness of the used constructor/conversion operator in this conversion should be considered and the issue description seems to indicate that a strict reading lead to surprisingly inconsistent results. I don't know exactly how the interpretation in the issue would apply to your case, but I would not be surprised if it matches Clang's behavior, given the issue's author.
In any case, the resolution of the issue changed the wording to whether "an implicit conversion sequence can be formed", which is in line with overload resolution and definitively does not consider whether the chosen implicit conversion sequence will actually result in a conversion that is well-formed, in particular whether or not the used functions are accessible/deleted.
The note referenced in the answer by @AnoopRana was also added with that resolution to make this clear.
With the new wording, both the conversion sequences from A{} to int and 0 to A can be formed and hence the operator is ambiguous. MSVC and GCC are correct now.
Clang lists defect report 1895's implementation status as "unknown" at the current time (https://clang.llvm.org/cxx_dr_status.html) and still has an open bug matching the CWG issue description here.
|
72,241,156 | 72,241,320 | Using the dynamic_cast operator | I'm trying to understand dynamic type casting.
How to properly implement the DrawAnimals and Talk To Animals functions using dynamic_cast?
DrawAnimals draws animals that can be drawn. Such animals implement the Drawable interface.
TalkToAnimals conducts a conversation with animals that can talk, that is, they implement the Speakable interface.
class Speakable {
public:
virtual ~Speakable() = default;
virtual void Speak(ostream& out) const = 0;
};
class Drawable {
public:
virtual ~Drawable() = default;
virtual void Draw(ostream& out) const = 0;
};
class Animal {
public:
virtual ~Animal() = default;
void Eat(string_view food) {
cout << GetType() << " is eating "sv << food << endl;
++energy_;
}
virtual string GetType() const = 0;
private:
int energy_ = 100;
};
class Bug : public Animal, public Drawable {
public:
string GetType() const override {
return "bug"s;
}
void Draw(ostream& out) const override {
out << "(-0_0-)"sv << endl;
}
};
class Cat : public Animal, public Speakable, public Drawable {
public:
void Speak(ostream& out) const override {
out << "Meow-meow"sv << endl;
}
void Draw(ostream& out) const override {
out << "(^w^)"sv << endl;
}
string GetType() const override {
return "cat"s;
}
};
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
void TalkToAnimals(const std::vector<const Animal*> animals, ostream& out) {
//?
}
void PlayWithAnimals(const std::vector<const Animal*> animals, ostream& out) {
TalkToAnimals(animals, out);
DrawAnimals(animals, out);
}
int main() {
Cat cat;
Bug bug;
vector<const Animal*> animals{&cat, &bug};
PlayWithAnimals(animals, cerr);
}
| I am going to explain for DrawAnimals and you can extended to other functions by yourself.
What you did here:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
/*if (const Animal* r = dynamic_cast<const Animal*>(&animals)) {
} else if (const Bug* c = dynamic_cast<const Bug*>(&animals)) {
}*/
}
Is plain wrong for several reasons:
animals is a vector
If you intended an individual element, then because &animals[i] (i = [0..animals.size()]) is a pointer to pointer (Animal**)
Because dynamic_cast<const Animal*>(animals[i]) (i = [0..animals.size()]) is the identity.
You need to work with each individual element of the vector:
void DrawAnimals(const std::vector<const Animal*>& animals, ostream& out) {
for (auto animal : animals) {
if (const Drawable* r = dynamic_cast<const Drawable*>(animal)) {
// this animal is Drawable
} else if (const Bug* c = dynamic_cast<const Bug*>(animal)) {
// this animal is a Bug
// only issue here: Bugs are also Drawable
// so this code will never be reached
}
}
}
Question: Why are some animals Drawable and other don't?
|
72,241,315 | 72,241,389 | Convert std::vector to std::string without \0 | I want to remove the vowels from a std::string with this code:
# include <string>
#include <vector>
bool IsVowel(char c) {
return ((c == 'a') ||
(c == 'A') ||
(c == 'e') ||
(c == 'E') ||
(c == 'i') ||
(c == 'I') ||
(c == 'o') ||
(c == 'O') ||
(c == 'u') ||
(c == 'U'));
}
std::string RemoveVowel(const std::string& str) {
const size_t s = str.length();
std::vector<char> inProgress(s);
int index = 0;
for (char c : str) {
if (!IsVowel(c)) {
inProgress[index] = c;
index++;
}
}
std::string sy(inProgress.begin(), inProgress.end());
return sy;
}
But with this input:
"aaaaaa"
I get this output:
"\0\0\0\0\0\0"
But I want to get this:
""
The problem is with std::string sy(inProgress.begin(), inProgress.end());. I don't know how to convert the std::vector to std::string without any \0.
How can I fix this problem?
| As you can see, inProgress always contains str.length() many elements. index tells you the actual number of vowels in there. std::string has constructors that let you use that information to determine how much of inProgress to use in the initialization of sy.
So, you could do:
std::string sy(inProgress.begin(), inProgress.begin() + index);
return sy;
This would construct sy using only the initial segment of inProgress that actually contains vowels.
|
72,241,322 | 72,241,968 | How to find the count of sub numbers of size k which divide the number | Given a number n
Find the count of the sub numbers of size x in a number num which divides num.
For example, if the number is 250
and x=2
the answer will be 2
as 250%25==0
and 250 % 50==0.
Can anyone help me out with the cpp code ?
class Solution {
public:
int divisorSubstrings(int num, int k) {
string s=to_string(num);
int count=0;
int i=0;
int j=k-1;
string temp="";
for(int k=i;k<=j;k++)
{
temp.push_back(s[k]);
}
while(j<s.length())
{
if(num%stoi(temp)==0)
count++;
temp.erase(temp.begin() + i-1);
j++;
i++;
temp.push_back(s[j]);
}
return count;
}
};
this is showing runtime error
| You have a number of problems. First, using simple letters for your variables means we don't have a clue what those variables are for. Use meaningful names.
Second, this:
for(int k=i;k<=j;k++)
You have an argument to your method called k. You've now shadowed it. Technically, you can do that, but it's a really really bad habit.
But the real problem is here:
temp.erase(temp.begin() + i-1);
i is initialize to 0 and never changed until AFTER this line runs the first time. So you're actually erasing a character before the start of the string.
|
72,241,514 | 72,241,582 | vector push_back memory access denied in Visual Studio |
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
numbers.resize(10001);
for (int i = 0; i < 10000; i++)
{
numbers.push_back(1);
}
return 0;
}
If I put more than 5000 1s in the vector, I get the following error, I don't understand.
There is no doubt about it other than the memory overflow. But int type = 4 bytes, so 4byte * 10000 = 40000byte 0.04mb
Why am I getting an error?
| The error seems unrelated to the code that you've shown.
Now, looking at your code there is no need to use resize and then using push_back as you can directly create a vector of size 10001 with elements initialized to 1 as shown below:
std::vector<int> numbers(10001,1);// create vector of size 10001 with elements initialized to 1
Or you can used std::vector::reserve instead of std::vector::resize, though this is totally unnecessary as you can use the first method shown above.
vector<int> numbers;
numbers.reserve(10001); //use reserve instead of resize
for (int i = 0; i < 10000; i++)
{
numbers.push_back(1);
}
|
72,242,061 | 73,369,849 | (esp 32) http.GET() is so slow | I want to get data from REST API by an esp32 and turning on and off LED lights(GPIO 26 and 27).
Here is my code :
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFi.h>
const char* ssid = "ssidName";
const char* password = "password";
void setup() {
Serial.begin(115200);
pinMode(26, OUTPUT);
pinMode(27, OUTPUT);
digitalWrite(26, LOW);
digitalWrite(27, LOW);
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
http.begin("https://retoolapi.dev/XB1y0H/data");
int httpCode = http.GET();
if (httpCode > 0){
String payload = http.getString();
payload.replace('[', ' ');
payload.replace(']', ' ');
char json[500];
payload.toCharArray(json, 500);
StaticJsonDocument<1024> doc;
deserializeJson(doc, json);
String led1 = doc["rele1"];
Serial.print("led1 :");
Serial.println(led1);
if(led1== "1") digitalWrite(26, HIGH);
else digitalWrite(26, LOW);
String led2 = doc["rele2"];
if(led2 == "1") digitalWrite(27, HIGH);
else digitalWrite(27, LOW);
Serial.print("led2 :");
Serial.println(led2);
}
http.end();
}else{
Serial.println("Check your internet connection");
}
}
It works but the problem is , it is so slow ; http.GET() takes approximately 2 seconds to be executed and I dont know why ...
Is it because of API ?
Is there any better solution ? I've heard about webSocket but I'm not sure about it .
Is it good and easy to integrate ?
| I have finally managed to do that by Websokcet .
you have to make http persistent connection , HTTP client library in idf is good but your server has to support it , the better practice is websocket.
|
72,242,240 | 72,242,357 | Why can’t my code find the second smallest elements array? | int smallindex = 0;
int secsmallindex = 0;
I put the lines above into gobalslope.
The rest of the code:
#include <iostream>
using namespace std;
int main() {
int list[10] = { 33,6,3,4,55,22,5,6,7,6 };
for (int a = 1; a <= 10; a++)
{
if (smallindex > list[a]) {
secsmallindex = smallindex;
smallindex = a;
}
else if (list[a] < secsmallindex && list[a] > smallindex) {
secsmallindex = a;
}
}
cout << secsmallindex << " " << smallindex;
}
I want to find the second smallest elements and smallest number.
But it can not find it.
The output is 2 and 10.
| You had some problems. Mostly index ranges of an array, and comparing index with the actual value stored in the array.
I commented out the old (problematic) lines and added the correct ones with some description. (Demo)
#include <iostream>
using namespace std;
int main() {
/// You don't need these variables to be global.
/// Minimise the scope of the variables!
int smallindex = 0;
int secsmallindex = 0;
int list[10] = {33, 6, 3, 4, 55, 22, 5, 6, 7, 6};
/// for (int a = 1; a <= 10; a++) <- old line
/// In C and C++, array indexing is 0 based! Your last index is 9
for (int a = 1; a < 10; a++)
{
/// if (smallindex > list[a]) <- old line
/// You comparing the index to the ath element but you should
/// compare element to element
if (list[smallindex] > list[a])
{
secsmallindex = smallindex;
smallindex = a;
}
/// else if (list[a] < twosmallindex && list[a] > smallindex) <- old line
/// Same as before, compare element to element not element to index
else if (list[a] < list[secsmallindex] && list[a] > list[smallindex])
{
secsmallindex = a;
}
}
cout << secsmallindex << " " << smallindex;
}
Output:
3 2
|
72,242,246 | 72,245,095 | Getting an HTTP response status code of 0 and empty message using C++ curl library libCPR | I'm using libcpr to send a GET request.
cpr::Response r = cpr::Get(
cpr::Url{target.str()},
cpr::Header{header});
For debugging, I print the response—
std::cout << "Response Error: " << r.error.message << std::endl;
std::cout << "Response Error Code: " << (int)r.error.code << std::endl;
std::cout << "Response Status Code: " << r.status_code << std::endl;
std::cout << "Response Text: " << std::endl;
—and get the following:
Response Error:
Response Error Code: 4
Response Status Code: 0
Response Text:
I see a lot of seemingly relevant threads online, but I feel like I've tried everything and I don't know what my particular issue is. I think someone more versed in curl, CMake, or OpenSSL might be able to spot it. So here's what I tried / know:
I don't think it's a problem with my code per se—more likely a problem with my setup (dependencies, options, etc.) Because the code works for a different target, i.e. I can hit "https://api.binance.us/api" and get a 200 and response I expect. It's for the targets "https://api.exchange.coinbase.com" and "https://api.kucoin.com/api" that give me a 0 and empty response.
I am able to get real responses using Postman. When I std::cout the request headers to send the same exact request using Postman, I do get a response:
(Don't worry, I've modified the values.)
For Windows users there was a thread earlier this year about an issue with HTTPS requests, stemming from an issue with vcpkg. I am on macOS Big Sur (11.6.5) so this is not my issue.
Just 1 month ago there was a thread that seems relevant. 17 days ago they appear to have "fixed" this issue (PR #733)—so I have pointed CMake to the latest version of libcpr, 1.8.3:
include(FetchContent)
FetchContent_Declare(
cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
GIT_TAG db351ffbbadc6c4e9239daaa26e9aefa9f0ec82d) # 1.8.3
FetchContent_MakeAvailable(cpr)
target_link_libraries(myProgram PRIVATE cpr::cpr)
Still no go for me.
Here's what CMake outputs in case there's a hint in there I don't see:
-- Enabled curl SSL
-- curl version=[7.80.0]
-- Could NOT find LibSSH2 (missing: LIBSSH2_LIBRARY LIBSSH2_INCLUDE_DIR)
-- CA path only supported by OpenSSL, GnuTLS or mbed TLS. Set CURL_CA_PATH=none or enable one of those TLS backends.
-- Enabled features: SSL IPv6 unixsockets libz AsynchDNS Largefile alt-svc HSTS
-- Enabled protocols: HTTP HTTPS
-- Enabled SSL backends: Secure Transport
-- Configuring done
-- Generating done
Multiple threads say that versions before 7.81.0 work fine.
I also tried adding the option cpr::VerifySsl{false}, but get back
SSL peer handshake failed, the server most likely requires a client certificate to connect
I kind of don't think that's the right path anyway.
Does anyone have ideas? Any other output or thing to try that might be useful?
| Of course, it's the simplest thing that I didn't try. This warning tipped me off:
-- Could NOT find LibSSH2 (missing: LIBSSH2_LIBRARY LIBSSH2_INCLUDE_DIR)
I simply did a brew install libssl2 and it now works.
|
72,242,566 | 72,242,620 | Bounds of mesh are scaled by its world postion | I am trying to get the correct world postion and size of the bounds for a mesh, however the size of the bounds are scaled by the position of the mesh.
The bounds of the mesh itself are correct, but trying to get them into world space does not work.
Fotos: 1 and 2
The code for rendering the bounds:
void MeshRenderer::drawBounds() // FIXME: world bounds are scaled by the transforms position
{
glm::mat4 transformation = entity->transform.getTransformationMatrix();
bounds.center = transformation * glm::vec4(m_Mesh.bounds.center, 1.0);
bounds.size = transformation * glm::vec4(m_Mesh.bounds.size, 1.0);
bounds.updateCornerVertices();
bounds.draw();
}
void Bounds::updateCornerVertices()
{
glm::vec3 halfSize = size * 0.5f;
auto verts = GeomUtil::createLineCubeVertices(
center + glm::vec3(-halfSize.x, halfSize.y, -halfSize.z),
center + glm::vec3(-halfSize.x, -halfSize.y, -halfSize.z),
center + glm::vec3(halfSize.x, -halfSize.y, -halfSize.z),
center + glm::vec3(halfSize.x, halfSize.y, -halfSize.z),
center + glm::vec3(-halfSize.x, halfSize.y, halfSize.z),
center + glm::vec3(-halfSize.x, -halfSize.y, halfSize.z),
center + glm::vec3(halfSize.x, -halfSize.y, halfSize.z),
center + glm::vec3(halfSize.x, halfSize.y, halfSize.z));
m_Vertexbuffer.setData(&verts[0], 48);
}
void Bounds::draw() const
{
Renderer::shaderColor.use();
Renderer::shaderColor.setMat4("_ModelMatrix", glm::mat4(1.0));
m_Vertexbuffer.bind();
glDrawArrays(GL_LINES, 0, 48);
m_Vertexbuffer.unbind();
}
glm::mat4 Transform::getTransformationMatrix() const
{
glm::mat4 matrix(1.0f);
matrix = glm::translate(matrix, position);
matrix = glm::scale(matrix, scale);
matrix = glm::rotate(matrix, glm::radians(rotation.x), GeomUtil::X_AXIS); // TODO: Figure out how rotations work (quaternions)
matrix = glm::rotate(matrix, glm::radians(rotation.y), GeomUtil::Y_AXIS);
matrix = glm::rotate(matrix, glm::radians(rotation.z), GeomUtil::Z_AXIS);
if (entity->parent)
matrix = entity->parent->transform.getTransformationMatrix() * matrix;
return matrix;
}
| size is a vector, but not a position. So it has to be
bounds.size = transformation * glm::vec4(m_Mesh.bounds.size, 1.0);
bounds.size = transformation * glm::vec4(m_Mesh.bounds.size, 0.0);
|
72,242,679 | 72,243,569 | generic decorators for callable objects with conditional return | I want to write decorator functions for callable objects.
This is what I have now:
#include <utility>
template <typename DecoratedT, typename CallableT>
constexpr auto before_callable(DecoratedT &&decorated, CallableT &&callBefore)
{
return [decorated = std::forward<DecoratedT>(decorated),
callBefore = std::forward<CallableT>(callBefore)](auto &&...args){
callBefore(std::as_const(args)...); // TODO: ignore parameters?
auto &&res = decorated(std::forward<decltype(args)>(args)...);
return res;
};
}
template <typename DecoratedT, typename CallableT>
constexpr auto after_callable(DecoratedT &&decorated, CallableT &&callAfter)
{
return [decorated = std::forward<DecoratedT>(decorated),
callAfter = std::forward<CallableT>(callAfter)](auto &&...args){
auto &&res = decorated(std::forward<decltype(args)>(args)...);
callAfter(std::as_const(args)...); // TODO: ignore parameters?
return res;
};
}
template <typename DecoratedT, typename CallBeforeT, typename CallAfterT>
constexpr auto decorate_callable(DecoratedT &&decorated,
CallBeforeT &&callBefore,
CallAfterT &&callAfter)
{
return before_callable(after_callable(std::forward<DecoratedT>(decorated),
std::forward<CallAfterT>(callAfter)),
std::forward<CallBeforeT>(callBefore));
}
This code works while a decorated object has a return type which is not void. Error otherwise:
<source>:21:24: error: forming reference to void
21 | auto &&res = decorated(std::forward<decltype(args)>(args)...);
| ^~~
#include <iostream>
template <typename SumT>
void print(const SumT& sum)
{
const auto &res = sum(4, 811);
std::cout << res << std::endl;
}
int main()
{
struct {
int operator()(int lhs, int rhs) const
{
std::cout << "summing\n";
return lhs + rhs;
}
} sum{};
const auto &printBefore = [](const int lhs, const int rhs, const auto &...){
std::cout << "Before sum (args): " << lhs << " " << rhs << std::endl;
};
const auto &printAfter = [](const auto &...){
std::cout << "After sum" << std::endl;
};
std::cout << "Undecorated: ";
print(sum);
std::cout << "\nDecorated Before:\n";
print(before_callable(sum, printBefore));
std::cout << "\nDecorated After:\n";
print(after_callable(sum, printAfter));
std::cout << "\nDecorated Before and After:\n";
print(decorate_callable(sum, printBefore, printAfter));
struct {
void operator()() const {}
} retVoid{};
const auto &voidDecorated = decorate_callable(retVoid,
[](const auto &...){},
[](const auto &...){});
// voidDecorated(); // does not compile
return 0;
}
https://godbolt.org/z/x94ehTq17
What is a simple and optimization-friendly way of handling void return type from a decorated object?
How can I optionally ignore arguments for lambdas where I don't need them? Using variadic lambdas is a one way, but it is enforced on the user side.
Should I use decltype(auto) for return in function declarations?
| I'm using the SCOPE_EXIT macro from Andrei Alexandrescus talk about Declarative Control Flow. The trick here is that SCOPE_EXIT creates an object with a lambda (the following block) and executes the lambda in the destructor. This delays the execution until the control flow exits the block.
SCOPE_EXIT will always execute the code, SCOPE_SUCCESS will only execute the code if no exception is thrown and SCOPE_FAIL will execute the code only when an exception is thrown.
Note: the original decorator didn't execute the callAfter when an exception is thrown.
#include <utility>
#include <exception>
#ifndef CONCATENATE_IMPL
#define CONCATENATE_IMPL(s1, s2) s1##s2
#endif
#ifndef CONCATENATE
#define CONCATENATE(s1, s2) CONCATENATE_IMPL(s1, s2)
#endif
#ifndef ANONYMOUS_VARIABLE
#ifdef __COUNTER__
#define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __COUNTER__)
#else
#define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__)
#endif
#endif
template <typename FunctionType>
class ScopeGuard {
FunctionType function_;
public:
explicit ScopeGuard(const FunctionType& fn) : function_(fn) { }
explicit ScopeGuard(const FunctionType&& fn) : function_(std::move(fn)) { }
~ScopeGuard() noexcept {
function_();
}
};
enum class ScopeGuardOnExit { };
template <typename Fun>
ScopeGuard<Fun> operator +(ScopeGuardOnExit, Fun&& fn) {
return ScopeGuard<Fun>(std::forward<Fun>(fn));
}
#define SCOPE_EXIT \
auto ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) \
= ScopeGuardOnExit() + [&]()
template <typename DecoratedT, typename CallableT>
constexpr auto after_callable(DecoratedT &&decorated, CallableT &&callAfter)
{
return [decorated = std::forward<DecoratedT>(decorated),
callAfter = std::forward<CallableT>(callAfter)](auto &&...args){
SCOPE_EXIT {
callAfter(std::as_const(args)...); // TODO: ignore parameters?
};
auto &&res = decorated(std::forward<decltype(args)>(args)...);
return res;
};
}
|
72,243,396 | 72,270,720 | Cout Not Printing the Return Value from the function | I am trying the Infix to Prefix conversion and evaluation in C++. Someone here guided me and my converstion was resolved easily. But now I am having problems while evaluating it. The problem is that cout is not printing the return value from my function. Following is my code:
int PrefixEvaluation(string s)
{
stack<int> st;
for(int i=s.length()-1; i>=0; i--)
{
if(s[i] >= '0' && s[i] <= '9')
{
st.push(s[i] - '0');
} // if
else
{
int op1 = st.top();
st.pop();
int op2 = st.top();
st.pop();
switch (s[i])
{
case '+':
st.push(op1+op2);
break;
case '-':
st.push(op1-op2);
break;
case '*':
st.push(op1*op2);
break;
case '/':
st.push(op1/op2);
break;
case '^':
st.push(pow(op1,op2));
break;
default:
cout<<"Invalid"<<endl;
break;
} // switch
} // else
} // for loop
cout<<st.top()<<endl;
return st.top();
} // PrefixEvaluation()
int main()
{
cout<<"Prefix Evaluation: "<<PrefixEvaluation("+*^55/9/9*974")<<endl;
} // main
There is no error displayed. The console simply displays a blank screen. Please help. Thank you.
|
The console simply displays a blank screen.
That is a problem. Not so much because your program crashed, but because you do not know where it crashed. The traditional remedy for this is to use a debugger, but in this case diagnostic output could be illuminating. Furthermore, for a project like this (a fairly simple console program), I would recommend having diagnostic output from the start so that you can verify your code as you go along.
What would be good diagnostic output? The core of PrefixEvaluation() is the stack st, so add a diagnostic line before every push and pop. This diagnostic should show the pieces you are working with. For example, when pushing a digit:
std::cerr << "Push " << s[i] << '\n'; // Not converted to int
st.push(s[i] - '0');
(I use std::cerr because it is unbuffered, and because it is possible to separate cout and cerr output by redirecting one of them to a file.) Next example, when pushing an operation:
std::cerr << "Push " << op1 << " + " << op2 << '\n';
st.push(op1+op2);
Do this for all the operations, plus the two pops, and you should see why your program crashed:
Prefix Evaluation:
Push 4
Push 7
Push 9
Pop 9
Pop 7
Push 9 * 7
Push 9
Pop 9
Pop 63
Push 9 / 63
Push 9
Pop 9
Pop 0
Push 9 / 0
There you go – you hit a division by zero error. (Note: this is a reason to output the pieces without combining them. If the diagnostic was std::cerr << "Push " << op1/op2 << '\n'; then the diagnostic would unhelpfully crash.) To make your program stable (i.e. work even when the input is bad), you should check for zero before dividing. It's up to you to decide what the program should do in this case. Perhaps you simply want to inform the user and exit.
if ( op2 == 0 ) {
std::cout << "Division by zero!\n";
std::exit(1);
}
st.push(op1/op2);
Don't forget to remove (or comment out) the diagnostics before declaring the project done.
You could get the same result from a debugger. Let the debugger break execution just as the program crashes, then look at the values of your variables at that point. See that op2 is zero. It works, but if you want to find out why op2 is zero, you often have to do another run, breaking multiple times. In contrast, the diagnostic outputs let you quickly trace the source of the zero to 9/63 with just one run.
The speed of tracing the state of your stack is the reason I find diagnostics helpful in this situation. Each test case can be quickly checked not only for the correct final result, but also for the correct computations along the way. The computations stand out, so if you know which should have been performed, you can scan the output to make sure each is present. This lets you check for many potential bugs with not much effort.
|
72,243,827 | 72,251,462 | How can I create a Qt project without a UI/Designer file? | I'd like my project to be written programmatically instead of using Qt Designer.
EDIT:
I'm just asking for a template :P
| EDIT 2: I found out how, feel free to use the code down below:
#include <QtWidgets/QDialog>
#include <QtWidgets/QApplication>
class MyWindow : public QDialog {
public:
MyWindow(QWidget* parent = nullptr);
};
MyWindow::MyWindow(QWidget* parent)
: QDialog(parent)
{
setWindowTitle("MyWindow");
// Make widgets, etc...
}
int main(int argc, char** argv)
{
QApplication app(argc, argv);
auto win = new MyWindow;
win->show();
return app.exec();
}
|
72,243,858 | 72,244,312 | Delete empty lines in file | I'm trying to delete empty lines from a file. Currently it deletes all except for the one I add at line 35:out_file << data_vector[i] << "\n";
How do I exclude the last "\n" so it doesn't add a new line?
Here's the full function:
std::vector<std::string> Data::Data::ReadData() {
std::regex find_empty_line("^(\\s*)$");
std::smatch match;
std::string data, fel;
std::vector<std::string> data_vector;
std::ifstream in_file;
in_file.open(file_name);
if (in_file.is_open()) {
while (in_file.good()) {
std::getline(in_file, data);
data_vector.push_back(data);
}
}
in_file.close();
std::ofstream out_file;
out_file.open(file_name);
if (out_file.is_open()) {
for (int i = 0; i < data_vector.size(); ++i) {
if (!data_vector[i].empty()) {
out_file << data_vector[i] << "\n";
std::cout << data_vector[i] << "\n";
}
}
}
out_file.close();
return data_vector;
}
| It's best practice (on most Operating Systems), and expected by a lot of file processing tools, to have a newline at the end of every line in a file, so you normally wouldn't want to remove the final newline... consider it a line termination character with no line after it, rather than a line separator with an implicit empty line afterwards.
But, if you really must avoid that to work with the tools you're stuck with, then one easy way to avoid outputting it for the last line is to:
out_file << data_vector[i] << (i < data_vector.size() - 1) ? "\n" : "");
If you're unfamiliar with the ternary conditional operator, the basic form is:
conditional-expression ? expression-used-if-true : expression-used-if-false
Examples: (a <= b ? a : b) evaluates to the minimum of a and b. Read more here if you need/want.
Then, to make that work, we need to make sure the last line in data_vector is the last line of output, which it might not currently be because we have some empty line in there, so let's filter those out while populating the vector (no need to check good()):
while (std::getline(in_file, data))
if (!data.empty())
data_vector.push_back(data);
Knowing there are no empty lines in data_vector then lets us simplify the output loop:
for (int i = 0; i < data_vector.size(); ++i) {
out_file << data_vector[i]
<< (i < data_vector.size() - 1) ? "\n" : "");
std::cout << data_vector[i] << "\n";
}
(This does assume you don't want the empty lines in the returned vector, either...)
|
72,243,871 | 72,244,058 | Group of structured binding errors, pertains to neural networking | so i downloaded a library that hasnt been in use in years, for Neural Evolutionary Augmenting Topologies. Basically, a neural network that evolves. It came with many, MANY errors out of the box (somewhere around 20-30) and i managed to fix them all, except for these:
Error C3694 a structured binding declaration can contain no specifiers other than 'static', 'thread_local', 'auto', and cv-qualifiers
Error (active) E2828 type "float" has no components to bind to
Error (active) E0413 no suitable conversion function from "const std::tuple<float, float, float>" to "float" exists //this is dataset
Error (active) E2825 invalid specifier for structured binding declaration
this is the code where the errors are:
const int x1 = 1;
const int x2 = 2;
const int y = 1;
static constexpr int NumInput = 2;
static constexpr int NumOutput = 1;
static constexpr bool Bias = true;
static constexpr float ThresholdFitness = 0.80f;
static constexpr std::size_t PopulationSize = 100;
using ParamConfig = EvolutionNet::DefaultParamConfig;
using EvolutionNetT = EvolutionNet::EvolutionNet<NumInput, NumOutput, Bias, ParamConfig>;
using Network = EvolutionNetT::NetworkT;
using FitnessScore = EvolutionNet::FitnessScore;
for (float&& [x1, x2, y] : dataset) { // const auto, where all the errors are
network->setInputValue(0, x1);
network->setInputValue(1, x2);
network->feedForward<ParamConfig>();
const float output = network->getOutputValue(0);
assert(output >= 0.f && output <= 1.f);
score += 1.f - (std::abs(output - y));
}
i dont know anything about structured binding, im just trying to be able to use some Neural Networking for other projects. This thing isn't the best documented, but i believe that
this is only meant to be a for each loop, unless structured binding has something to do with that. How would one fix these errors? thank you.
| As the error message says only the auto type specifier (and cv-qualifiers) is allowed in a structured binding, so replace float&& with auto&&.
If you are uncomfortable with this syntax, you don't need to use it though. It is purely syntactical sugar. You can access the values of the individual elements of a std::tuple with std::get, e.g.:
for(auto entry : dataset) {
auto x1 = std::get<0>(entry);
auto x2 = std::get<1>(entry);
auto y = std::get<2>(entry);
//...
}
Or instead of auto you can write out the types if you like to. If you want references to the elements in the tuple instead of just their values, add &&/&/const where appropriate.
|
72,244,215 | 72,251,062 | OpenGL Compute Shader: Writing to texture seemingly does nothing | I've found a handful of similar problems posted around the web an it would appear that I'm already doing what the solutions suggest.
To summarize the problem; despite the compute shader running and no errors being present, no change is being made to the texture it's supposedly writing to.
The compute shader code. It was intended to do something else but for the sake of troubleshooting it simply fills the output texture with ones.
#version 430 core
layout(local_size_x = 4 local_size_y = 4, local_size_z = 4) in;
layout(r32f) uniform readonly image3D inputDensityField;
layout(r32f) uniform writeonly image3D outputDensityField;
uniform vec4 paintColor;
uniform vec3 paintPoint;
uniform float paintRadius;
uniform float paintDensity;
void main()
{
ivec3 cellIndex = ivec3(gl_GlobalInvocationID);
imageStore(outputDensityField, cellIndex, vec4(1.0, 1.0, 1.0, 1.0));
}
I'm binding the textures to the compute shader like so.
s32 uniformID = glGetUniformLocation(programID, name);
u32 bindIndex = 0; // 1 for the other texture.
glUseProgram(programID);
glUniform1i(uniformID, bindIndex);
glUseProgram(0);
The dispatch looks something like this.
glUseProgram(programID);
glBindImageTexture(0, inputTexID, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F);
glBindImageTexture(1, outputTexID, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_R32F);
glDispatchCompute(groupDim.x, groupDim.y, groupDim.z);
glMemoryBarrier(GL_ALL_BARRIER_BITS);
glUseProgram(0);
Inspecting through RenderDoc does not reveal any errors. The textures seem to have been bound correctly, although they are both displayed in RenderDoc as outputs which I would assume is an error on RenderDoc's part?
Whichever texture that was the output on the last glDispatchCompute will later be sampled in a fragment shader.
Order of operation
Listed images
The red squares are test fills made with glTexSubImage3D. Again for troubleshooting purposes.
I've made sure that I'm passing the correct texture format.
Example in RenderDoc
Additionally I'm using glDebugMessageCallback which usually catches all errors so I would assume that there's no problem with the creation code.
Apologies if the information provided is a bit incoherent. Showing everything would make a very long post and I'm unsure which parts are the most relevant to show.
| I've found a solution! Apparently, in the case of a 3D texture, you need to pass GL_TRUE for layered in glBindImageTexture.
https://www.khronos.org/opengl/wiki/Image_Load_Store
Image bindings can be layered or non-layered, which is determined by layered. If layered is GL_TRUE, then texture must be an Array Texture (of some type), a Cubemap Texture, or a 3D Texture. If a layered image is being bound, then the entire mipmap level specified by level is bound.
|
72,244,407 | 72,244,420 | There seems to be a problem with input of only 2 with a size of 6. Everything else seems to work exactly as expected. Why is this happening | I am starting to learn c++. So I want to try this using only recursion.Thank You for your help.
#include <iostream>
using namespace std;
int lastIndex(int arr[], int size, int num){
size--;
if(size < 0)return -1;
if(arr[size] == num)return size;
return(arr, size, num);
}
int main(){
int arr[11] = {1, 2, 2, 4, 2, 8};
cout << "Last Index = " << lastIndex(arr, 6, 2);
}
| i think you mean
return lastIndex(arr, size, num);
your code
return(arr, size, num);
is equivalent to
return num;
|
72,244,467 | 72,246,635 | What is the necessary lifetime for SetWindowTextA string parameter | I have a program that creates a std::string s on the heap and passes it to the SetWindowTextA(hWnd, s.c_str())
My question is how long does that string need to live? Does SetWindowTitleA copy the string or do I need to keep the string alive?
| Since my question was answered in the comments here is the the quick answer to anyone having the same question:
Yes SetWindowTitleA will create a copy of the passed in const* char. So the necessary lifetime is until the function returns. Then the passed string can be deleted, dropped or whatever.
|
72,244,685 | 72,244,795 | Why does a non-constexpr std::integral_constant work as a template argument? | My question is why the following code is valid C++:
#include <iostream>
#include <tuple>
#include <type_traits>
std::tuple<const char *, const char *> tuple("Hello", "world");
std::integral_constant<std::size_t, 0> zero;
std::integral_constant<std::size_t, 1> one;
template<typename T> const char *
lookup(T n)
{
// I would expect to have to write this:
// return std::get<decltype(n)::value>(tuple);
// But actually this works:
return std::get<n>(tuple);
}
int
main()
{
std::cout << lookup(zero) << " " << lookup(one) << std::endl;
}
Of course, I'm happy to be able to program this way. Moreover, I understand that std::integral_constant has a constexpr conversion operator. However, the parameter n to lookup is not constexpr, so I'm confused as to how a non-static method on a non-constexpr object (even if the method itself is constexpr) can possibly return a compile-time constant.
Of course, we happen to know in this case that the body of the conversion operator doesn't look at the runtime value, but nothing in the type signature guarantees that. For example, the following type obviously doesn't work, even though it, too, has a constexpr conversion operator:
struct bad_const {
const std::size_t value;
constexpr bad_const(std::size_t v) : value(v) {}
constexpr operator std::size_t() const noexcept { return value; }
};
bad_const badone(1);
Is there some extra property of methods that they are considered differently if they ignore the implicit this argument?
|
Of course, we happen to know in this case that the body of the conversion operator doesn't look at the runtime value, but nothing in the type signature guarantees that.
Correct. What you are missing is the fact that this doesn't matter.
When a function is called during constant expression evaluation, the compiler checks whether the function is constexpr. If it's not constexpr, then the enclosing evaluation fails to yield a constant expression.
But if it is constexpr, then the compiler executes its body at compile time and checks whether anything in its body disqualifies the enclosing evaluation from being a constant expression.
So in the case of the conversion operator of std::integral_constant, the compiler, executing its body at compile time, sees that it simply returns the value of the template parameter, which is fine.
If the compiler were evaluating a constexpr member function of some other type, which reads a non-const non-static data member of the object (and the object is not constexpr), then the compiler, at that point, would determine that the enclosing evaluation is not a constant expression.
It's a bit upsetting that when you see a function that has been declared constexpr, this tells you nothing about which evaluations of that function yield constant expressions, but that's the way it is.
|
72,244,716 | 72,248,865 | co_await is not supported in coroutines of type std::experimental::generator | What magic generator should I define to make the code below work?
#include <experimental/generator>
std::experimental::generator<int> generateInts()
{
for (int i = 0; i < 10; ++i)
{
co_await some_async_func();
co_yield i;
}
};
with MSVC I get compiler error:
error C2338: co_await is not supported in coroutines of type std::experimental::generator
EDIT1:
The error goes from its await_transform:
template <class _Uty>
_Uty&& await_transform(_Uty&& _Whatever) {
static_assert(_Always_false<_Uty>,
"co_await is not supported in coroutines of type std::experimental::generator");
return _STD forward<_Uty>(_Whatever);
}
| My understanding is probably that generator_iterator can't handle co_await because it requires the task to be suspended with co_yeld, see the iterator source code:
generator_iterator& operator++()
{
m_coroutine.resume();
if (m_coroutine.done())
{
m_coroutine.promise().rethrow_if_exception();
}
return *this;
}
Probably some async_generator should handle a situation when a task is suspended with co_await and the return value is not ready yet, so its operator++ also suspends in its turn and becomes asynchronous like this:
async_generator_increment_operation<T> operator++() noexcept
{
return async_generator_increment_operation<T>{ *this };
}
where async_generator_increment_operation is defined as follows:
template<typename T>
class async_generator_increment_operation final : public async_generator_advance_operation
{
public:
async_generator_increment_operation(async_generator_iterator<T>& iterator) noexcept
: async_generator_advance_operation(iterator.m_coroutine.promise(), iterator.m_coroutine)
, m_iterator(iterator)
{}
async_generator_iterator<T>& await_resume();
private:
async_generator_iterator<T>& m_iterator;
};
template<typename T>
async_generator_iterator<T>& async_generator_increment_operation<T>::await_resume()
{
if (m_promise->finished())
{
// Update iterator to end()
m_iterator = async_generator_iterator<T>{ nullptr };
m_promise->rethrow_if_unhandled_exception();
}
return m_iterator;
}
|
72,244,834 | 72,245,177 | Does header file import modules a standard thing? | C++ 20 modules guaranteed backward compatible so modules can import headers.
And Visual Studio introduced header file import modules,is this stardard or just a VS thing?
// MyProgram.h
import std.core;
#ifdef DEBUG_LOGGING
import std.filesystem;
#endif
| #include is a preprocessor directive that does a textual copy-and-paste of the text in the target file. Modules didn't change this. Textually copy-and-pasting import directives is still textual copy-and-pasting.
So yes, this is standard. Assuming your compiler implements them correctly.
That being said, it's probably not a good idea to have headers import things. If you want to build a collection of imports used by various files in your system, just build a proper named module and reap the benefits of the module build system. It's OK to export import modules.
|
72,245,002 | 72,245,551 | Calling a purely template lambda callback in C++20 | With C++20, we've gained templated lambdas, great!
[]<class T>(){};
Is it possible to call a lambda callback with a template parameter, but no argument to deduce it from?
For ex,
template <class Func>
void do_it(Func&& func) {
// Call lambda with template here, but don't provide extra arguments.
// func<int>(); ?
}
do_it([]<class T>(){ /* do something with T */ });
|
Is it possible to call a lambda callback with a template parameter,
but no argument to deduce it from?
This is probably what you want
template <class Func>
void do_it(Func&& func) {
func.template operator()<int>();
}
|
72,245,577 | 72,245,660 | strlen defaulting to '40'? | new programmer here starting with the basics.
I need to write a code that checks for the length of a string (line) and does things with it. I'm working on getting the length correct before I start with the next part of the task.
What's happening when I run the below code is strlen(string1) seems to be defaulting to '40' no matter what I enter?
I'm not sure what's going wrong!
Any help would be greatly appreciated.
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
char line, just, jline;
void prompt();
int main() {
cout << "Enter a line of text: " << endl;
char string1[line];
cin >> line;
char string2[] = "1234567890123456789012345678901234567890";
line = strlen(string1);
just = strlen(string2);
cout << "Length of string is: " << strlen(string1) << endl;
if ((strlen(string1)) > (strlen(string2))) {
cout << "Error, your line must be less than 40 characters" << endl;
}
}
| There are 2 problems with your code as described below:
Problem 1
In standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program:
char string1[line]; //not standard C++ because line is not a constant expression
Problem 2
Note that there is another problem with this. Since line is a global variable it will be statically initialized to 0. Thus char string1[line]; is actually equivalent to char string1[0];.
`But from array declarators documentation:
If the expression is a constant expression, it shall have a value greater than zero.
Thus, char string1[line]; is invalid for this reason also.
Solution
Better would be to std::string and as shown below:
#include <iostream>
#include <string>
int main() {
std::cout << "Enter a line of text: " << std::endl;
std::string inputLine;
std::getline(std::cin, inputLine);//take input from user and put it into inputLine
std::string var = "1234567890123456789012345678901234567890";
//----------------------------------------------------vvvvv----------->use size member function of std::string
std::cout << "Length of string is: " << inputLine.size() << std::endl;
if (inputLine.size() > var.size()) {
std::cout << "Error, your line must be less than 40 characters" << std::endl;
}
else
{
std::cout<<"valid input"<<std::endl;
}
}
Demo.
In the above snippet, we have used std::string::size to know the size/length of the std::string.
Also, the use of global variables should be avoided wherever possible. Refer to Are global variables bad?.
|
72,245,664 | 72,245,800 | using declval with reference types | I would like to understand how the assignment of int & to double below in conjunction with declval works? Is T deduced to something other than int & ?
#include <iostream>
#include <type_traits>
#include <utility>
template <typename T, typename U, typename = void>
struct assignment : std::false_type{};
template <typename T, typename U>
struct assignment<T, U, std::void_t<decltype(std::declval<T>() = std::declval<U>())>> : std::true_type {};
int main() {
// int &x = 23.4; // does not compile since x is not a const ref
static_assert(assignment<int &, double>::value); // why is this OK?
}
|
Is T deduced to something other than int & ?
T will still be deduced as int&, so std::declval<T>() = std::declval<U>() will be roughly equivalent to
int& f();
double&& g();
f() = g(); // assignment
Note that f() = g() is still well-formed because f() returns a reference to an already created int that can be assigned to a double. But if you do int& f() { return 23.4; }, then you will get a compile error because non-const lvalue references cannot be initialized by a rvalue. Instead, you can create a helper function which take T as its parameter type
template <typename T, typename U, typename = void>
struct initialize : std::false_type{};
template<typename T>
void accepted(T);
template <typename T, typename U>
struct initialize<T, U,
std::void_t<decltype(accepted<T>(std::declval<U>()))>> : std::true_type {};
This will make static_assert(initialize<int &, double>::value) fail because int& cannot be rvalue-initialized.
|
72,245,738 | 72,245,903 | concepts template argument deduction | The concept below has two template parameters but only one is specified during usage. Is T always deduced and InnerType always the parameter that needs explicit specification?
#include <iostream>
#include <string>
#include <span>
template < class T, class InnerType >
concept RangeOf = requires(T&& t)
{
requires std::same_as<std::remove_cvref_t<decltype(*std::ranges::begin(t))>, InnerType >;
std::ranges::end(t);
};
void print(const RangeOf<char> auto& seq) {
std::cout << "char seq: " << std::string_view(seq.data(), seq.size()) << std::endl;
}
int main() {
auto a_view = std::string_view("hello");
print(a_view);
}
| When you use concepts with templates as you did there, the type you are trying to constraint matches the very first type-argument. Everything else you specify comes after that in the order you specified. Here's a simplified example:
#include <concepts>
template <class T1, class T2, class T3>
concept ThreeTypes = std::same_as<T1, int> &&
std::same_as<T2, short> &&
std::same_as<T3, long>;
template <ThreeTypes<short, long> T>
void foo(T t) {
}
int main() {
foo(14); // OK
// foo(14.1); // Won't compile
}
See online.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.