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 |
|---|---|---|---|---|
66,935,386 | 66,935,445 | c++ weird scope in if statement | When I declare anything inside an if statement it doesn't propagate out of it, moreover, if I have a variable outside, and i redeclare it inside if statements it lost it once the code ends the statement, how can I manage to globalize the scope of an if statement.
| Redeclaring a variable in an inner scope creates a new variable.
#include <iostream>
int main()
{
int i = 1;
if (true)
{
int i = 42; // variable is re-declared
} // lifetime of inner i ends here
std::cout << i; // expected output 1
}
You can reference a variable in an inner scope... |
66,935,504 | 66,935,589 | How to set length of array alias with scoped enum template argument without casting | My goal is to create an alias for a std::array that sets the length based on an enum template argument. I managed to make it work relying on the conversion of the enum, as seen in my code below.
#include <array>
#include <iostream>
enum class StateRepresentation
{
Log2 = 1,
One_hot = 16
};
template <StateRepr... | You can use conditional_t to switch on which member of the enum class is used for instantiation:
template <StateRepresentation R>
using State = std::conditional_t<R == StateRepresentation::Log2,
std::array<int, 1 * 16>,
std::array<int, 16 * 16>>;
This a... |
66,935,515 | 66,935,826 | Dont know how to fix: expected primary-expression before '.' token | I'm currently just starting off coding in c++, the current project I'm working on is making an in-console chess engine type thing. The function below is supposed to check if a particular square has a piece on it, and if so, if the piece is white. Board.grid is a 2D array of strings where " " would be an empty square,... | The symbol Board is a type not an instance. In C++ you can't use the . operator to access type members, only members of objects.
The simple solution is to create a Board objects:
struct /* Anonymous structure */ {
string Grid[8][8] =
{
{"bR1", "bN1", "bB1", "bQ1", "bK1", "bB2", "bN2", "bR2"},
{"... |
66,935,701 | 66,935,762 | Address of stack memory returned when overloading operator [ ] | I'm encountering some issues with overloading the [] operator for a problem in class. This is the function for the overloading:
const char* Person::operator[](const char* str)
{
if (strcmp(str, "name") == 0)
return reinterpret_cast<const char *>atoi(name);
if (strcmp(str, "age") == 0)
{
cha... | You are taking an address to a temporary (that is located on the stack), that will leave the returned pointer dangling almost immediately.
I would very strongly suggest using std::string for strings, do not write C++ just as C with classes.
Then return by std::string by value here. Bad C-like alternative is to allocate... |
66,935,841 | 66,936,041 | If there a way to test a char to a class of user define character? | Is there any way to define a type and do the following?
char c = 'a';
if (c == BRASSECHARTYPE)
{
// do something if c is one of the following char [{()}]
}
| There is lots of ways to do it:
Simple function:
bool isOneOfChars(char ch, std::initializer_list<char> chars)
{
return std::find(std::begin(chars), std::end(chars), ch) != std::end(chars);
}
bool isBrace(char ch)
{
return isOneOfChars(ch, {'[', '{', '(', ')', '}'});
}
Fancy template with fold expression:
tem... |
66,935,934 | 66,935,973 | Abstract Classes, Polymorphism C++ - Calling pure virtual method in another function | I have an abstract base class defined like this:
class NodeSubElementEnforceType {
public:
virtual void getType() = 0;
void performChecks() {
getType();
// other things ......
}
};
I will have a bunch of derived classes that will each have their own implementation of... | Yes, it would work. But storing raw pointers inside a vector is not a good idea, use smart pointers or boost pointer container if that’s not an overkill.
|
66,936,165 | 66,964,522 | any elegant way to get c++20 coroutine handle to the outside? | we know that c++20 coroutine suspend and return caller after using co_await awaitable, if we want to resume this coroutine, the only way is to get the coroutine handle from awaitable object function void await_suspend(std::coroutine_handle<> cont) const and then use handle.resume() to resume coroutine, is there any wa... | well, I find a better way to resume coroutine from the caller by reference to c++23 std::generator, shown as below:
struct Result{
//add
Result(promise_type* obj):promise_type_ptr(obj){}
//add
void resume(){
promise_type_ptr->resume();
}
struct promise_type {
// mod
Result get_return_object() {... |
66,936,204 | 66,936,351 | Workaround for PyByteArray_AsString from bytearray that contains null characters | I've got some buffer of data, a PyByteArray, that I want to extract the char * from. I want to then take that char* and create a stringstream from it.
void CKKSwrapper::DeserializeContext(PyObject *obj) {
// Is a PyByteArray object as determined by https://docs.python.org/3/c-api/bytearray.html#c.PyByteArray_Check
... | If you read the description of all the PyByteArray functions, you will find a useful function called PyByteArray_Size. This gives you the size of the array.
std::string has many constructors. One of them constructs the std::string from a beginning and an ending iterator. A pointer meets those qualifications. So, you sh... |
66,936,243 | 66,936,537 | C++ opening a window without libraries | I am new to C++, and I would like to know for future reference:
Is it possible to open a (cross-platform compatible) window without any libraries (such as Win32 API, GTK, QT, etc)?
If not, can someone explain why?
And how can an OS launch a GUI? Even if it does so with assembly, C++ can do what assembly can do (from wh... |
Is it possible to create a GUI without API calls, or any external libraries?
No 1.
1: unless, for example, you are writing your own display driver and have direct access to video hardware.
If not, why
Every OS handles UI programming differently. You must use the UI APIs that are provided by each OS that your p... |
66,936,424 | 66,937,322 | C++ Error project.cpp:11:20: error: no match for 'operator[]' (operand types are 'std::__cxx11::list<int>' and 'int') | Ok, so I'm relatively new to c++ and I'm trying to self-teach with youtube tutorials and websites. What I'm trying to do is to make a list, then add things inside the list. That worked fine until I tried to get something inside the list. I get the error project.cpp:11:20: error: no match for 'operator[]' (operand types... | In c++, the STL list doesn't support operator[]. The reason for this is that it is implemented as a liked list. This means that each item only knows where the elements before and after it are. The list would look something like this.
Instead of accessing a given part of the list through the brace notation, you want to ... |
66,936,702 | 66,936,746 | Thread Constructor Initialization C++ | I have been attempting to write a simple program to experiment with vectors of threads. I am trying to create a thread at the moment, but I am finding that I am running into an error that my constructor is not initializing properly, with the error that there is no matching constructor for std::thread matching the argum... | The problems you're encountering are because std::accumulate is an overloaded function template, so the compiler doesn't know what specific function type to treat it as when passed as an argument to the thread constructor. Similar problems arise with your thread_sum function because of the auto parameters.
You can choo... |
66,937,896 | 66,937,912 | C++ Stack Unable to process | I am having an error in my program (Error: undefined reference to `customerRent::customerRent()') Appreciate your help and advice. Thank you
class customerRent: public customerQueue, public videoList {
private:
int custRentVideoID;
int custRentCustID;
// stack<customerRent> custRent;
public:
/*custome... | you might want to consider change your default constructer from
customerRent(); //constructor
to
customerRent() //constructor
{}
or as @prehistoricpenguin rightly pointed out change to
customerRent()=default; // for c++11 and above
this declaration customerRent cStack; is looking for a default constructor which i... |
66,938,060 | 66,990,204 | Setting up the card position on the window screen with class function | I don't want to hardcode the position for the card to be in the middle of the screen and we did a project like this without class. So though would be easy to just put what I did to make the card to be in the center but no matter what I did, the card stays at the top left corner.
I even notice at times if I put the rect... | It is tricky to help you without full code, cause I don't know how exactly did you want to use setPostioning.
After a small workaround, It finally appeared in the center of the screen.
Feel free to comment, if my example still doesn't satisfy your needs.
In the header file I added a reference to sf::RenderWindow, to us... |
66,938,205 | 66,938,510 | Segmentation fault in C++ before entering main | This is quite common question and I tried reading the solutions but none of them seem to fix my problem. Here is the code I wrote which I know is quite a mess because I am a newbie at C++.
#include<iostream>
#include<string>
#include<iomanip>
#include<set>
#include<queue>
#include<cmath>
#include<algorithm>
#include<ve... | You’re allocating over two million std::vectors in your code in stack. Usually the stack isn’t very big so that most definitely will go over the reserved space and cause issues. The allocation for local objects happens before any code in the function is run so it will look like it crashes in the function but before any... |
66,938,233 | 66,938,320 | Can a pointer be set to null if new operator fails? | If a pointer is allocated with memory by the new operator and the allocation isn't successful, is it safe to set the pointer to nullptr in the catch block?
foo* var;
try {
var = new foo[size];
}
catch (std::bad_alloc& e) {
std::cout << "Error: " << e.what() << "\n";
var = nullptr;
}
| An Alternate approach :
By default, when the new operator is used to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown.
But when nothrow is used as argument for new, it returns a null pointer instead.
Therefore in your case you can also use the below syntax.
foo* var = new (s... |
66,938,439 | 66,938,552 | The mystery of C++20 concept boolean-testable | C++20 introduces a comparison concept boolean-testable, but I noticed its italics and the hyphens in the middle, indicating that it is for exposition-only, and since there is no so-called std::boolean_testable in <concepts>, we cannot use it in our own code.
What is the purpose of this exposition-only concept? And why ... | Its purpose, like all exposition-only concepts, is to simplify the specification in the standard. It's simply a building block for specifying other (potentially user-facing) concepts without needing to repeat the thing the concept models. Of note, it appears in the specification of another exposition-only concept
templ... |
66,938,471 | 66,938,791 | how to have conditions in displaying a text from a text file using c++ | i have this school project where i have this text file:
VIDEO ID : 1
MOVIE TITLE : TITANIC
GENRE : ROMANCE
PRODUCTION : PARAMOUNT PICTURES
NUMBER OF COPIES: 3
VIDEO ID : 2
MOVIE TITLE : IT
GENRE : HORROR
PRODUCTION : NEW LINE CINEMA
NUMBER OF COPIES: 0
VIDEO ID ... | I would create a class to store information about one movie and add a member function to be able to read one movie from an istream (like an ifstream). Since the file contains the field names too, I'd also add a function to strip that part away. Example:
#include <sstream> // std::istringstream
struct Movie {
int i... |
66,939,375 | 66,940,350 | How to use a derived functor in element wise operation in Eigen | I wanted to generalised all the custom element-wise functors that I need deriving all of them from a common base class that provides the operator() method. This way I can simply declare a variable pointing to the base class and when I call the operator() method each derived class has his own implementation. Unfortunatl... | By default unaryExpr takes its argument by value, which means that it will try to copy *B. Because of the type it will call the copy constructor of Base.
This behavior is commonly not what people want and is described as "Object slicing" when it affects data members (though no data is lost in this case, it's just not u... |
66,939,669 | 66,960,509 | Creating a variable like x = func(); function call and var creation order defined? | void f()
{
auto x = func();
int y = func();
auto z = f1() * f2() + static_cast<int>(f3());
}
I believe it should be defined that call to the func will always happened first, before memory allocation for x, for the case with auto, but couldn't found info about it.
Is it so?
And is it defined for the case wh... | Evaluation of the initialization expression (func() or f1() * f2() + static_cast<int>(f3())) definitely happens only when the particular line of code is reached.1
Memory for the variable may be obtained (aka "allocation") at any time earlier... however there's no way to use that memory prior to the definition because u... |
66,939,771 | 66,963,218 | How to implement properties in C++ concepts | The C++ concepts are a relatively new idea in C++.
But we have few available explanation as to how it works.
struct contain {
public:
using Tin = int;
using Tout = int;
Tout sqr(Tin x)
{
return x * x;
}
contain(int _x) : x(_x)
{
}
int get_x() const
{
return x;
}
private:
int x;
};
int ... |
That is we want to have a concept that tests that contain contains Tin, Tout and a member function Tout sqr(Tin). Would it also be possible to test if there is a non-member function cube(contain)?
It kinda depends on what you mean by that. You can of course write a concept for something that behaves "enough like" con... |
66,940,754 | 67,136,372 | How can I debug C++ code called from Python on a remote machines using PyCharm? | How can I debug C++ code called from Python on a remote machines?
I'm using PyCharm, but its debugger doesn't seem to allow you to debug mixed code. What alternatives do I have? I know about gdb but I need some usage details.
| Pycharm ia a python IDE, it cannot be used to debug c++ directly.
If you can use other ides, such as VSCode , the link below may help you.
https://nadiah.org/2020/03/01/example-debug-mixed-python-c-in-visual-studio-code/.
If using gdb, you can use command:
gdb --args python your_python_script.py
then you can debug as ... |
66,940,989 | 66,941,037 | Separating classes in header and source causes build errors | The following code snippets are intentionally made simple only to illustrate the problem. There are two cases I want to show here. The first one in which all code is put in a single file as follows.
#include <iostream>
class Base
{
protected:
double data;
public:
Base(double data);
};
Base::Base(double data ... | The default argument belongs in the declaration (in the header), not in the definition (in the .cpp file).
|
66,941,281 | 66,943,879 | Understanding Asynchronous / Overlapped IO | I am learning about Asynchronous / Overlapped IO in windows. I have written the following code, but it doesn't compile. Where is my mistake? I don't know why we need to call something as FileIoCompletionRoutine and how should I define it?
#include <windows.h>
#include <iostream>
VOID WINAPI FileIOCompletionRoutine(DWO... | You have merely forward-declared the FileIOCompletionRoutine() function, which satisfies the compiler, but you have not actually implemented the function, so the linker fails to find it.
#include <windows.h>
#include <iostream>
VOID WINAPI FileIOCompletionRoutine(DWORD, DWORD, LPOVERLAPPED);
HANDLE g_HandleEvent;
wch... |
66,941,331 | 66,944,889 | Modbusclient as a console application, "Stuck in Connectingstate loop" | I'm trying hardly to convert the Modbusmaster example (qt example) which is a widget application to a console application. I wanted to build a connection between a local slave and my master. The problem I'm facing is that my code is changing its state to “Connecting state” ,gets stuck and doesn't want to build a connec... | I can be wrong but I think the QModbusDevice::ConnectingState you see actually means your server is up and running and waiting for a connection.
I guess what you are missing is opening a connection from a Modbus client. You can do that with different tools, I guess running the client example
would be a good idea. Other... |
66,941,375 | 66,941,448 | How to access PE NT headers from DOS headers? | I'm trying to read a .exe PE file into memory and access NT headers. I can already access DOS headers but can't resolve NT headers from it.
Here's what I have so far:
static constexpr uint16_t DOS_HDR_MAGIC = 0x5A4D; // "MZ"
static constexpr uint32_t NT_HDR_MAGIC = 0x00004550; // ... |
I simply add this value to file start: (struct nt_headers_t *)file + dos_header->e_lfanew;
Am I doing that wrong?
Yes, but for a "boring reason" that has nothing to do with PE headers: since you've done the cast before the addition, the offset is scaled by the size of nt_headers_t. The offset needs to be added unscal... |
66,941,786 | 66,949,764 | Intellisense not working with CMake FetchContent | I am new to CMake and have been playing around with a "Modern CMake" approach.
A brief overview of the project structure:
+ project folder
- CMakeList
+ src
- CMakeList
- lib.cpp
+ tests
- CMakeList
- test.cpp
I have two issues that I would like to address. The main one is g... | It is quite strange and in my side, the vector is colored by your provided code.
So please make sure that you have added add_subdirectory ("CMakeList") under CMakeLists.txt file. And make sure that there is no error for your project.
Or you could try this:
One) disable any third party installed extensions under Extens... |
66,942,128 | 66,943,782 | Difference between range-based for loop and normal for loop Depth-First Search implementation | I'm trying to implement a depth first search algorithm for a graph data structure and my function looks like this:
void dfs(int x, vector <v_Int>& Adjacency_List, v_Int& visited) {
visited[x] = 1; //Mark current vertex as visited
for (int i = 0; i < Adjacency_List[x].size(); i++) { //Iterate through all neighb... | In first implementation, neighbour is not i, its Adjacency_List[x][i].
int neighbour = Adjacency_List[x][i];
if (visited[neighbour] != 1) { //If neighbour not visited, recursively go there
dfs(neighbour, Adjacency_List, visited);
}
|
66,942,184 | 66,942,221 | Why does this code outputs two different results? | I'm trying to make a function that returns the length of an array, but the function always returns 8
#include <iostream>
using namespace std;
int size(int arr[])
{
return sizeof(arr);
}
int main()
{
int v[] = {1, 2, 4};
cout << sizeof(v) << endl;
cout << size(v);
return 0;
}
| This is because ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’..
|
66,942,696 | 66,942,860 | Why aren't my If and Else statements doing nothing? (c++) | I just started learning c++ and I'm trying to make a dice game where the user puts in a number between 1 and 6 and then the code prints a random number within that range and if y and z are the same you win.
This is the code I have but when I put in a number that isn't in the array it works as if it were in the array.... | There's five issues I found with your code.
First and foremost, you are better off doing while(true) instead of for( ; ; ).
Secondly, your else block should start on the same line that terminates the if block.
Third, you should insert a break statement when you win the game.
Fourth, you should change the condition if (... |
66,943,348 | 66,943,575 | Requires-clause appears after template template parameter: is this legal grammar? | Recently, I unexpectedly found that gcc and msvc accept the following code (notice the requires-clause in template-list):
#include <vector>
template <template <class> requires true class>
void f() {}
int main() {
f<std::vector>();
}
and clang rejects its grammar with:
<source>:3:28: error: template template parame... | Yes, this appears to be legal grammar. A template begins with a template-head which is
template < template-parameter-list > requires-clause opt
then a template-parameter-list can be
template-parameter
where template-parameter can be
type-parameter
and then type-parameter can be
template-head type-parameter-key .... |
66,943,938 | 66,944,563 | Static polymorphism using std::variant | I'm trying to implement something like static polimorphism using std::variant. I want to declare methods using VARIANT_METHOD or VARIANT_METHOD_CONST, that should take return type, method name, arguments, and qualifiers.
#include <variant>
#define VARIANT_METHOD(retType, name, ...) \
template <typename... Args> re... | The cleanest way I know of is to abuse operator->* and make polymorphic method pointers. You can get the same syntax (except ->* instead of .), no macros.
template<class F>
struct poly_member {
F f;
friend decltype(auto) operator->*( auto&& t, poly_member const& self) {
return self.f(decltype(t)(t));
}
tem... |
66,944,554 | 66,946,587 | How to use fmt library in the header-only mode? | Having a hard time using the header-only mode of fmt library. Here is what I tried in details:
I downloaded fmt7.1.3 from https://fmt.dev/latest/index.html, only put the directory fmt-7.1.3/include/fmt in a directory ([trgdir]) and wrote a test.cpp as follow:
#include <iostream>
#include <fmt/format.h>
int main() {
... | You need to define a macro before include, like this:
#define FMT_HEADER_ONLY
#include "fmt/format.h"
|
66,944,744 | 66,944,895 | syntax to unpack tuple on parameter pack and variadic template | I have an example parameter pack function:
template<typename T, typename ... Args>
constexpr bool all_values_equal(T first, Args... args) {
return ((first == args) && ...);
}
static_assert(all_values_equal(1, 1, 1.0));
I often use std::tuple as I like to be able to work with templates. Extracting types, Slicing t... | std::apply let's you call a function with the tuple elements as parameters. You can use that with a lambda.
template<typename ... Args>
constexpr bool all_values_equal(std::tuple<Args...> tuple) {
auto cmp = [](auto&& first, auto&&... args) {
return ((first == args) && ...);
};
return std::apply(cm... |
66,945,095 | 66,945,164 | Qt mutually exclusive checkboxes | I want to make a group of mutually exclusive checkboxes in Qt (no Qt Designer or any of that fancy stuff). With three checkboxes I can do something like this in the action function:
void mainWindow::checkbox1action() {
// mutual exclusivity
checkbox2->setChecked(!checkbox1->isChecked());
checkbox3->setChecked(!ch... | You can add your checkboxes into a QButtonGroup and set it to be exclusive.
QButtonGroup *group = new QButtonGroup(this);
group->setExclusive(true);
group->addButton(checkbox1);
group->addButton(checkbox2);
There is also QRadioButton, which is automatically exclusive within the same widget.
|
66,945,206 | 66,945,527 | Why does this use of the detection idiom result in different compilation errors for Clang and GCC and none for MSVC | While playing around with the detection idiom and void_t I found that expressions where the subtraction operator and void* are involved lead to different errors in the tested compilers.
GCC 10.2 and below, no matter if C++11,14,17 or 20 is used, seem to treat some expressions as hard error rather then substitution fail... | GCC 10.2 and earlier are wrong to treat (void*)0 - (void*)0 as a hard instead of soft error. This is fixed in trunk.
Clang does everything correctly.
MSVC is wrong to allow (int*)0 - (void*)0; (while correctly rejecting (void*)0 - (int*)0;), as shown by:
[expr.add]/2.2
For subtraction, one of the following shall hold:... |
66,945,515 | 66,945,976 | How to detect whether a struct's member is a bit-field at compile time in C++? | Given a struct S:
struct S {
bool a : 1;
bool b : 1;
};
How to determine that S::a and S::b are bit-fields at compile time?
I was trying to come up a macro like IsBitField(S, a) but had hard time to apply SFINAE with offsetof() or addressof() (which are known to be invalid operations per bit-fields).
| First, for a SFINAE solution, the ellipsis overload trick (with expression SFINAE) still works, we just need to find a construct that is ill-formed when applied to a bitfield while well-formed when applied on a normal member.
For example, you cannot form a pointer-to-member if the member is a bitfield.
So we could writ... |
66,945,592 | 66,945,631 | Does std::optional forwards rvalueness when contained object functions are called? | Little known feature of C++ is ref-qualifiers for member functions.
It works as I expect it to work in most cases, but it seems that std::optional does not forward the knowledge of its imminent demise to contained object member functions.
For example consider the following code:
#include <chrono>
#include <iostream>
#i... | Overloaded operator arrow cannot do what you want; it terminates with a pointer always.
x->y is defined by the standard as (*x).y if and only if x is a pointer; otherwise it is (x.operator->())->y. This recursion only terminates if you hit a pointer.1
And there is no pointer to temporary type. Try this:
const auto c... |
66,945,729 | 66,945,877 | In function template, how to determine type of one argument based on another | I'd like to implement a function template that takes two arguments, a T* and a T, but where the second argument's type is determined by the first. Here's a minimal non-working example:
#include <cstddef>
#include <cstring>
#include <cstdint>
#include <type_traits>
#include <vector>
template<typename T> void
patch(T *... | This is exactly the kind of scenario that std::type_identity_t<T> is intended to resolve. This transformation creates what's called a non-deduced context, which you've requested for your second parameter of type T. Unfortunately this type trait wasn't introduced until the C++20 standard.
You can continue to use the one... |
66,945,754 | 66,945,999 | Is there a format processor to write my own printf-like function and keep the %d style arguments, without using sprintf? | I'm writing a serial interface for an MCU, and I want to know how one would create a printf-like function to write to the serial UART. I can write to the UART, but to save memory and stack space, and avoid temp string buffers, I would prefer to do that write directly instead of doing sprintf() to a string and then wri... | depending on your standard library implementation you need to write your own versions of fputc or _write functions.
|
66,945,777 | 66,946,073 | C++ function map with varialbles input | In C++, I want to use a map of functions with different type of input or output.
Do to so, I found that using a map with any type could be a way.
But I get several problems. First, I can not use directly the functions in the map.
However, I can use a lambda function to wrap the functions then use these lambda functions... | What you probably want is something like this:
using CallWrapper = std::function<void(const std::string&)>;
std::map<std::string, CallWrapper> mapLambda;
mapLambda["L0"] = [funct0](const std::string&) { funct0(); };
mapLambda["L1"] = [funct1](const std::string& args) {
int p = ...; // parse the argument from `args`... |
66,945,839 | 66,945,907 | How to make a deep nested part of code be toggled without making 2 versions of it | I have the following structure of code:
for
for
for
for
{
things
if(condition1||condition2)
}
And basically that "if" checks 2 variables that depends of every loop before it, but only have to be checked if the user said so at the beginning of the program, otherwise that "if" is pointless.
I could... | You can write your code in a function like this
template<bool Boolean>
void code(/* parameters */)
{
for // ...
for // ...
// all the fors ...
{
// things
if constexpr (Boolean) // compile time branch
{
if(condition1 || condition2)
// ...
... |
66,946,382 | 66,946,427 | Cannot use '==' operator to compare two vectors | I have a program for my Arduino Uno, but for some reason, I get the error
no match for 'operator==' (operand types are 'Vector' and 'Vector')
on my second vector comparison, not the first.
Here is code that represents my problem.
#include <Vector.h>
void setup() {
}
void loop() {
Vector<char> tACode;
Vector<ch... | looking at the definition of Vector it does not provide a operator==:
template <typename T>
class Vector
{
public:
Vector();
template <size_t MAX_SIZE>
Vector(T(&values)[MAX_SIZE],
size_t size = 0);
template <size_t MAX_SIZE>
void setStorage(T(&values)[MAX_SIZE],
size_t size = 0);
... |
66,946,434 | 66,946,965 | checking the values of the neighboring points | I am currently working on a code that checks the giving index neighbors (north, west, east, south) and if the neighbors have the value 0 or 11 it should return false. The start point is 0,0 which has the value 4.
This is my test function.
bool testG(int grid[ROW][COL], int row, int col) {
if (row < 0 || col <... | struct location {
int row = 0;
int col = 0;
};
int get( int grid[ROW][COL], location l ) {
return grid[l.row][l.col];
}
std::vector<location> get_adjacents( location l ) {
std::vector<location> retval;
if (l.row-1 >= 0) retval.push_back( {l.row-1, l.col} );
if (l.row+1 < ROW) retval.push_back( {l.row+1, l.c... |
66,946,517 | 66,947,754 | derived structs and pointer to self in parent struct | I have three structs, one "parent" struct which contains properties, and two structs derived from the parent one, in which I only have methods. Essentially the content of the struct is always the same, but I want different implementations of a same method in different situations.
Example code:
struct Unit {
int id... | To answer your original question (which no one seems to want to actually answer - instead just giving you opinions on how to write your code): Yes, you can do what you want to do, it involves templatizing Unit by the pointer that you want to store in next: https://godbolt.org/z/qrrMfc7PM
Note that this pattern is so co... |
66,948,213 | 66,948,792 | Alternative to virtual inheritance in re-using base template implementation | In a project I'm working on we're using a pattern where we have pure abstract classes defining an interface, and template implementations that may be instantiated with different template parameters, which are used for many things, including dependency injection. Something like:
struct Base {
virtual int getVal() = 0;... | The basic pattern is:
struct Base{
virtual int count()const=0;
};
template<class X, class B=Base>
struct CountImpl:B{
int count()const final{ return X::count; }
};
now we can CountImpl<Foo, Extended> to rebase the inheritance.
Fancier stuff, with plug in aspects etc, can be done. In simpler cases this is not wor... |
66,948,262 | 66,948,549 | I am getting an error of expression must be modifiable | This is the struct
typedef struct struct1
{
char words[kInputSize];
struct WordNode* next;
}struct1;
I am getting error for allocationg memory block for block->words.
struct1* add(struct1** newHead)
{
struct1* block= NULL;
// allocate a block of memory for new record
block->words = malloc(strlen(... | In your posted struct1, words is declared like this:
char words[kInputSize];
... and then you try to set it equal to a pointer, here:
block->words = malloc(strlen(words) + 1);
This doesn't work because in C++ (or C for that matter) you are not allowed to set an array equal to a pointer.
If you want to be able to set ... |
66,948,292 | 66,948,400 | Multithreading atomics a b printing 00 for memory_order_relaxed | In the below code the write to a in foo is stored in store buffer and not visible to the ra in bar. Similarly the write to b in bar is not visible to rb in foo and they print 00.
// g++ -O2 -pthread axbx.cpp ; while [ true ]; do ./a.out | grep "00"; done prints 00 within 1min
#include<atomic>
#include<thread>
#include... | a.store(1, mo_relaxed) is sequenced before a.load in the same thread (in both foo and bar), so both loads must see that store result (or another later store value). That makes it impossible for either load to see the initial 0.
A thread always sees its own operations in program order, even if they're on atomic objects... |
66,948,294 | 66,950,072 | Clion compiler not working after macbook update? | My CLion does not allow me to compile with this message below. Any way to fix this?
/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake -DCMAKE_BUILD_TYPE=Debug -G "CodeBlocks - Unix Makefiles" /Users/name/CLionProjects/untitled118
-- The C compiler identification is unknown
-- The CXX compiler identification is u... | You are missing the command line tools. This happens very often after updates to XCode and/or macOS. The tools which are from the prior version will be removed, however the new tools will not be installed.The way to fix this problem is:
Follow the instruction for the latest version of XCode for installing the command ... |
66,948,600 | 66,954,172 | "tensorflow/core/framework/common_shape_fns.h: No such file or directory" when adding custom op in tensorflow | I am trying to add a custom op in Tensorflow in Google Colab using this Tensorflow Doc. However, when building I am getting this error.
2021-04-05 04:24:26.500483: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0
2021-04-05 04:24:29.436586: I tensorfl... | Use the following steps to run this in Google Colab. Basically, we will remove the use of the variables (e.g, TF_LFLAGS, TF_CFLAGS) in building and build this with direct command.
Add the cpp file.
# create empty file and copy and paste code
! touch ./xor_op.cc
Or use magic operation,
%%writefile xor_op.cc
#And con... |
66,949,230 | 66,949,323 | Output 11 for this program never occurs | This time i use atomic_fetch_add . Here is how i can get ra1=1 and ra2=1 .
Both the threads see a.fetch_add(1,memory_order_relaxed); when a=0. The writes go into store buffer and isn't visible to the other. Both of them have ra=1 and ra2=1.
I can reason how it prints 12,21 and 22.
22 is given by both of them incremen... | a.fetch_add is atomic; that's the whole point. There's no way for two separate fetch_adds to step on each other and only result in a single increment.
Implementations that let the store buffer break that would not be correct implementations, because ISO C++ requires the entire RMW to be one atomic operation, not atomi... |
66,949,990 | 66,950,038 | How to interpret this conditional statement with regard to std::errc | I was reading an example of how to use std::from_chars function here, when I came by the following if statment:
if(auto [p, ec] = std::from_chars(str.data(), str.data()+str.size(), result);
ec == std::errc())
std::cout << result << "\n" "p -> \"" << p << "\"\n";
Unfortunately I can not understand what e... | This
if(auto [p, ec] = std::from_chars(str.data(), str.data()+str.size(), result);
ec == std::errc())
std::cout << result << "\n" "p -> \"" << p << "\"\n";
is similar to
auto [p, ec] = std::from_chars(str.data(), str.data()+str.size(), result);
if( ec == std::errc() )
std::cout << result << "\n" "p ... |
66,951,327 | 66,953,539 | Need help understanding how std::promise and std::future work in this case | Code
#include <iostream>
#include <thread>
#include <atomic>
#include <future>
void listenForInput(std::promise<bool>&& interruptPromise)
{
std::cin.get();
std::atomic_thread_fence(std::memory_order_acquire);
interruptPromise.set_value(true);
std::cout << "[Speech 100] no u \n";
}
bool is_ready(std::f... | Primise/future isn't a value that changes, it is a value that is delivered later.
If you want a value that changes, you can stich together one out of a mutex, condition variable and a bool. However, reasoning about a bool that changes more than once in a multithreaded environment will break most people's brains in my ... |
66,951,813 | 66,951,995 | Failed to randomize bytes using independent_bits_engine | I'm trying to randomize a byte array, but it doesn't let me compile it, because of the errors below. It doesn't even work with byte instead of std::uint8_t.
error C2338: invalid template argument for independent_bits_engine: N4659 29.6.1.1 [rand.req.genl]/1f requires one of unsigned short, unsigned int, unsigned long,... | [rand.req.genl]/1.6 (in the C++23 draft):
Throughout this subclause [rand], the effect of instantiating a template:
that has a template type parameter named UIntType is undefined unless the corresponding template argument is cv-unqualified and is one of unsigned short, unsigned int, unsigned long, or unsigned long l... |
66,952,249 | 66,952,358 | Why strings can be used like this | C++ code
string *stra;
string strb = "ABC";
stra = &strb;
std::cout << stra[0][1] << std::endl;
std::cout << *stra << " " << stra[0]<< std::endl;
why use stra[0] is print same at *stra or why I can use like that
| According to the C++ 14 Standard (5.2.1 Subscripting)
1 A postfix expression followed by an expression in square brackets is
a postfix expression. One of the expressions shall have the type
“array of T” or “pointer to T” and the other shall have unscoped
enumeration or integral type. The result is of type “T.” The typ... |
66,952,564 | 66,954,065 | C++ String class implementation | My project asks to implement a string class in C++, however, I'm confused about one of the public function
class String
{
private:
char* buffer;
int size;
public:
// Initializes a string to be empty (i.e., its length will
// be zero and toChars() will return "").
String();
// Initializes a... | There are some differences in how much memory you allocate which will come back and bite you.
Your default constructor doesn't allocate anything.
Your converting constructor allocates size + 1 chars.
Your copy constructor allocates size chars.
You also need to add a move constructor and copy+move assignment operators.... |
66,953,100 | 66,955,225 | 2 C++ classes with same functionality but different variable names - which pattern to use? | I have 2 C++ classes which have the same variable types and need to perform exactly the same operations on these variables. However, the variable and function names of these 2 classes are different as they mean different things in their respective classes.
How can I achieve this without code duplication? Does inheritan... | There are several ways to deal with this.
Just use one class. If the functionality is the same and you are just changing names, then why do you need more than one class.
PROS: minimize code duplication
CONS: if these are for two different applications, you are violating the single responsibility principle
Create a ... |
66,953,589 | 66,953,627 | arranging an array in ascending order | I was tasked in school to create a program that arranges an array's values in ascending order. It's almost there but whenever i input "44 55 66 22 33 11 77 99 88 66" or any number it outputs
-858993460,11,22,33,44,55,66,66,77,88, or a negative number at the start
what the heck is happening to the first number? is there... | Here is off-by-one error:
for (int a = 0; a < 10; a++) {
When a = 9, num[a + 1] will be out-of-range.
The line should be:
for (int a = 0; a < 9; a++) {
|
66,953,746 | 69,290,227 | VsCode creates an .exe file every time I create a C++ file | I'm pretty new to VsCode. So the problem is whenever I create a new C++ file and run it, an exe file is created with the same name.
Here's the picture,
So if I have many C++ files, there will be also many .exe files that are not clean to see and distracting.
Is there anyway to get rid of this exe files? (If not comple... | If these files keep creating every time you run the code, you can go to Settings in the bottom left corner and search for Files:Exclude. Then you have to Add the **/*.exe Pattern. It makes all executable files hidden in the Explorer section.
|
66,953,833 | 66,957,641 | Can't relaxed atomic fetch_add reorder with later loads on x86, like store can? | This program will sometimes print 00, but if I comment out a.store and b.store and uncomment a.fetch_add and b.fetch_add which does the exact same thing i.e both set the value of a=1,b=1 , I never get 00. (Tested on an x86-64 Intel i3, with g++ -O2)
Am i missing something, or can "00" never occur by the standard?
This... | The standard allows 00, but you'll never get it on x86 (without compile-time reordering). The only way to implement atomic RMW on x86 involves a lock prefix, which is a "full barrier", which is strong enough for seq_cst.
In C++ terms, atomic RMWs are effectively promoted to seq_cst when compiling for x86. (Only after ... |
66,953,888 | 66,954,575 | How to generate all binary string in order(increasing) upto 2^63 without converting numbers? | Output should be like
0
1
10
11
100
101
110
111
1000
1001
1010
1011
1100
1101
1110
1111
10000
....etc
Here this should be generated without conversion from number. For example we should not generate 111 by converting 7 to binary.
| As the only feature you need is to increment, you could readily write a class:
class BinaryNumber {
public:
uint8_t data[64]; // This is wasted space, see notes.
bool increment();
};
std::ostream & operator<<(std::ostream &, const BinaryNumber &);
It might be that bitset is a better data structure tha... |
66,955,603 | 66,955,700 | Does c++ include stl library such as <locale> implicitly from other libraries? | I am looking at the example given for std::tolower in c++ reference and it seems the method std::tolower works even if I replace library <locale> with <algorithm>
Is <locale> imported indirectly if <algorithm> is included?
Example:
// tolower example (C++)
#include <iostream>
#include <string>
#include <locale> ... |
Is <locale> imported indirectly if <algorithm> is included?
There is no import (before C++20 and modules) in C++11, just includes. Read n3337 (or some newer C++ standard), the documentation of your compiler (e.g. GCC) and preprocessor (e.g. GNU cpp).
If you use GCC, compile your C++ code mathworker.cc as g++ -Wall -... |
66,955,782 | 66,955,810 | Using hardcoded char array pointer outside its scope, why no crashes | #include <iostream>
using namespace std;
int main()
{
char * a = nullptr;
{
char * b = (char *) "hello";
a = b;
}
cout << a << endl; // prints hello
return 0;
}
I have the code above. I am having hard time understanding why the code doesnt crash. My reasoning is I expec... | C-style string literal like "hello" has static storage duration; it exists in the life of the program. Then it's still valid for cout << a << endl; (while a is pointing to it) after the scope where b is defined.
String literals have static storage duration, and thus exist in memory for the life of the program.
|
66,955,826 | 66,955,936 | How to search a vector of pairs by pair.first, and returning the entire pair? | I have a vector of pairs, and I also have a number that is possibly equal to pair.first within the vector. I would like to search the vector using this number, and then if it is in the vector, return the entire pair. Here is code:
vector<pair<size_t, size_t>> = (psuedocode) {{0, 13}, {1, 12}, {3, 11}};
Now, I have a v... | std::find_if() is better suited to the job in this case.
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
int main() {
std::vector<std::pair<int, int>> v{{1, 2}, {2, 3}, {3, 4}};
int vertex= 2;
auto it = std::find_if(
v.begin(), v.end(),
[&vertex](std::pair<int, int> i)... |
66,955,981 | 66,956,070 | Do the ISO C or C++ standards specify `const char *` should be a NULL terminated string? | I have always seen const char * used in this way, and libc makes assumptions to this effect.
During an API review, I said const char * should be assumed to be a NULL terminated string, then someone said it doesn't have to be - so no assumptions can be made.
We can still be defensive making assumptions, but we can write... | What we can assume about the memory at, or starting at, the address a pointer to const char contains is context dependent.
const charpointers are often used as pointers to ASCII text (a "string"), but don't have to be; such a pointer can as well point to arbitrary data, or to a single char.
APIs which rely on null term... |
66,956,785 | 66,956,916 | Problem while creating 2D array dynamically in C++. Here is the code. It dosen't work for some specific conditions | In my following code i am taking input (int) rows and cols form the user and creating a 2d array. After taking the input i am printing the same 2d array.
#include<iostream>
using namespace std;
int main()
{
int rows,cols;
cin>>rows>>cols;
int **matrix=new int*[cols];
for(int j=0;j<cols;j++)
{
... | You have wrong use of rows and cols. In places where you need rows you use cols sometimes, and vice versa. Full corrected code:
Try it online!
#include<iostream>
using namespace std;
int main()
{
int rows,cols;
cin>>rows>>cols;
int **matrix=new int*[rows];
for(int j=0;j<rows;j++)
{
matrix[j]... |
66,956,924 | 66,956,989 | c++ bugs out when trying to find vector<struct>.begin()/.end() | So there is this thing bugging me in my project, that prevents me to find the vector.begin() and vector.end() when putting struct as the vector type. Anyone can help me there?
struct product
{
string name = "";
int qty = 0, code = 0, cat = 0;
double price = 0.00;
}
(...)
vector <product> prod;
(...)
for(in... | In this for loop
for(int i = 0; i != prod.end(); i++)
there are compared an object of the type int and an object of the type either std::vector<product>::iterator or std::vector<product>::const_iterator
There is no operator != defined for operands of these types.
It seems you mean something like
for ( auto it = prod.... |
66,957,130 | 66,957,264 | Wrapper hash function to return hash of wrapped type | I have the following code:
#include <bits/stdc++.h>
using namespace std;
// wrapper class on type E
template <typename E>
class g {
public:
E val;
g(E x) : val(x) {};
};
// hash for g<E> should be hash for E
template<typename E> struct std::hash<g<E>> {
std::size_t operator()(const ::g<E> &t) const {
... | Your code is attempting to invoke std::hash<int>() on t, which has type g<int>. You need to "unwrap" the wrapper and call std::hash<int>() on the enclosed int:
return std::hash<E>()(t.val);
|
66,957,506 | 66,957,590 | In C++ is there any way to optimize for empty types for composition as opposed to inheritance? | A cool feature in C++ is empty base/type optimization, so:
struct EmptyType {};
struct Foo : EmptyType
{
long long a;
};
int main()
{
sizeof(EmptyType); // Is 1
sizeof(Foo::a); // Is 8
sizeof(Foo); // Is not sizeof(a) + sizeof(EmptyType), is still 8
}
However I was wondering if you can get this kind ... | Yes, since C++20, you can use the [[no_unique_address]] attribute:
#include <iostream>
struct empty {};
struct foo {
[[no_unique_address]] empty b;
int a;
};
int main() {
foo x;
std::cout << &x.b << '\n' << &x.a << '\n'; // may print the same address
std::cout << sizeof(int) << ' ' << sizeof(x) <... |
66,957,633 | 66,964,168 | How to Enumerate Volumes on Remote Computer? | I am running three computers in my home network, all within the same workgroup. Now I want to find out on my computer which volumes are present/mounted on the other computers im my network, and I want to do it in my C++/C# code.
Method NetServerEnum works fine and delivers the computer names in my network but now I am ... |
I have already tried function NetServerDiskEnum but receive
ERROR_ACCESS_DENIED.
This is because only members of the Administrators or Server Operators local group can successfully execute the NetServerDiskEnum function on a remote computer.
Refer: NetServerDiskEnum Remarks
Instead, No special group membership is req... |
66,957,721 | 66,958,250 | Hashtable AddEntry Separate Chaining Segmentation Fault | I am getting a segmentation fault in my Separate Chaining Hash Table object.
bool hashTable::addNode(int id, string information){
bool inserted = false;
int position = hash(id);
cout << &hashtable[position]<<endl;
if(hashtable[position]==NULL){
hashtable[position]->data.id = id;
hashtable[position]->data.info... | There are a few spots in your code where it looks like you're using the address-of operator & incorrectly. Let's start with this one:
if (&hashtable[position] == NULL) {
...
}
I completely see what you're trying to do here - you're trying to say "if the slot at index position holds a null pointer." However, that's ... |
66,957,728 | 67,019,529 | How to check that file is empty or not before writing something in it ? thanx | before writing some data in the file I want to check that this file is empty or not. If it is empty then I
have to write a matrix with 0 value in it. so, tell me please how can I do it?
void details(int arr[][10]) // assumed that this matrix already contains 0
//values
{
int m1 = 1... | The Function tellg() returns the read (get) position of the file and we opened the file with the read (get) position at the end using std::ios::ate . So if tellg() returns 0 it must be empty.
|
66,958,002 | 66,959,545 | How to write this more compact | I am trying to convert a char buffer into multiple int variables. This is what i got so far after a day of trying.
ZeroMemory(buf, 4096);
int bytesReceived = recv(sock, buf, 4096, 0);
if (bytesReceived > 0)
{
/*for (int i = 0; i < bytesReceived; i++)
{... | From your comment it looks like you are getting NOT the hex characters, but in fact the binary value 2,000.
You can throw away your binary -> string -> binary conversion and get the values directly from your buffer.
Based on your code, I assume that you know you are getting 2-byte short int values. recv returns a numbe... |
66,958,183 | 66,958,495 | Is it possible to determine if a callable is a predicate (i.e. returns bool)? | In an attempt to rewrite a predicate combinator like this
auto constexpr all = [](auto const&... predicates){
return [predicates...](auto const&... x){
return (predicates(x...) && ...);
};
};
(little generalization of this) in a way that it would give meaningful errors when fed with non-predicates/pred... |
So my question is: is it even possible to determine the return type of an arbitrary callable?
No. You can only do this in very narrow circumstances:
the callable is a pointer to member data / pointer to member function
the callable is a pointer/reference to function
the callable is a function object with a single no... |
66,958,225 | 66,960,251 | Why am I unable to access my Python function after importing its module in C++? | I am attempting to call a function print_stuff which is a member of the class Spam from a user-defined Python module Spam in C++
#define PY_SSIZE_T_CLEAN
#include <Python.h>
int main()
{
Py_Initialize();
//modify python module search path
auto modulePath = /* hardcoded search path for module */
PyObje... | First, I don't think you need the last two lines in spam.py. I reduced it to this:
class Spam:
def __init__(self):
pass
def print_stuff(self):
print((1,2,3))
Now, let's test the module:
>>> import spam
>>> s = spam.Spam()
>>> s.print_stuff()
(1, 2, 3)
So far, so good. Let's see if we can use ... |
66,958,284 | 66,966,323 | Use of application class within shared library | I'm trying to create a "gaming platform" that lets the user choose a game to play and also the graphic library to render it. Those games and graphic libraries are implemented as dynamic libraries, loaded at runtime. We'll call the gaming platform Core.
The shared libraries contain classes that are loaded at run-time wi... | Okay, after reading Drepper's paper How to write shared libraries I've found what the problem was.
In C++ the methods are not linked. Nor the program, nor the lib have the methods of the other linked. The patch is to use vtable. If the method is virtual, the program checks the vtable that goes with the object and there... |
66,958,398 | 66,958,444 | rvalue references and user defined conversion | I am trying to figure what happens in the code below (it was inspired by shared_ptr(unique_ptr&&) constructor).
#include <iostream>
using namespace std;
class A {};
class B {
public:
B(const A&) {
cout << "ctor from A&\n";
}
};
void f(B&&) { cout << "f(B&&)\n"; };
void f(const B&) { cout << "f(const ... | The function does not accept an object of type A. However, it does accept an object of type B, and A is convertible to B by virtue of the implicit converting constructor. The result of the conversion is a prvalue. The rvalue reference overload is a better match than the const lvalue reference when the argument is a prv... |
66,958,733 | 66,959,072 | cuda kernel execution delayed by cpu code | I cannot get my head around the following admittedly very simple code, which is a boiled down version of a more complicated project where I spent many hours on by now.
This code as is will run on my system in about 2000 milliseconds. But when I enable the line to put cpu into sleep for 500 ms, the program alltogether w... |
I cannot understand how that fits into the statement that cuda kernels execute asynchronously with respect to the host?
You're experiencing WDDM Command Batching as described here.
In a nutshell, on windows, when in the WDDM driver model, GPU commands (e.g. anything from the cuda runtime API, plus kernel launches) w... |
66,958,777 | 66,959,613 | Can't Convert A Float in Array to String | I am trying to create a sine, cosine, tangent, and cotangent table. I want to printf/cout an "INF" instead of huge complicated numbers or interesting symbols when I calculate the cotangent of 0. But it doesn't allow me to do this. I tried every way I can think of, but I couldn't do it.
Can you help me about that?
Code ... | There are 2 issues:
Due to low PI precision, tan(90*PI/180) returns a large number and not infinity.
Your system is printing infinity as 1,#INF00. I don't think there's a way to change that.
To work around both issues don't let large values go to printf and instead print your own string if the value is larger than so... |
66,959,037 | 66,959,087 | Declaring an array of std::bitset using std::string | Im currently trying to declare an array of 17 std::bitsets, each 32 bits long. I'm doing it like this:
std::bitset<32> mTestInstruction[17]
{
std::string("01000000001000000000000000000001"),
std::string("01000000011000000000000001100011"),
std::string("01000000101000000000000000000001"),
std::string("10... | You need to call the constructor of std::bitset like:
std::bitset< 32 > mTestInstruction[17]
{
std::bitset< 32 >( std::string( "01000000001000000000000000000001" ) ),
std::bitset< 32 >( std::string( "01000000011000000000000001100011" ) ),
// ...
};
or even shorter:
std::bitset< 32 > mTestInstruction[17]
{
... |
66,959,326 | 66,959,416 | Adding a variable to a vector in c++ | I have a std::vector called possible_numbers and I am trying to use its .push_back() method to add the value of the variable i to the back of the vector. When I try to do it, my code ends up adding i to the vector, instead of the value of i.
#include <iostream>
#include <vector>
int main() {
std::vector<std::strin... | There are multiple issues with this code snippet:
If you are trying to generate a list of numbers, why are you using std::vector<std::string>? This is creating a vector of strings, if you are looking for ints, use std::vector<int>.
Pushing "i" is pushing the string literal "i", not the variable i. When removing the "... |
66,959,333 | 66,959,784 | What should be the type of the object constructed from the below code i.e. new TreeNode<int> (13) | From the book "C++ primer", it says:
compiler uses the initializer's type to deduce the type to allocate.
It also mentions:
we can use auto to deduce the type of the object we want to allocate from that initializer.
In the below line of code, does new TreeNode<int>(13) return a pointer of type int* (since the initi... | The section of the book describes the behavior of the keyword auto. It's not the general behavior. auto(obj) is a special case. auto is not a type. It's a keyword for a placeholder: https://en.cppreference.com/w/cpp/language/auto
Using auto the type is deduced from the object.
In new TreeNode<int>(13); you are using a ... |
66,959,350 | 66,968,626 | operator = problem. Why is this happening? | So i have written the following method in a class:
Array & operator = (const Array &a) {
/*delete [] array;
priv_size = a.priv_size; HOW DOES THIS EVEN DO SOMETHING???
priv_base = a.priv_base;
array = new int[priv_size*priv_size];
for (int i=0; i<priv_size*priv_size; i++)
... | My question is answered:
In my example i wrote Array b = a;, which in c++ calls the copy constructor and not the opperator =
This is documented here:
https://en.cppreference.com/w/cpp/language/copy_initialization
As well as here:
https://en.cppreference.com/w/cpp/language/copy_constructor
Thanks to everyone who took th... |
66,960,261 | 66,965,797 | C++ measuring memory usage during MergeSort | I want to measure RAM memory usage after MergeSort in C++ on 10 000 000 random elements (self-written MergeSor). I use MEMORYSTATUSEX function to count it like this
#define DIV 1048576 //conversion to MB
[...]
MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&memInfo);
DWORDLONG t... | Okay i found solution, a little overkill but it works. You have to do a little workaround, which is measuring memory every time function mergeSort is called and then check if the current value of memory is greater than previous
int memoryTaken = 0; //global variable, not very elegant but works
void mergeSort(int arr[],... |
66,960,595 | 66,960,878 | Is there a sensible scenario, where the == operator is not the negation of the != | As a follow-up to my previous question (Does overriding the operator == for a class automatically override the operator !=),
is there a scenario, where you would override the == and != operators to not be the negation of each other,
where the negation would be defined as:
(!(a == b)) == (a != b)
or
(a == b) == (!(a !=... | No, in a broad sense. Stepanov would say that if you don’t follow this rule of logic then you get what you deserve. That is why in C++20 they will be by default defined by each other just like he wanted.
In practice, yes, there are at least two scenarios.
NaN (not-a-number) in IEEE floating point numbers. Two NaN are ... |
66,960,998 | 66,961,098 | C++ operator overloading fails to output + operation | I'm learning C++ and trying to write a C++ class for matrices, where I store the matrix as a one-dimensional C array. To this end, I defined an element member function to access the matrix elements based on their location in the array. I have then overloaded the << and + operators to handle the display and addition of ... | Your << operator takes a non-const reference to a matrix as parameter. That means it can't take reference to a temporary object.
The result of A+B is a temporary object if you don't assign it to something.
So you need to change this:
std::ostream & operator<<(std::ostream &os, matrix &M);
into this:
std::ostream & ope... |
66,961,011 | 66,961,105 | Fold on variadic template function to call a function on every template type while providing the order | I have recently discovered SQLite and it seems like a wonderful embedded DB to me. The only (and really small) issue that I can find on it is about its C interface and how it forces you to type a lot of boiler plate code, so I wonder if using variadic templates and C++17 fold features we can improve that point.
Unfortu... | template<typename... Args, std::size_t...Is>
auto sqlite3_record(sqlite3_stmt* statement, std::index_sequence<Is...>)
{
return std::make_tuple(sqlite3_column<Args>(statement, Is)...);
}
template<typename... Args>
auto sqlite3_record(sqlite3_stmt* statement){
return sqlite3_record<Args...>(statement, std::make_index... |
66,961,362 | 66,961,377 | Polymorphic Python field lookup vs C++ field lookup | I am curious as to the differences between how Python and C++ lookup fields using inherited getters. Consider these two code snippets and their outputs.
class Base:
x = 10
def get_x(self):
return self.x
class Derived(Base):
x = 20
print(Base().get_x())
print(Derived().get_x())
Outputs
10
20
On... | They have different outputs because C++ and Python are two fundamentally different languages and they work in fundamentally different ways.
The C++ version is not logically equivalent to the Python one. The C++ version has two completely different class members named x that belong to two different classes. Declaring a ... |
66,961,406 | 66,961,476 | C++ Variant visit overloaded function | I want to execute an overloaded function over a variant. The following code block works and compiles, but the visit invocation seems overly complex. Why can I not simply write:
std::visit(&f, something);
Working version and context:
#include <variant>
#include <string>
#include <iostream>
#include <functional>
struct... | std::visit(&f, something);
This is not valid, because f is not a single function. &f says "give me a pointer to f". But f isn't one thing; it's three functions which happen to share a name, with three separate pointers.
std::visit([](auto&& x) {f(x);}, something);
This creates a closure based on a template which gene... |
66,962,110 | 66,962,134 | How to find out if a type is a templated type of any type? | In the below code:
template <typename T>
struct templatedStruct
{
};
template <typename T>
void func(T arg)
{
// How to find out if T is type templatedStruct of any type, ie., templatedStruct<int> or
// templatedStruct<char> etc?
}
int main()
{
templatedStruct<int> obj;
func(obj);
}
Is the only way ... | You can define a type trait for it.
template <typename T>
struct is_templatedStruct : std::false_type {};
template <typename T>
struct is_templatedStruct<templatedStruct<T>> : std::true_type {};
then
template <typename T>
void func(T arg)
{
// is_templatedStruct<T>::value would be true if T is an instantiation of ... |
66,962,149 | 66,962,236 | Can template alias be used as a function input type? | I am wondering if it is possible to have a template alias as a function input type, and the 'further' type can be further determined based on the input?
template<typename T>
using Vec = std::vector<T>;
I want to define a function:
void func(Vec& a){
for(auto &each :a){
//Do something
}
}
Where the type of Vec... | Thanks to template argument deduction, templates already behave in the way that you want.
Defining func as
template<typename T>
void func(Vec<T>& a) {
// ...
}
will let you write
Vec<int> a{};
func(a);
Vec<double> b{};
func(b);
No explicit type parameters are required at the call-site.
|
66,962,445 | 66,975,124 | Display texture and sprite on the window in class function | So this is my cpp file that has the function. I comment out some member factor as I felt like it wasn't being read at all but will include them to see if I am able to use them. My texture seems to be able to appear but no matter the size or position I try to put it it is not being shown at all. It seems to load properl... | When linking an a texture to a sprite, you need to tell that sprite the actual reference to the one texture.
sprite.setTexture(image&);
Calling the font address by using the '&' operator should solve your problem.
You should also load your image only once by calling:
if(!image.loadFromFile("Jester.png"))
{
exit(1)... |
66,962,472 | 66,963,450 | I am trying to create a vehicle registration portal. For some reason the get() is only receiving the owner name | I am trying to create a vehicle registration portal. For some reason, the get() is only receiving the owner's name.
I'm trying to practice inheritance and used the concept of inheriting properties from the parent class "vehicle".
This one is the child class "get info"
#include<iostream>
using namespace std;
class vehi... |
In void get() you are trying to get owner name in Registration number that is of int type, therefore it breaks
Secondly you Owner Name should be of string type other than Char since char can only store 1 character.
In class vehicle, noPlate is of int type, you must also take int type tempNoPlate in derived class get... |
66,962,474 | 66,962,773 | Given a matrix of size nxm, how can we calculate the sum of all possible square matrices of size (L)? | Given this 3x3(nxm) matrix, how can I traverse and get the sum of all possible square-submatrices i.e(1x1,2x2 in this particular case)
2 2 3
3 4 5
4 5 5
I know here,
every element is an individual submatrix(1x1),
and the rest square-submatrices are as follow:
2 2
3 4
2 3
4 5
3 4
4 5
4 5
5 5
I've tried my approach ... | This is the solution of your case.
for(int i=0; i+(l-1)<n; i++){
for(int j=0; j+(l-1)<m; j++){
int sum = 0;
for(int a=0; a<l; a++){
for(int b=0; b<l; b++){
sum += matrix[i+a][j+b];
}
}
cout << sum << endl;
}
}
or you can try to run the ful... |
66,962,722 | 66,968,336 | how to convert simple string cpp variable to MIPS code | Sounds simple, but I have been searching for a good hour or so now.
I want to know if there is a way for me to start a register with a string without having to store the string in .data.
For example, I can do; li $t0, 0 which has the effect of setting $t0 = 0. This is the same as me saying int a = 0 in cpp.
However, is... | A string is nothing but a pointer to a byte/char that ends at 0 value byte.
Since there is no native c++ to MIPS compiler we could argue with common sense that the simplest way to define and initialize a string in MIPS is
.data
mes: .asciiz "Hello"
.text
la $t0, mes
|
66,962,839 | 66,963,946 | Applying function to a variadic template | I have a class that holds a map of Collection<T>, which is cast into a void* for storage purposes.
Each Collection<T> can hold an array of IDs, and I want to provide some variadic template magic to be able to tell if some ID exists in some grouping of Collection<T>. I'm just not sure how to go about it, after looking o... | if you have c++17 (fold expression)
template<typename ...Ts>
bool does_have(int id) {
return (contains<Ts>(id) && ...);
}
|
66,962,890 | 66,963,062 | Undefined reference to linker error when using namespaces in headers in c++ | I've read through all similar "Undefined reference to" threads I could find but couldn't find a solution. Most of the other threads also involved classes which I don't plan to use for this. The program compiles executes normally if I define the function within the header instead of using an external .cc file. I feel... | You are not actually compiling the cpp file that has the definition of pewpew.
Try:
g++ -lstdc++ hntestmain.cc hntest.cc -o hntestmain
The compiler needs to know about all the source files. The header file is dealt with during pre-process and knows to look in the same folder. You can imagine that if you have more file... |
66,962,982 | 66,963,007 | From where does the value of argc and argv comes in the main function c++ | I'm new to c++ and I've seen many c++ compilers automatically pass int argc,char* argv as parameters in main function but where are they defined?
A little curious to know about.
| These are typically supplied by the shell, or more specifically, the parent process. That is the parent process can decide which, if any, parameters to pass through. These show up in argc/argv. See the exec family of functions for examples of how this looks from the parent process perspective. There's also kernel versi... |
66,963,222 | 66,963,423 | Why do left operands of logical AND/OR not carry dependency to the parent evaluation? | According to C++ standards:
An evaluation A carries a dependency to an evaluation B if - the value of A is used as an operand of B, unless:
— B is an invocation of any specialization of std::kill_dependency (29.3), or
— A is the left operand of a built-in logical AND (&&, see 5.14) or logical OR (||, see 5.15) operato... | memory_order_consume was an attempt to expose an asm-level CPU feature for use in C++. (It's temporarily deprecated until it can be reworked to something that compilers can implement in practice, and that doesn't require so much kill_dependency noise in the source). Understanding the CPU behaviour is key to understand... |
66,963,381 | 66,968,379 | Best practice for boost spirit context-dependent grammar rule | Just a sample to clarify the issue .. (this is pseudo code)
Classic way: Just make a rule for every path. So starting at "start" and selecting outer_rule1 or outer_rule2 and from there going into inner_rule1 and inner_rule2. You can clearly see that the inner rules are nearly equal. E.g. thing about a grammar where the... | You forgot to specify which version of Spirit (Qi or X3) (again?).
So, here goes:
Spirit Qi: Inherited Attributes
You can inject state into the rules by using Inherited Attributes or Locals.
Demo using the first:
Live On Compiler Explorer
#include <boost/spirit/include/qi.hpp>
#include <fmt/ranges.h>
namespace qi = bo... |
66,963,410 | 66,964,133 | Using Visual Studio C++ compiler w/ Meson? | I'm trying to use https://github.com/Pizzabelly/EasyRP to create a desktop application, and I need a C++ compiler to continue. It says to download "any c++ compiler (cl, g++, clang++, etc)", and I'm wondering if I have to download a new package/directory to continue, or if there's a way to use something from Visual Stu... | I followed https://mesonbuild.com/Using-with-Visual-Studio.html along with https://github.com/Pizzabelly/EasyRP. Make sure to use the VS command line. Also, EasyRP says to run msbuild /p:Configuration=Release, and I had to add msbuild /p:Configuration=Release ALLBUILD.vcxproj so that it would properly build.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.