question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
69,369,124 | 69,369,318 | Visual Studio Debugger, interpreting memory without bound or as different types? | I'm hoping to improve my debugging workflow by learning how to inspect values faster and with more clarity, but I'm having a big issue.
Visual Studio's C++ debugger makes some assumptions about my memory that aren't always true:
The "Type" of the value may not be how I want to see it's memory printed out
I may want t... | There are many questions here, sorry if I overlooked some.
For the type, Visual Studio's Watch window can cast. For example, if you have
float f = 1.23;
you can view it as float by just listing its name, or you can cast:
*(int*)&f 0x3f9d70a4 int
For the strings (and looking for memory around your variables) I sugg... |
69,369,380 | 69,375,820 | std::scoped_lock and mutex ordering | I'm trying to determine if std::scoped_lock tries to establish an ordering or mutex id to acquire locks in a prescribed order. Is not clear to me that it does it from a somewhat brief looking at a browsable implementation I found googling around.
In case it is not doing that, What would be the closest to standard imple... | The order for std::lock isn't defined until run-time, and it is not fixed. It is discovered experimentally by the algorithm for each individual call to std::lock. The second call to std::lock could lock the mutexes in a different order than the first, even though both calls might use the same list of mutexes in the s... |
69,370,273 | 69,370,405 | What is going on in this code. Can somebody explain me? | Can please someone explain me what is going on with this code. I mean I don't get it. Here is the source code.
#include <iostream>
using namespace std;
int main(){
int a = 0;
int c = 0;
for (int b = 1; b <= 144 ; b++){
a = b;
b = c;
c = a + b;
cout << a << "\n";
... | Well, I'll go by explaining it line by line.
Before main()
First, the include <iostream> imports the cout function to output to the terminal.
The using namespace std; is like a shortener and imports the standard library. Instead of std::cout, now you are writing cout.
During main()
The int main() calls the main functio... |
69,370,780 | 69,370,817 | Invalid types float[int] for array subscript in a for loop | I'm not familiar with c++. I've been doing a question. I need to pass the values from the first two functions(weight & height) to calcbmi function. There's an error in for loop in calcbmi function. Also it says "cannot convert 'float*' to 'float'" in main method calcbmi.
#include <iostream>
#include <cmath>
using nam... | Look at void calcbmi (float weight,float height, float bmi, int size) and you'll see that bmi is a float - not a float[], so you can't do bmi[i] = .... The same goes for weight and height.
The proper signature of the function should be:
void calcbmi (float weight[],float height[], float bmi[], int size)
Your program i... |
69,371,288 | 69,371,327 | Class's container get() member function usage vs copying | I have created a config class which loads configuration from a config YAML.
I have created vector containers for each type
// Pseudo Code
class config
{
private:
std::vector<std::string> c_name;
public:
config(yaml_file_path)
{
// Handles reading from yaml and loading data to c_name container.
... |
What would be better?( as code practice and execution time and/or memory space)
Your get_name() function does the container copy each time of the call. This is much expensive and do not required as long as you do not want to modify it outside the class.
I would suggest having one/ both of the overloads instead, so th... |
69,371,551 | 69,371,615 | Deduct template parameter fail while using if constexpr | I am trying to figure out how the sfinae concept works in C++. But I can't convince the object-type compiler if bool is true or false.
#include <iostream>
class A {
public:
void foo() { std::cout << "a\n"; }
};
class B {
public:
void ioo() { std::cout << "b\n"; }
};
template<class T>
void f(const T& ob, bool... | You need to let the bool parameter to be part of template. In your case, bool value is a run time parameter.
By adding the value as non-template parameter, your code can compile:
template<bool Flag, class T>
// ^^^^^^^^
void f(const T& ob)
{
if constexpr (Flag) {
ob.foo();
}
else
ob.i... |
69,372,318 | 69,373,730 | Qt Accidental activation of dragLeaveEvent,what should I do? | I have a QPushButton on a QScrollArea, the parent of the QPushButton is the QScrollArea. I drag the object to the QScrollArea and then to the QPushButton which always activates the dragLeaveEvent of the QScrollArea, I don't want this function to activate, what should I do?
| Thank you for your replies, I have solved the problem.
The method is very simple, just set the parent of the QPushButton to QScrollArea::widget() and it's solved.
|
69,372,464 | 69,372,561 | c++11 how to convert legacy class to template | I have a legacy class like:
class Wrapper{
public:
Wrapper(void*);
void* get();
};
I want to create a type safe wrapper like:
template<class T>
class Wrapper{
public:
Wrapper(T);
T get();
};
Stuff like this won't work because of C++11:
template<class T = void*> //Here I would need <>
class Wrapper...
... | If you do not want to change at other places, you can give your templated class a different name (because you don't even use it then in the first place):
template<typename T>
class WrapperT
{
public:
WrapperT(T t) : _T(t) {}
T get() { return _T; }
private:
T _T;
};
using Wrapper = WrapperT<void*>;
If you ... |
69,372,524 | 69,378,553 | Is it possible to get the type of the derived class from base class without using template in C++? | Suppose I have some unrelated classes, that I want all of them to have a pointer of themselves. Naturally I could use template to achieve this:
template <typename T>
struct Base {
// omitted the code to setup the variable
static T *ptr;
}
class Derived1 : Base<Derived1> {}
class Derived2 : Base<Derived2> {}
// To... | Based on the discussion, there is no template-less approach to CRTP. So I guess I'll stick to the current code.
|
69,372,954 | 69,376,724 | ecCodes (grib reading library) does not free the memory | I am using ecCodes library in my project, and I have encountered an issue that memory is not freed between reading the files.
The minimal example representing the problem is this (and is basically a combination of those two library API usage examples [1](https://confluence.ecmwf.int/display/ECC/grib_get_keys) [2]:
#inc... | So I contacted the library authors and realized that I have not read this example carefully enough.
For the ecCodes to correctly free the memory codes_handle should be deleted every time it is created (analogically to how you should free the memory every time you alloc it). Therefore in my example codes_handle_delete()... |
69,373,479 | 69,374,778 | How to get GCC-style line annotated error messages from Python interpreter? | When I compile a program using GCC and there is a part of the line that is incorrect, the error message I receive usually annotates the incorrect part. For example, an invalid header file leads to
prog.cpp:1:10: fatal error: iostreamm: No such file or directory
#include <iostreamm>
^~~~~~~~~~~
compilation te... | You do get such arrows for syntax errors, which is the closest equivalent to a compilation error for the Python implementation.
What you are asking for is arrows pointing to the sub-expressions that lead to raise (throw in C++). Neither GCC nor CPython at the moment do that.
|
69,373,619 | 69,373,659 | Called object type 'int' is not a function or function pointer | I am kinda new to C++, therefore, I don't know what is the cause of this error, I am trying to solve the edit distance problem recursively, however, this error shows up.
error: called object type 'int' is not a function or function pointer
return __comp(__b, __a) ? __b : __a;
#include <iostream>
#include <string>... | 3rd argument of std::min is the comparer, you might prefer the overload taking initializer_list:
return min({
distance(v, v2, a, b - 1) + 1,
distance(v, v2, a - 1, b) + 1,
distance(v, v2, a - 1, b - 1) + cost(v, v2, a, b)});
|
69,373,816 | 69,374,111 | Error: no matching function for call to 'sf::RenderWindow::draw(<unresolved overloaded function type>)'| SFML in C++ | I tried to create a Button class and use it with SFML, unfortunately, it produces the error:
no matching function for call to 'sf::RenderWindow::draw()'|
and a few more.
This is the code:
void onclic(){
cout << "Clicked";
}
class Button{
public:
string ButtonText;
Col... |
error: use of deleted function 'sf::RenderWindow::RenderWindow(const sf::RenderWindow&)'.
This tells you that you are trying to copy a sf::RenderWindow but a sf::RenderWindow is not copyable.
In the shown code, this is the offending copy:
void Butt(string ButtonText, Color color, int sizee, int x, int y,
fu... |
69,373,967 | 69,394,366 | QQmlPropertyMap in propery QQmlPropertyMap | I have a class that can create dynamic properties without Q_PROPERTY
//myclass.h
#include <QQmlEngine>
#include <QQmlPropertyMap>
class MyClass : public QQmlPropertyMap
{
public:
static MyClass& instance();
~MyClass() override = default;
Q_DISABLE_COPY_MOVE(MyClass)
private:
explicit MyClass();
};
QObje... | I found a solution. In myclass.h declare
Q_DECLARE_METATYPE(QQmlPropertyMap*)
In the constructor of MyClass
QQmlPropertyMap *subProperty = new QQmlPropertyMap(this);
subProperty->insert("SubTest1", "some text");
QVariant stored;
stored.setValue(subProperty);
insert("Test2", stored);
QTimer::singleShot(3000, [subProp... |
69,375,132 | 69,375,253 | How can I use different struct as template argument in a template function? | I am writing a template function like that:
template<typename T>
std::string EncodeData(int DataType, T Data, std::string ReadCommandID, std::string& ThisID);
The type T that I want to use is some different structs, for example:
struct A
{
int A_data;
bool A_data_2;
// etc.......
};
struct B
{
double ... |
What else I can do to slove this problom in one single function?
This is not possible under c++11 compiler. However, in C++17 you have if constexpr to do such:
template<typename T>
std::string EncodeData(int DataType, T const& Data, std::string const& ReadCommandID, std::string& ThisID)
{
if constexpr (std::is_sa... |
69,376,164 | 69,376,248 | Virtual derived functions and include loops | I am currently learning C++ as a student and I have a problem.
Here is my problem :
I have a class Point (described below)
I have a class Cartesian and Polar whom inherit from Point
I need to create a function to convert a Cartesian to Polar and a Polar to Cartesian. It needs to be callable directly from Cartesian an... | In these declarations of member functions
virtual void convert(Cartesian&) const = 0;
virtual void convert(Polar&) const = 0;
the names Cartesian and Polar are not yet declared.
You need either to introduce them as forward declarations before the class Point like
class Cartesian;
class Polar;
or to use elabor... |
69,376,628 | 69,376,965 | Creating the container of smart pointers by cloning elements of another container | I have a class, which supports cloning (via method clone). I have a bunch of its instances in a vector of std::unique_ptr.
Now, I want to create an std::set of same smart pointers from the above vector, ideally during its construction. The obvious design is as following:
#include <memory>
#include <set>
#include <vecto... | If you can use Boost, here is a possible solution:
SetOfA(const std::vector<std::unique_ptr<A>>& data) :
set_of_a(
boost::make_transform_iterator(data.begin(), std::mem_fn(&A::clone)),
boost::make_transform_iterator(data.end(), std::mem_fn(&A::clone)))
{ }
|
69,376,734 | 69,378,350 | Undefined Reference in self-built shared library with cmake | I am currently trying to utilize a self-built shared library. The Library FooBar utilizes the "Foo" Library to do some costly calculations. "Foo" however needs "Bar", the licensing library. It has been successfully cross-compiled when using the following CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(Foo... | There was an interface change in the "Bar" Library, which went unnoticed by me. Had to replace the header file and the library. Found the change by looking deeper into the library, using the nm -gDC xxxx.so command.
Thank you all for your help, the error was done by me...
|
69,377,635 | 69,409,388 | Debug C++ DLL with VSCode instead of Visual Studio | Im working on a project where i need to debug a C++ DLL/Lib. I have the DLL/PDB/H/Source files and i need a "Client" to invoque the DLL so i can debug some functions.
So far i have in Visual Studio a solution for a "DLL Client". To have it working i had to add my "Aditional Include Directories" (the .h file), the dll ... | So, i dont know if its the best solution but is the one i could find. Probably there is some way to improove this with the C++ extension of vscode.
launch.json (for debug)
{"configurations": [
{
"name": "(gdb) VCVarsall 32",
"type": "cppvsdbg",
"request": "launch",
"program": "${work... |
69,378,099 | 69,378,343 | std::unordered_map gives error when inserting using emplace function | I'm getting this weird error when inserting an element into std::unordered_map using emplace function but not if I use operator[] function overload. This is my code:
#include <iostream>
#include <unordered_map>
#include <memory>
class B {
public:
B() = default;
~B() = default;
};
class A {
public:
A() = ... | When you use emplace like mp.emplace("abc", A()); what you are doing is creating a temporary A, and that object is then copied/moved into the object that emplace is going to construct. When you did ~A() = default; in the class, that gets rid of the compiler supplied default move constructor, and the copy constructor i... |
69,379,215 | 69,380,333 | QTimer dont stop when windows is closed | I am currently starting on QTCreator. I have been asked to use QTimers in a particular context which is this:
We have an open window,
One or more QTimers are triggered and make things appear on the screen every x msec.
When we press "Escape" the window should close and everything should be reset to 0.
But here is the p... | Assuming you are using,
QWindow *qw = new QWindow();
QTimer *timer= new QTimer();
To solve the issue you need to connect destroyed() signal of QWindow to timer's slot stop()
So as soon as window is destroyed all registered timers will be stopped without explicit stop call. make sure you connect all timer instances. C... |
69,379,238 | 69,379,560 | Splitting template class definitions and declarations fails for nested templates | I know what I want, but I don't know how to tell the compiler what I want. I have split declarations and method definitions in .h and .cpp file, but the .cpp file gets included in the header, so all I did was separate declarations and definitions.
header file (avltree.h) - it includes the source file!:
template < class... | Your problem is the:
template < class KEY_T, class DATA_T >
class CNode;
Those KEY_T and DATA_T are unrelated to the one of CAvlTree.
clang and gcc even emit an error for those because of name shadowing (I don't know if VS does that too).
Due to CNode being a class template, the compiler expects you to provide templat... |
69,379,489 | 69,380,680 | State pattern error in C++ (no suitable constructor) | class Tool {
public:
virtual void mouseUp();
virtual void mouseDown();
virtual ~Tool();
};
class SelectionTool : public Tool {
void mouseDown() override {
std::cout << "SelectionTool icon\n";
}
void mouseUp() override {
std::cout << "Draw a dashed rectangle\n";
}
};
class ... | I suspect the polymorphism video you were using didn't use smart pointer types.
You can't just use std::shared_ptr<T> as if it were the underlying type. They have get and set interfaces, but they are not a seamless replacement. If they were, they couldn't do their job!
Using std::unique_ptr adds more conditions that yo... |
69,379,497 | 69,392,636 | C++ std::random and enum class | I've got a fussy question regarding more modern C++ "preferred" styles.
Say I want to use the contents of std::random in order to select a value from an enum class. How can I finagle that? We're talking some pretty basic stuff here, where the first selection works just fine, but Visual Studio scolds me (rightly) for us... | Both enum and enum class are rather problematic: they don't know their size, they can't be iterated etc. As a replacement, you can use std::variant with dummy types:
struct Left {};
struct Right {};
using Direction = std::variant<Left, Right>;
template<typename V, typename E, std::size_t idx = 0>
auto constexpr cast =... |
69,380,549 | 69,381,326 | Is cos(x) required to return identical values in different C++ implementations that use IEEE-754? | Is there any sort of guarantee - either in the C++ standard or in some other document - that C++ code computing cos(x) will produce identical values when compiled with g++, clang, MSVC, etc., assuming those implementations are using IEEE-754 64-bit doubles and the input value x is exactly equal? My assumption is "yes,"... | cos is a transcendental function. Transcendental functions are subject to the table-maker's dilemma. Informally, what this means is: let's say you come up with some iterative algorithm for approximating the cosine of an input value: for example, a Taylor series. When you run this iterative algorithm, you have to decide... |
69,380,561 | 69,380,915 | C++ Why diff EOF checks recommended for text vs numeric? | My textbook recommends using the member accessor method iStreamVar.eof() when dealing with textual data and while (iStreamVar) when dealing with numeric data.
Can someone please explain why it would matter?
Quote from book:
Using the function eof to determine the end-of-file status works best if the input is text. The... | Which method you use for determining the end of data depends on how you use it. My guess is, both methods which your textbook mentions are used wrong, so they fail in different situations. That's why it recommends using different methods in different situations.
The correct method is not trivial, and it depends on how ... |
69,380,733 | 69,394,822 | Weird behaviour of some specific Windows locales: why, and how to cope? | I wrote a simple C++ program to test available Windows locales.
#include <iostream>
#include <iomanip>
#include <locale>
int main(int argc, char* argv[])
{
const char* locName = (argc < 2) ? "" : argv[1];
std::locale loc (locName);
std::cout.imbue(loc);
std::cout << "Locale is " << loc.name() << '\n'... | There are two separate problems.
fre_fr and fr_FR.ISO8859-1 are not valid locale names as far as Windows is concerned. They are accepted by some third-party software (Python and maybe others) but one cannot use them in C setlocale or C++ std::locale. Weirdly, there seem to be two different failure modes when an invali... |
69,381,068 | 69,381,230 | Can't find Configuration Property in Visual Studio (C++) | I'm trying to use gcd function from #include <numeric> in Visual Studio 2019 (Community version). However, using namespace std, visual studio just says that "gcd" is undefined. Based on my research, I'm supposed to change the C++ version. However, in the normal settings I can't find "Configuration Properties" and right... | The gcd function was added in C++17. You probably haven't set the appropriate standard in your project settings. At least this is the exact issue you'll get when trying to use std::filesystem::... with an older C++ standard with Visual Studio. (The file system library was added in C++17 too.)
In the project properties ... |
69,381,645 | 69,381,756 | While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0 | While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
... | Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to bre... |
69,381,715 | 69,381,773 | My code is in an infinite loop and I need it taken out. It should output 5 rows with 3 columns with no duplicates in each row | So there is a bug in my code that puts it in an infinite loop. I need that taken out and I cannot find it for the life of me.
Here is the code:
#include <iostream>
#include <cstdlib>
const int MAX = 6;
const int SIZE_OF_SAMPLES = 3;
const int REP = 5;
bool inArray (int[], int, int );
void... | Within the while loop
while(cntr < n) {
r = rand(); //Get random number
r = r % (max + 1);
if (inArray(result, cntr, r)) {
result[cntr] = r;
cntr++;
}
}
the variable cntr is not incremented if the condition in the if statement evaluates to false. So if such a value of r that is absen... |
69,381,798 | 69,383,641 | Why do I get a seg fault when assigning a string pointer to a string pointer? | Consider the following simplified code:
typedef struct __attribute__ ((__packed__)) {
int numberB;
std::string strA;
} StructA;
typedef struct __attribute__ ((__packed__)) {
int numberB;
std::string strB;
} StructB;
char *ExampleClass::getBuffer(void){
char* mBuf;
int offset = 10;
return mBuf+of... | In getBuffer(), mBuf is uninitialized, but you add offset to it, so the pointer being return'ed is indeterminate. It certainly does not point at a valid StructB object, which is why the subsequent code in ExampleFunction() crashes when accessing B's members. Technically, this is undefined behavior, so anything can happ... |
69,381,876 | 69,479,217 | What is oneAPI and how does it compare to TBB? | We've been using TBB for years and I see when upgrading, we're taken to a oneAPI TBB page now instead. Does oneAPI TBB replace the traditional TBB? Are both versions being maintained or is the standalone TBB now deprecated?
Trying to determine which to migrate to. Looks to me like oneAPI TBB replaces TBB, as the TBB pa... | oneTBB is the next version of TBB. While they are almost source compatible, the binary compatibility is not preserved and some interfaces were either removed or changed. Consider the topics: Migrating from Threading Building Blocks (TBB) and TBB Revamp.
As for tbb.h, all oneAPI components reside inside oneapi/, i.e. it... |
69,382,472 | 69,382,682 | Algorithm to find minimum in array of point | I have a vector of values with the minimum, but which is non-decreasing after it and non-increasing before. Here is the example:
std::vector<int> arr = {90, 80, 70, 60, 55, 62, 71, 89, 104}
In the example I want to find 55.
I want to be able to find its minimum efficiently. O(n) complexity is not enough. Supposedely, ... | You can achieve O(lg n) complexity as follows:
int findTurningPoint(const vector<int>& v, int begin, int end) {
int mid = (begin + end) / 2;
if (v[mid - 1] > v[mid] && v[mid + 1] > v[mid]) {
return mid;
} else if (v[mid - 1] > v[mid]) {
return findTurningPoint(v, mid + 1, end);
} else if... |
69,382,578 | 69,384,088 | The element 'xsl:stylesheet' is used but not declared in the DTD/Schema | I'm trying to convert an XSL-FO document to HTML using the "fo2html.xsl" file from RenderX. That was the suggestion from this StackOverflow post:
Converting XSL-FO to HTML
I'm using the load() method, and it works on everything up until loading the "fo2html.xsl" file.
hr = pXMLDoc->load(vSource, &vbResult)... | You could try adding an XML declaration (see https://www.w3.org/TR/REC-xml/#sec-prolog-dtd) that indicates that the document is standalone:
<?xml version="1.0" standalone="yes" ?>
Alternatively, you might need to expand the entities yourself and get rid of the DOCTYPE declaration so there's no schema in the file.
|
69,382,679 | 69,382,718 | Will this create an object of Sales_data, or it will create variables inside the class? | I'm a 13 year old who's trying to learn C++. I bought C++ Primer and I came across something confusing for me:
struct Sales_data {/**/ } acum, trans, * salesptr = nullptr;
struct Salees_data {};
Salees_data accumm, transs, * salessptr;
I do understand what is a struct and class but I have no idea what this sta... | This defines a Sales_data struct and
acum and trans - Two Sales_data instances
salesptr - A Sales_data pointer, initialized to nullptr
struct Sales_data {/**/ } acum, trans, * salesptr = nullptr;
This defines a Salees_data struct and
accumm and transs - Two Sales_data instances
salessptr - A Salees_data pointer, u... |
69,382,829 | 69,421,968 | How to create a QML component from C++ with component scope instance hierarchy | I have a test QML file like this:
// TestMain.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
id: root
width: G_WIDTH
height: G_HEIGHT
readonly property real x_SCALE: width / G_WIDTH
readonly property real y_SCALE: height / G_HEIGHT
title: "Test Window"
visible: ... | This is due to missing QQmlContext.
I would need to create the QML instance passing the context:
item = qobject_cast<QQuickItem*>(
component.createWithInitialProperties(
props,
engine.contextForObject(wrapper)));
|
69,382,871 | 69,383,087 | Syntax misunderstanding and confusion | I am trying to read a file and also try the Gauss elimination process. One thing that is unclear to me is the syntax of the ifstream, when you want to read a file. In on previous example the syntax was like this:
ifstream filein;
filein.open(Filename=name of the file I will read from)
if(not filein.good()){
cout <<"The... | The code isn't the same because... there is almost always more than one way to write a program. The two examples are showing different approaches.
The first case uses the default constructor to create an ifstream object which, by default, doesn't open a file. Then, the ifstream::open() method is called to open a file. ... |
69,382,875 | 69,382,926 | lab.cpp:112:14: error: no member named 'display' in 'std::vector<Invitee>' | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Date {
public:
Date() {
day = 12;
month = 31;
year = 2021;
}
Date(int x, int y, int z) {
day = x;
month = y;
year = z;
}
void GetDate() {
cout << "Date: " << day << "/" << month << "/" << year <<... | list is a vector<Invitee> and has only the member functions defined by the std::vector class template, so you can't do list.display(). That member function doesn't exist.
You could however loop over the Invitees stored in list and call the display() member function on each element:
for(Invitee& inv : list) inv.display(... |
69,383,065 | 69,383,196 | How to use a template template argument from a member templated type alias of a struct | I'm trying to use a template template argument coming from a member type alias of a struct, but I can't find the right syntax:
struct A
{
template <typename T>
using type = int;
};
template <template <typename> class C>
struct B
{
// ...
};
B<typename A::type> b; // Does not compile: error: template argument... | A::type is a template, not a typename.
B<A::template type> b1; // OK
B<A::type> b2; // OK
|
69,383,144 | 69,383,286 | Code involving counting prime numbers stops working once a composite number is input. C++ | Code involving counting prime numbers stops working once a composite number is input. C++.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum=0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout <... | You set j = 0 outside of your d-while loop. A prime number does not change the value of j, but a composite number does. Once you put in a composite number and j is changed to be something other than 0, that value stays as it is for the next iteration of your do-while loop.
Solution:
move int j = 0; to be inside the do-... |
69,383,240 | 69,383,312 | Determining specific type to use inside "if constexpr" | I am trying to get a feel for using "if constexpr( expr )" and perform actions if a particular type is detected.
I am tinkering with the following bit:
#include <iostream>
#include <type_traits>
struct aT {};
struct bT {};
struct cT {};
constexpr aT atype;
constexpr bT btype;
constexpr cT ctype;
int main()
{
if ... | constexpr implies const in the context of variable declaration. Try this:
if constexpr (std::is_same<decltype(atype), const aT>::value)
std::cout << "I am type " << typeid(atype).name() << std::endl;
|
69,383,412 | 69,383,441 | Using auto in lambda function declaration | When can auto be used as the type specifier of a variable initialized with a lambda function? I'm try to use auto in the following program:
#include <iostream>
#include <functional>
class A
{
const std::function <void ()>* m_Lambda = nullptr;
public:
A(const std::function <void ()>& lambda): m_Lambda (&lambda... | A lambda expression does not result in a std::function. Instead, it creates an unnamed unique class type and that has an overload for operator(). When you pass your lambda to A's constructor, it creates a temporary std::function object, and you store a pointer to that temporary object. When A's constructor ends, tha... |
69,383,489 | 69,383,558 | SFINAE for unsigned type selection | I'm trying to use SFINAE to check if a type has an unsigned equivalent. While it seems to work for int and bool, it fails for float. From the error it seems a certain type is not defined. The question is if the template argument to enable_if is ill-formed, why isn't this removed from overload selection ?
#include <type... | You are using make_unsigned on an invalid type (see below) which makes the behavior undefined or program ill-formed. A better approach would be to check if it's an integer:
std::enable_if_t<std::is_integral_v<T>, bool>
From std::make_unsigned:
If T is an integral (except bool) or enumeration type, provides the membe... |
69,383,928 | 69,384,472 | Macro for detecting non-static non-type members in classes | In C++ Templates - The complete guide, 2nd edition, at page 434, a macro is defined to generate predicates testing the existence of a nontype memeber in a class:
#include <type_traits>
#define DEFINE_HAS_MEMBER(Member) \
template<typename T, typename = void> \
struct HasMemberT_##... | You are overlooking non-static member functions.
The primary use case of the traits created by DEFINE_HAS_MEMBER is to check for the existence of a particular method. To borrow from the terminology in the question, a range is defined by having begin() and end(). While the trait created by the original macro works, your... |
69,383,936 | 69,384,677 | Failing to compare two template template types with fixed number of arguments | I have a SFINAE template version of is_same for comparing template template arguments.
It generally works as expected on both templates with fixed and variadic number of template parameters:
namespace eld::util::traits
{
template<template<typename...> class ATT, template<typename...> class BTT>
struct i... | Neither should work: GCC has a bug of helpfulness that it considers an alias template to be the same as the underlying template if they’re sufficiently similar. The fixed/variadic mismatch, while still usable in practice, is enough for it to revert to conforming behavior.
|
69,384,631 | 69,385,288 | Extract a c++ variant type from a list of type names | I am designing a pipeline class that needs to extract a std::variant from a list of distinct types in a filter class. For example:
template <typename T>
struct Filter {
using type = T;
// ...
}
template <typename... Filters>
struct Pipeline {
// how to properly define the variant type?
// std::variant<Filte... | Based on Piotr's answer:
#include <variant>
template <typename T, typename... Ts>
struct unique { using type = T; };
template <typename... Ts, typename U, typename... Us>
struct unique<std::variant<Ts...>, U, Us...>
: std::conditional_t<(std::is_same_v<U, Ts> || ...),
unique<std::variant<Ts... |
69,384,923 | 69,384,973 | How to condense a struct in a class c++? | I have a a.h which has a class d. I am wondering how to make a shorthand way to use the struct 'a' inside of my class.
//a.h
class d
{
public:
struct a
{
int val;
}
};
//a.cpp
#include "a.h"
using d::a; //line with error
a methodName()
{
//does stuff
return object_of_type_a;
}
| what about this one
class d
{
public:
struct a
{
int val;
};
};
typedef struct d::a da;
|
69,385,934 | 69,386,265 | Forced to call the base constructor when using virtual inheritance although it will never be called? | I have a class Base which has a parameterized constructor and two classes Middle1 and Middle2 which virtually inherit from Base (in order to solve the diamond problem). In addition, class Foo inherits from Middle1 and Middle2.
Foo now calls the Base constructor explicitly and passes the parameter.
class Base
{
private:... | In virtual inheritance, the most-derived class has to directly call all of its ancestor constructors. Since Base doesn't have a default constructor, Middle1() and Middle2() can't compile if they can't pass an int& to Base().
However, in the code you have shown, there is no reason for Base() to take an int by reference.... |
69,386,167 | 69,391,142 | I'm using boost::filtered_graph, but the output of print_graph and write_graphviz differ -- any idea why? | I'm new to boost::graph (and boost really). I want to use boost::filtered_graph many times on the same original graph, and use the write_graphviz function to let me visualise the results. I think my understanding must be off though because the following code isn't doing what I think it should: to output the same graph ... | Your filter is random. And since you didn't retain any state to make it transparent or deterministic, the results are random. Simple as that.
Ironically, at the same time you managed to get completely deterministic results across runs because you fail to use random correctly (e.g. seeding the generator).
In your case, ... |
69,386,453 | 69,641,441 | Qt holds Ctrl to drag software elements into the File Explorer, but the File Explorer does not accept them | I can receive when I don't press Ctrl, I need to implement Ctrl pressed for copy and Ctrl not pressed for cut (move), how can I achieve this?
| I have solved this problem, the QDrag::exec() function has some parameters to choose from, I rewrite it as exec(Qt::ActionMask, Qt::MoveAction); and it solves the problem perfectly.
|
69,386,540 | 69,386,827 | How to implement a universal function for both sequence and associative container? | I am thinking to write a function that works both for sequence and associative container. That's something like
template<class C, class V = typename C::key_type>
bool has_val(const C& c, const V& v)`
Inside the function, I would like to
Check if class C has member function const_iterator find(key_type) const for co... | Use SFINAE to detect whether to use c.find():
#include <algorithm>
template <class C, class V, typename = void>
constexpr inline bool use_mem_find = false;
template <class C, class V>
constexpr inline bool use_mem_find<C, V,
std::void_t<decltype(std::declval<const C&>().find(std::declval<const V&>()))>> = true;
te... |
69,386,661 | 69,387,232 | Why do I get a error in leetcode submission but pass in IDE using the same code? | I am solving LeetCode question: 234. Palindrome Linked List:
Given the head of a singly linked list, return true if it is a palindrome.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
The number of nodes in the list is in the range [1, 10⁵].
0 <= Node.val ... | The error occurs when the Leet Code test system will try to release the memory used by the previous test case, before launching the next one.
Your code leaves the list in a state where it will run in cycles: the node that follows slow has been rewired by your code to point back to slow.
We can imagine how the Leet Code... |
69,387,447 | 69,407,723 | Unable to resize win 32 window | I'm trying to learn how to create a window in win 32. This is as far as I have got with it. The problem I'm facing is I'm unable to create a window that can be resized by the user. I'm hoping that someone could help me solve this newbie problem.
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lP... | It appears that you want to to idle processing, meaning having some tasks done for your directX application when no event are present in the event loop.
There are 2 different ways of doing that:
dedicate a separate thread for background processing. It adds the complexity of multiprocessing, but allows to do all the pr... |
69,388,002 | 69,388,277 | Overloaded function templates that differ only in their return types in C++ | It is well known that ordinary functions that differ only in their return type cannot be overloaded in C++.
But this limitation does not hold for overloaded function templates, for example:
int f(auto) { return 1; }
auto f(auto) { return 2; }
All compilers accept it, demo: https://gcc.godbolt.org/z/qj73Mzehd
Why does ... |
Why does the language make such exception for the templates?
You mean this?
signature [defns.signature.templ]
⟨function template⟩ name, parameter-type-list, enclosing namespace (if any), return type, template-head, and trailing requires-clause (if any)
Yes, the return type is there. It's what always made possible t... |
69,388,168 | 69,388,475 | Is there a way to detect compiler -fxxxx flags in C++ code in clang? | Is there a way to detect compiler -fxxxx flags in C++ code in clang?
I don't want to store the whole command line in binary, I want to test an individual option.
I want it to provide compilation error or warning if some flag is specified to avoid the code crashing at runtime.
| There is no good way of detecting the presence of the flag in C++ code.
The compiler does not communicate the presence of this flag to the code.
You could write some code that changes behavior based on the presence of the flag, but doing so is very fragile, and not guaranteed to actually work. Intentionally introducing... |
69,388,518 | 69,388,818 | weird compilation failure with overloaded const function and compiling with -pedantic | The code below fails to compile.
if I remove the bool foo(bool) overload, then the a.foo(&b); call compiles.
if I remove the const qualifier from bool foo(bool*) const; then the a.foo(&b); call compiles.
While writing the question I found out that without -pedantic to gcc it also compiles
I can't understand why...
stru... | First of all, pointers are implicitly convertible to bool. So an overload set between a pointer and a bool will be ambiguous unless one of the overloads represents a perfect match on all parameters.
To better visualize the issue I extracted the member functions to free functions, which is basically the same thing:
stru... |
69,388,612 | 69,388,848 | Conversion Constructor using map argument giving Errors | I made a small console program which has a class called Class_Room. I can make objects of school classrooms from it and store student names, roll numbers and ages in it. The student data are stored in a map. I wanted to make classroom object like this:
Class_Room class8C = {
{"student x", 2}, //2 for rollnumber... | There's a bit more to this answer, but I'll go with the thing that will solve your issue, then will try to explain some of the more interesting bits so that you learn something from it.
GIST: Your map is the other way around
// your map has keys of type int, values of type string
Class_Room(std::map<int, std::string> m... |
69,388,842 | 69,388,922 | How to pass an argument to a member function wrapped in std::function<void()>? | At first it seemed clear that I shouldn't be able to do this, but then I discovered that it can be done with free functions.
Here is an example where I pass void() functions from Child to Parent. The parent calls the function when their Frame comes up.
I have figured out the syntax to pass free functions with arguments... | Ditch the bind.
Use [this]() { f_Child1(); } and [this]() { f_Child(4); }.
Also, the free version can be just []() { f_Free2(4); }.
|
69,388,966 | 69,396,133 | Can't use defined type in C Python extension | I'm following the C Python extension tutorial to create new type.
I created the file custom.c, setup.py and added the following line to my CMakeLists.txt:
execute_process(WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} COMMAND ${PYTHON_BIN} setup.py build)
But when I run
Py_Initialize();
PyImport_AddModule("custom"));
PyR... | PyImport_AddModule("custom"));
See https://docs.python.org/3/c-api/import.html#c.PyImport_AddModuleObject; this looks in sys.modules for "custom". If it can't find it then it creates a new empty module named "custom". It does not search the path for files.
import custom
This looks in sys.modules for "custom". If it f... |
69,389,353 | 69,508,439 | How do you update a UTextureRenderTarget2D in C++? | I'm referenced @J. Rehbein's ask.
How do you update a UTextureRenderTarget2D dynamically in C++?
And use public modules ("Core", "CoreUObject", "Engine", "InputCore", "UMG", "GameplayTasks", "Landscape", "RHI", "RenderCore").
Why printed assertion failed log?
How fix assertion failed problem?
Please, teachers.
void AWo... | I want change URenderTargetTexture2D's texture. i'm tried how that use 2_DrawMaterial.
And i feel hardness from how convert UMaterialInstanceDynamic to UMaterialInterface.
So, next tried how that use ENQUEUE_RENDER_COMMAND. Blocked again.
So I posted a question.
Sorry and thanks everyone for read my awkward(weird?) que... |
69,390,666 | 69,391,033 | std::move behaves differently on different compilers? | I was experimenting with a simple code for calculating cosine similarity:
#include <iostream>
#include <numeric>
#include <array>
#include <cmath>
float safe_divide(const float& a, const float& b) { return b < 1e-8f && b > -1e-8f ? 0.f : a / b; }
template< size_t N >
float cosine_similarity( std::array<float, N> a, s... | What is happening is:
std::inner_product( a.begin(), a.end(), a.begin(), 0.f ) returns a temporary, whose lifetime normally ends at the end of the statement
when you assign a temporary directly to a reference, there is a special rule that extends the life of the temporary
however, the problem with: std::move( std::inn... |
69,391,091 | 69,391,714 | g++ is recognized by cmd but not by vs code | I'm trying to set c/c++ environment in my visual studio code. I have installed the mingw and set the environmental variable of the bin folder. However upon running a code in vs code, it shows the following error:
g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable progra... | You are using powershell terminal, If you dont know what powershell is or you dont need powershell, I recommend you to run Command prompt terminal (cmd). It's available in terminal menu here:
In powershell you can verify that g++ in PATH running this command echo $env:path, it's powershell equivalent of echo %PATH%
|
69,391,923 | 69,392,845 | CZMQ set send HWM / set receive HWM | Doesn't this have to work?
#include <czmq.h>
zsock_t *sockout = zsock_new_pub("inproc://a");
zsock_set_sndhwm (sockout, 20);
How to set HWM and/or BUF sizes?
UPDATE:
I added some more code and works in this context:
#include <string>
#include <czmq.h>
int main (void){
zsock_t *sockout = zsock_new_pub("inproc://... | I am answering my own question for a complete solution pub/rec
Publisher code:
#include <string>
#include <czmq.h>
int main (void)
{
zsock_t *sockout = zsock_new_pub("ipc://a");
zsock_set_sndhwm (sockout, 20);
zsock_set_rcvhwm (sockout, 20);
std::string data2send;
for (size_t i = 0; i < 1000; i++)... |
69,392,275 | 69,392,489 | Setting up eigen math library with visual studio | I have downloaded eigen and am trying to set it up with visual studio. My current file structure looks like this:
project:
src
Vendor
src:
main.cpp
Vendor:
Eigen
Here is my main.cpp file.
#include "../Vendor/Eigen/Core/Matrix.h"
#include <iostream>
int main()
{
Vector3f v;
}
I am getting hundreds of errors.
The ... | It is only a guess depending on your source structure but you copied the wrong sources:
You need to copy the Eigen directory into your Vendor not the src which is in Eigen directory. And then try to:
#include <Eigen/Core>
The structure of Eigen
Eigen
|--> .gitlab
|--> Eigen / you need to copy this full directory
... |
69,392,516 | 69,395,497 | Does not work _cgets. Identifier not found | I am trying to compile the following code in visual studio 2019:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
char* p;
buffer[0] = 3;
p = _cgets(buffer); // problem with _cgets
printf("\ncgets read %d symbols: \"%s\"\n",... | _cgets is no longer available, use _cgets_s instead:
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <string>
int main()
{
char buffer[5];
size_t sizeRead;
auto error = _cgets_s(buffer, &sizeRead);
printf("\ncgets read %zu symbols: \"%s\"\n", sizeRead, buffer);
... |
69,392,733 | 69,393,378 | an illegal memory access was encountered | I am a beginner at CUDA programming, writing a program composed of a single file main.cu which is shown below.
#include <iostream>
#include <opencv2/opencv.hpp>
#define DEBUG(str) std::cerr << "\033[1;37m" << __FILE__ << ":" << __LINE__ << ": \033[1;31merror:\033[0m " << str << std::endl;
#define CUDADEBUG(cudaError)... | As mentioned in a comment, your GPU function takes arguments by references.
__global__ void makeGrey(
unsigned char *&pimage,
const int &cn,
const size_t &total)
This is bad, passing a reference to a function means more or less that you're passing an address where you can find the value, not the value itse... |
69,393,323 | 69,394,678 | C++: initializing constexpr lambda to constexpr/non-constexpr variable | I'm reading the "C++ 17 The Complete Guide" book by Nicolai M. Josuttis and cannot understand the following example
auto squared1 = [](auto val) constexpr { // example 1. compile-time lambda calls
return val * val;
};
and the statement to it
If (only) the lambda is constexpr it can be used at compile time,
but squa... | The statement auto square1 = initialize a global variable, not even constant. This is a runtime variable that you can mutate, assign to and potentially other stuff.
You could very well initialize such variable like this:
auto returnMeALambda() {
int capture = rand() % 2;
return [capture](auto val) {
r... |
69,393,860 | 69,394,694 | Use of decltype Gives warning Reference to Local Variable | I am trying to understand how decltype works in C++ and so going through examples. Just when i thought i understood what it means, i tried to create examples to confirm that and i got something that i cannot understand. The example is as follows:
#include <iostream>
template<typename T>
auto func2(T a, T b) -> declt... |
But what i don't understand is that why are we not getting the same warning when i use return (b < a ? a:b);
How clever compiler warnings can be is entirely up to the compiler vendor; see e.g.
Warnings on sign conversion when assigning from the result of unsigned division
and when you catch a bug through a compiler... |
69,394,369 | 69,394,475 | C++ constexpr constructor initializes garbage values | I wanted a simple class which would encapsulate a pointer and a size, like C++20's std::span will be, I think. I am using C++ (g++ 11.2.1 to be precise)
I want it so I can have some constant, module-level data arrays without having to calculate the size of each one.
However my implementation 'works' only sometimes, dep... | I think the issue is your initialization is creating a temporary and then you're storing a pointer to that array after it has been destroyed.
const CArray gbl_arr{{3,2,1}};
When invoking the above constructor, the argument passed in is created just for the call itself, but gbl_arr refers to it after its life has ended... |
69,394,698 | 69,394,761 | Storing derived class to the vector C++ | I have problem with storing child class object to the vector. I have parent class
class IngameObject
{
protected:
bool clickable = false;
};
I have second class
class Character : public IngameObject
{
protected:
bool clickable = true;
};
Now, I am trying to create new instance of Character and stroe it to the... | Storing a derived class in a std::vector as you do is correct: the problem is not related with polymorphism or "storing derived class in a vector":
#include <iostream>
#include <vector>
class IngameObject
{
protected:
bool clickable = false;
};
class Character : public IngameObject
{
protected:
bool clickable... |
69,394,739 | 69,395,005 | Can I make conan usage optional to users of my library that uses conan? | Using conan to develop a library seems to force users of the library to also use conan. Is there a (standard) way I can replace the CONAN_PKG::protobuf reference in Targets.cmake with just protobuf?
Context
I am using cmake to build a static C++ library using protobuf, using conan to handle the protobuf dependency, ie
... | Yes, all the modern CMake integrations can achieve some level of transparent integration. First attempts are cmake_find_package and cmake_find_package_multi, but the most modern one are:
CMakeDeps: see docs generates xxx-config.cmake scripts, so consumers can do a normal find_package(protobuf ...)
CMakeToolchain: see ... |
69,394,803 | 69,394,963 | What are the parameters of the 0xC00000FD (Stack Overflow) error? | I've created a function which allocates an array, which is too big, on the stack (C++). The run results with this error:
Unhandled exception at 0x000000013F4DEBF7 in xxx.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000000000043000).
I've never seen the "parameters" section assigned to a particul... | The "parameters" are described in the documentation for the EXCEPTION_RECORD structure. Everything in that exception message came from EXCEPTION_RECORD, first ExceptionAddress, then a module name derived from ExceptionAddress, then ExceptionCode and its friendly name, and finally NumberParameters are read from Excepti... |
69,395,029 | 69,395,125 | Phantom \.txt file in windows | It seems like it is possible to create a file \.txt in windows that can be read, but I'm not able to access it any other way or see if it exists. This seems to only work for \.txt since I can't create other files with backslashes in it such as a\.txt
string filename = "\\.txt";
// make file
ofstream writer(filename);
... | On Windows, ofstream writer("\\.txt") creates a file named .txt in the root of the current drive. It is a perfectly valid file name.
ofstream writer("a\\.txt") tries to create a file named .txt in the a subdirectory of the current directory. The a directory must exist in order for it to succeed. Most likely it does not... |
69,395,155 | 69,395,231 | Is it portable to self move a std::string? | std::string s = "y";
s = "x" + std::move(s) + "x";
Send(std::move(s));
Microsoft STL implementation checks for this, but is it mandated by the standard?
It looks more clean than insert + append or two variables approach.
Note: I know I can do Send(std::move("x" + std::move(s) + "x")), but real code is not so simple.
| There's no self-move here. A self-move is something like this:
s = std::move(s);
which means
s.operator=(std::move(s));
In other words, when operator= is called, this points to the same string as the argument.
In your code, "x" + std::move(s) will be evaluated first, which returns a std::string prvalue. In other word... |
69,395,260 | 69,395,423 | Why I'm getting error: invalid operands to binary expression after overloaded += operand? | I'm trying to overload the += operator for a simple mathematical Vector class, to sum the elements of two vectors, like this:
vector1 += vector2
Part of Vector2D.h:
#ifndef _VECTOR2D_H_
#define _VECTOR2D_H_
class Vector2D
{
public:
Vector2D():x(0),y(0){}
~Vector2D(){}
/* All the mathematical operation .... | It looks like on this line you have two pointers
m_pVelocity += m_pAcceleration;
so you'd need to dereference them to use this operator
*m_pVelocity += *m_pAcceleration;
|
69,395,803 | 69,396,071 | Check if there's duplicate element in an container in compile time with C++20 | One simple way of doing this prior to C++20 is to do a nested loop:
template<typename Container>
constexpr bool has_duplicate(Container&& container)
{
for (auto it1 = container.cbegin(); it1 != container.cend(); ++it1)
for(auto it2 = container.cbegin(); it2 != it1; ++it2)
if (*it1 == *it2)
... | Godbolt uses libstdc++ by default, even when compiling with Clang, which is somewhat confusing.
Whether Clang should actually fully support linking towards libstdc++ or not, I cannot say, but e.g. the following Clang bug report highlights the same issue:
Bug 46746 - Clang can't compile libstdc++ ranges
Minimal exampl... |
69,395,818 | 69,901,405 | Use Boost as a git submodule with CMake | I want to use the Boost library for my C++ project (more precisely, I'm interested in the Boost Graph Library). I'd like it to be inside my git repository, as a git submodule, as it's done for every other dependency.
For example, if I want to start a project with fmt dependency as a git submodule, I do:
mkdir my_projec... | I found a solution which seems quite simple. You can just add_subdirectory() as shown for fmt.
The complete CMakeLists.txt file looks like this:
cmake_minimum_required(VERSION 3.17)
project(test_boost)
add_subdirectory(deps/fmt)
add_subdirectory(deps/boost EXCLUDE_FROM_ALL)
add_executable(test_boost main.cpp)
target_... |
69,396,146 | 69,396,193 | c++ - Destructor called on assignment | I'm still learning the basics of c++ so I may not have had the correct vocabulary to find the answer to my question but I couldn't find this mentioned anywhere.
If I have a class with a constructor and destructor why does the destructor get called on the new data when I am assigning to the class?
For example:
#include ... | Your object owns a raw pointer to allocated memory, but does not implement a proper copy constructor that makes an allocation and copies the data behind the pointer. As written, when you copy an object, the pointer is copied, such that now two objects point to the same address (and the old one that the just-assigned-t... |
69,396,459 | 69,396,719 | C++ default value initialization changes with input-output streams | I am researching an interesting behavior for two code segments, that give me unexpected behavior.
Describing The behavior
Code segment 1:
#include <iostream>
using namespace std;
int main()
{
long long n;
long long m;
// cin >> n;
cout << m;
return 0;
}
When I run this (for example in http... | C++ initialization is super complicated. However, this case is rather simple (confusing terminology aside ;). You are right that both m and n are default initialized. Though, immediately after that your interpretation is rather off. It starts with
This is expected and corresponds to the fact that the long long type ha... |
69,396,496 | 69,397,447 | Understanding the usage of the syntax "<DataType>" in C++ | I want to understand the usage of the "<DataType>" in C++.
As far as I read about, it is the syntax used for templates, which uses the specified data type for specialization of function or class instantiation.
Coming from python, I understand that all data types are by definition a class (correct me if it does not appl... | I'll use your examples:
std::vector<int> x;
x is a vector (dynamic-length array) that contains ints.
std::vector< std::vector<int> >& someVar;
someVar is a reference to a vector of vectors. The inner vectors holds ints. This would be a common way to make a reference to a two-dimensional dynamic array, where each row ... |
69,396,523 | 69,396,664 | Difference between boost::asio::strand and boost::asio::io_context::strand | I'd like to serialize http post requests using strand, to avoid overlapping writes to network.
My approach was to call the post method from the strand object with the callback that send the data as can be shown in the following code :
void Send(
boost::beast::http::request<boost::beast::http::string_body> &req) {
... | There's actually not much difference between them. In fact, they share a lot of code and that shows that one was created from the other.
See diff here (bosst 1.67).
However, boost::asio::strand es a class template originally intended to be used with asio::io_service:
template <typename Executor>;
class strand
{
public:... |
69,396,692 | 69,398,653 | Why can't I change the Qvariant value inside a QMap? | I'm trying to pass an object called QMap<QString, QVariant>* collect_row and then I'm going to fill the second element with a QVariant value. The current value in the second element is 0.
I'm using this code to connect to a database and then copy the row from the database into the QMap<QString, QVariant>* collect_row.
... | Use this code. Note that I changed the QMap pointer to reference. I believe the code should work though I have not tested it. But it is still super-ugly and very non-optimal. But I tried to do just minimal changes to your provided code.
DATABASE_STATUS Database::get_row_from(const QString& table_name, const QString& at... |
69,396,899 | 69,397,397 | Do I understand the semantics of std::memory_order correctly? | c++reference.com states about memory_order::seq_cst:
A load operation with this memory order performs an acquire operation, a store performs a release operation, and read-modify-write performs both an acquire operation and a release operation, plus a single total order exists in which all threads observe all modificat... | cppreference is only a summary of the C++ standard, and sometimes its text is less precise. The actual standard draft makes it clear: The final C++20 working draft N4681 states in atomics.order, par. 4 (p. 1525):
There is a single total order S on all memory_order::seq_cst operations, including fences, that satisfies ... |
69,397,010 | 69,397,101 | C++ problem where the value assigned to a variable is getting changed even though it hasn't been modified yet | Please help me with this strange problem where the input value is given as 4 (i.e. n = 4) and after a for loop the same value is getting displayed as 2, but why? It was not used anywhere (AFAIK) and it shouldn't get changed (I have no clue about it).
The original problem on HackerRank.
MY CODE >>
#include <cmath>
#incl... | int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
First of all, that's not even legal in C++. As a gcc extension to support C style VLA's, what is the value of n when the array declaration is seen? You have not read it yet!!
Instead, use... |
69,397,469 | 69,397,520 | Overloading prefix operator+ | I am trying to make a custom type in C++
I am trying to overload the + operator
class MyClass {
....
int operator+(int i) {
....
}
}
That works with
int main() {
MyClass MC;
count << MC+1;
}
How can I get it to work with 1+MC
| This is what I did.
^ cat Foo.cpp
#include <iostream>
class MyClass {
public:
int value = 5;
};
int operator+(const int value1, const MyClass &value2) { return value1 + value2.value; }
int main() {
MyClass myClass;
int newValue = 1 + myClass;
std::cout << newValue << std::endl;
}
^ make Foo
g++ ... |
69,397,543 | 69,397,741 | Passing functions with different number of parameters as argument in C++ | [Edited] Based on the feedback from comments, I have rephrased my question.
In C++, is it possible to create a function func that receives another function f as a parameter, if the number of arguments of f might change?
According to this thread, a syntax in C like
void func ( void (*f)(int) );
would help if I already ... | The Q&A you link is for C. In C++ you can pass a function pointer but not always this is the best alternative.
Your question leaves out the crucial part: How do you plan to call f in func when you don't know the number of parameters?
You can do type erasure and remove information of a type easily (eg number of argument... |
69,397,744 | 69,397,981 | Why does computing a formula with multiple unknowns not working? | I'm trying to compute the formula "V / I = R" in my program by asking the user to input values for V and I. Unfortunately my program does not compile and I'm not sure why.
#include <iostream>
using namespace std;
int main()
{
int V, I, R;
cout << "Please enter the voltage: " << endl;
cin >> V;
cout <... | C++ is not a system to solve linear equation, you must tell it what to do.
You need to replace:
V / I = R;
cin >> R;
with
R = V / I;
The knowledge you used, to flip the equation around, stays with you. The compiler needs instructions. Also note the = is not the symbol for equality. It is the symbol for assignment. It... |
69,398,068 | 69,398,117 | How can C++ differentiate between () and {} when init a vector | #include <iostream>
#include <vector>
int main() {
std::vector<int> v1(10);
std::vector<int> v2{10};
for (int x : v1)
std::cout << x << ", ";
std::cout << std::endl;
for (int x : v2)
std::cout << x << ", ";
}
makes
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10,
How can C++ distinguish bet... |
How can C++ distinguish between () and {} when initialising a class?
Because they are using different syntaxes, so the compiler can parse them differently and behave accordingly.
how can I create a constructor for both () and {} with different meanings?
Define 2 constructors, making one of them take a std::initiali... |
69,398,507 | 70,039,088 | GMP mpz_t variable being set with incorrect value | I've been working on the Euler 29 problem for a few days and am having difficulty getting the mpz_t type to work correctly. The objective is to iterate through a^b for values of 2 <= a,b <= 100 and count the nonrepeat values.
Using vector I was able to store the values using pointers in an array like so:
mpz_t a;
mpz_i... | I figured out that due to the way mpz_t variables work the mpz_set function does not work with a pointer to mpz_t type variables as a parameter.
Instead, I was able to get the program to work by assigning the mpz_get_str function to a string and pushing that to a vector of strings to check for repeat values.
mpz_t rop;... |
69,399,103 | 69,399,187 | character '\0' vs string "\0" | An online testing system expects my code to output the number 10.
It accepts:
printf("%d",10)
printf("%c%c\0", '1', '0')
printf("%c%c\0something", '1', '0')
printf("%c%c%s", '1', '0', "\0")
But rejects:
printf("%c%c%c", '1', '0', '\0')
printf("%c%c%c", '1', '0', 0)
putchar('1');putchar('0');putchar('\0');
putchar('1')... | Your online testing system is expecting to see the character sequence {'1', '0'}, but you are sending it the sequence {'1', '0', NUL }. You're trying to print the string terminator in addition to the string characters.
The string "10" is internally represented as the character sequence {'1', '0', NUL}, but when you di... |
69,399,702 | 69,425,956 | Colstore vs Rowstore for in-memory algorithms | I'm familiar with using a column- vs a row-store for how a databases internally persists data to disk. My question is whether, for a dataset is entirely in memory, and there's no storage to disk, if the row- vs column- orientation makes much of a difference?
The things I can think of that may make a difference would be... |
I'm familiar with using a column- vs a row-store for how a databases internally persists data to disk. My question is whether, for a dataset is entirely in memory, and there's no storage to disk, if the row- vs column- orientation makes much of a difference?
A lot depends on the size of the dataset, what the contents... |
69,400,540 | 69,410,264 | C++ boost-asio-network in async callback, which one is better ? using lambda or boost::bind() | C++ lambda made me confusing.
bind functions for async read.
template<typename T>
class connection
: public boost::enable_shared_from_this<connection<T>>
, boost::noncopyable
{
public:
using err = boost::system::error_code;
protected:
boost::asio::ip::tcp::socket socket_;
...
// completion function
//... | You already figured out that this needs to be explicitly captured in addition to the shared pointer, the latter just for the lifetime guarantee.
However your original question is slightly more interesting than you knew! There's a subtle difference between lambda and bind expressions. If you use bind to bind to a generi... |
69,400,565 | 69,400,628 | A simple operator overloading program in C++ on codeblocks. Got an error at line 19. The same program runs perfectly on Turbo C++ | Got an error on line 19:
error : no 'operator++(int)' declared for postfix '++' [-fpermissive]
#include<bits/stdc++.h>
using namespace std;
class sample
{
int x,y;
public:
sample(){x=y=0;}
void display()
{
cout<<endl<<"x="<<x<<" and y= "<<y;
}
void operator ++(){x++;y++;}
};
int main()
... | TURBO C++? Haven't heard that name in a LONG time. That is a compiler from an era before C++ was even standardized, and is not representative of C++ anymore.
Prefix increment and post-increment are different functions. You can't just overload one and expect both to work.
Also your signature is wrong. It should retu... |
69,400,617 | 69,400,688 | How to insert std::vector or array to a std::forward_list without using any loop? | forward_list<int> listOne;
forward_list<int> listTwo;
vector<int> arr = {2,4,3};
forward_list<int>::iterator it;
In the code mention above, I want to insert a std::vector in listOne and I tried using insert_after function.
it = listOne.begin();
listOne.insert_after(it,arr);
But it didn't work.
I want to know that, ... | You could use a std::copy with std::front_inserter
copy(arr.rbegin(), arr.rend(), front_inserter(listOne));
Working demo
|
69,400,860 | 69,402,941 | Many folders project Makefile | I have the following project structure:
common
|-- foo.cpp
|-- foo.h
exercise_1
|-- main.cpp
|-- bar_1.cpp
|-- bar_1.h
exercise_2
|-- main.cpp
|-- bar_2.cpp
|-- bar_2.h
...
How can one organize Makefile to build such project from the main directory e.g.:
make exercise_10
So that this command would build object files ... | If you use GNU make you could define a macro to build any of your exercises. Something like the following:
EXERCISES := $(wildcard exercise_*)
MAINS := $(addsuffix /main,$(EXERCISES))
.PHONY: all
all: $(MAINS)
common-objs := $(patsubst %.cpp,%.o,$(wildcard common/*.cpp))
common-headers := $(wildcard ... |
69,401,556 | 69,401,636 | Is cin.get() reading multiple digit characters at once? | We were asked to write a simple C++ program by our teacher to add two numbers in the following format:
input: 12 14
output: m+n = 26
The program must also work for other inputs in the form:
input: Hello please add 12 and 14 !
output: m+n = 26
The solution that was given was:
#include <iostream>
using namespace s... | Yes, cin.get() will read only one character at a time.
The important part, where the number is actually read, is 4 lines below: cin>>m;. This will consume as many digits as possible and store the resulting integer in m.
Some more details:
// example with input 524 42
while(cin.get(ch)) // extract one character ... |
69,401,709 | 69,404,274 | Conditional jump or move depends on uninitialized value(s) with strcat in for loop | I have a file containing the strings of 3 chromosome, which I want to concatenate into one genome. And then I have to access this concatenated string across multiple threads (I use pthread_t). To to this I have to use pthread_mutex_lock when extracting the data, then I use strcat to concatenate the data which are extra... | Using Valgrind to locate the problematic code
The "Conditional jump or move depends on uninitialised value(s)" message means Valgrind has determined that some result of your program depends on uninitialized memory.
Use the --track-origins=yes flag to track the origin of the uninitialized value. It might help you findin... |
69,401,716 | 69,401,900 | Is optimizing small std::strings wiht c-style functions often pointless? | Let's say we've got the following piece of code and we've decided to optimise it a bit:
/// BM_NormalString
bool value = false;
std::string str;
str = "orthogonal";
if (str == "orthogonal") {
value = true;
}
So far we've come up with two pretty simple and straightforward strategies:
/// BM_charString
bool v... | For small strings, there's no point using dynamic storage. The allocation itself is slower than the comparison. Standard library implementers know this and have optimised std::basic_string to not use dynamic storage with small strings.
Using C-strings is not an "optimisation".
|
69,401,732 | 69,402,214 | Ambiguity error accessing equality comparison operator in G++ | In case of multiple inheritance if all parent classes have their own equality comparison operator ==, and the child class has a (friend) function operator ==, as in the example:
struct A {
bool operator ==(const A&) const = default;
};
struct B {
bool operator ==(const B&) const = default;
};
struct C : A, B ... | Indeed the global operator operator==(const C&, const C&) has priority. However the compiler "want to know" all the possibilities in order to decide: In other words: as soon as you try to use the operator== the compiler requires you to have no ambiguities, even if the required alternative is not between the ambiguous o... |
69,402,374 | 69,431,491 | MDI Tab names changing back... / Taskbar Preview not selecting | I'm creating an MDI application, WITHOUT the Document/View.
I am also using MDITabbedGroups.
I had a problem, because I have to name may tabs dynamically (names are in the DB and user created), meaning I couldn't use resources for the names.
I create all the tabs as 'Program name', then rename them by calling the follo... | After much hunting around in the AFX source files, I found this:
CString CMDIChildWndEx::GetFrameText() const
{
ASSERT_VALID(this);
CString strText;
GetWindowText(strText);
return strText;
}
& this
void CMDIFrameWnd::OnUpdateFrameTitle(BOOL bAddToTitle)
{
if ((GetStyle() & FWS_ADDTOTITLE) == 0)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.