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 |
|---|---|---|---|---|
64,866,412 | 64,866,597 | Create instance of derrived inner class in base class | Is there a way to create an instance of an inner class, which is defined within a derrived class, on the base class? See bellow.
template<typename D>
struct Base {
D::Data data; // MSVC 2019 gives me compilation errors.
};
struct Derrived : Base<Derrived> {
struct Data {
bool b = false;
int i = 0;
... | No, this will not work, for two reasons:
the type of D::Data is dependent on the type of D, which is a template parameter, and so this can cause ambiguities for the compiler. Some compilers will warn you about this, eg:
prog.cpp:6:3: error: need ‘typename’ before ‘D::Data’ because ‘D’ is a dependent scope
D::Data d... |
64,866,457 | 64,866,497 | No viable conversion from returned value of type 'int' to function return type (vectors) | I am trying the hackerrank question and they gave said to give the output as "Print two space-separated integers describing the respective numbers of times the best (highest) score increased and the worst (lowest) score decreased." Now, whenever I try to give only cout, it throws an error saying "Non-void function does... | The problem is that you set your function to return vector type of object, so returning 0 or not returning anything is unacceptable. You basically have 3 options here:
Set your function as a void type - then you can only "cout" and you're good, or
even nothing at all.
Return "scores" itself without actually using it o... |
64,866,790 | 64,872,470 | ncurses: handle keyboard inputs in the terminal in C++ | I am trying to build a simple tetris game within the terminal. I need to move the pieces when the player presses an arrow key. I heard about the getch() method but it doesn't seem to work with arrow keys (they were all detected with the same int code: 27). What should I do?
Here is my current code:
initscr();
i... | The as noted in the manual page:
Most programs would additionally use the sequence:
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
That is, your program should turn on keypad mode to get KEY_UP, etc:
The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user ... |
64,866,830 | 64,867,285 | Why doesn't msg.message ever equal WM_QUIT in my program | I have a program that uses peekmessage instead of get message and it is supposed to break if msg.message ever equals WM_QUIT but it never equals and my program never ends.
MSG msg = { };
while (TRUE)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
... | Unlike GetMessage(), which returns 0 when WM_QUIT is retrieved, PeekMessage() simply returns TRUE when any message is retrieved, and FALSE otherwise. You have to check the MSG only when PeekMessage() returns TRUE. There is no guarantee that the MSG is updated when PeekMessage() returns FALSE. But you are checking th... |
64,866,850 | 64,866,903 | (C++) A simpler way to compare a value to every element of an array with the OR operator? | I'm trying to build a calculator in c++ using classes, and i came accross this issue. here's the code:
(it's not really an issue right now, but i can see it becoming one in the future)
char opcheck;
char opDisp[6] = { '+', '-', '*', '/', 'p', 'r' };
while (opcheck==opDisp[0] || opcheck==opDisp[1] || opcheck==opDisp[2]... | You might use std::find
while (std::find(std::begin(opDisp), std::end(opDisp), opcheck) != std::end(opDisp))
|
64,867,394 | 64,867,449 | C++ : Get a child member from the Father class | I recently asked a question related to the accessibility of a child member from a parent class using the cout method . But this time what if I want to use a get method instead of cout ? Will this change the idea ?
Assuming I have a class called CArray :
class CArray
{
public:
CArray();
private:
std::vector<C... |
what If I want to get the MatriculationNr from the first element of Persons (as an example)?
You won't be able to. Not with the code you have shown, anyway. MatriculationNr exists only in CStudent, and it is private at that, so only CStudent can access it.
cout << Persons[i]->getMatrikulNr(); is not valid since we... |
64,867,407 | 64,867,597 | Composing C++ classes with members that have extended types | How does one in C++ compose a class that has members which are types that have extensions? Take an example of a car. We have a Car and a BigCar. The Car comes with an Engine but the BigCar should come with a BigEngine. But if we just hide the engine member of BigCar with BigEngine, regular Engine will still be created ... | With a template:
#include <iostream>
class Engine {
public:
Engine() : cylinders{4} {}
int cylinders;
};
class BigEngine : public Engine {
public:
BigEngine() : Engine{}, fuel_injector{true} {
this->cylinders = 8;
}
bool fuel_injector;
};
template<typename E = Engine>
class Car {
public:
... |
64,867,479 | 64,867,549 | C++ Simple File I/O Issue | I have this bit of code that reads in a CSV .txt file laid out like this (the actual file is millions of rows long):
1,2,3,4,5,
6,7,8,9,10,
11,12,13,14,15,
16,17,18,19,20,
etc...
The purpose of the code is supposed to be to separate each column of the imported text file into a separate file. For example, with the abov... | Your loop is reading an entire line from the file, but not doing anything with that line, it is just thrown away. Inside the loop, you are then reading the next 5 individual values from the input file and writing them to the output file. But on the next loop iteration, you are again reading the next entire line and t... |
64,867,572 | 64,875,454 | How to build a node with yaml-cpp? | I want to use yaml-cpp for a project of mine to generate a yaml-file however I have trouble figuring out how exactly I have to go about this. The yaml file I need to emit should look like this:
action_counts:
version: 0.3
subtree:
- name: system
local:
- name: adder
action_counts:
... | Lots of examples of creating messages can be found in the tests of yaml-cpp library.
The desired structure can be formed as follows:
#include <fstream>
#include "yaml-cpp/yaml.h"
int main() {
YAML::Node action_1;
action_1["name"] = "add";
action_1["counts"] = 1000;
YAML::Node action_2;
action_2["n... |
64,867,807 | 64,868,051 | Method to store C++ lambda: template vs non-template form? | When it comes to receive and store a lambda function, I commonly see this:
struct foo {
std::function<void()> myFunc;
template<typename F>
void foo(F&& func) {
myFunc = std::move(func);
}
};
Does the form above offer any advantage over the form below?
struct foo {
std::function<void()> myF... | In the first form
template<typename F>
void foo(F&& func) {
myFunc = std::move(func);
}
F&& is a forwarding reference, so your usage of std::move() is incorrect - you should use std::forward<F>(func) instead. Once you apply the fix, this form will work correctly with both lvalue and rvalue arguments.
... |
64,867,905 | 64,867,948 | How can I make a dynamic array of pointers that each point to an abstract base class? | For what I'm working on, I'm making a class that holds a dynamic array of different sorts of pets. I have an abstract class of Animal, from which I have a few derived classes (Cat, Dog, Rabbit, Horse, etc.). I need to be able to add an instance of those derived classes to the end of the dynamic array. In the list objec... | Your thinking is correct, but your implementation of add() is not optimal. If nothing else, it is leaking the old pets array. But it is also just coded more complicated than it needs to be.
It should look more like the following instead (assuming pets and length were initialized properly before add() is called, and t... |
64,868,110 | 64,868,286 | How to fix memory leak with linked list? | Hi I have the following code, and keep getting memory leaks, can someone help me fix this please, I've been at this for hours but cant seem to find why there is a memory leak, I am new with nodes, I think the problem is with the destructor, but can't seem to pin point exactly what, please help!
#include <iostream>
usi... | I don't think you want destructing a node to delete the entire list. You could but I think each node should be independent of the others - the linked list class is where list level things should happen.
Also, you don't want the destructor to contain the code to clear the list because you may want to clear the list at ... |
64,868,195 | 64,916,053 | Why the model is not displayed in the center of screen? | I want to show a point cloud with VTK. I inherit a class named VTKWidget from QVTKOpenGLNativeWidget, its constructor is that:
VTKWidget::VTKWidget(QVTKOpenGLNativeWidget* parent)
:QVTKOpenGLNativeWidget(parent)
{
QSurfaceFormat::setDefaultFormat(QVTKOpenGLNativeWidget::defaultFormat());
_renderWindow = vtk... | If you want to see the whole point cloud at the end of updateData, you should use _renderer->ResetCamera().
(https://vtk.org/doc/nightly/html/classvtkRenderer.html#ae8055043e676defbbacff6f1ea65ad1e)
The fact that the location of setRenderWindow() impact the rendering is a side effect.
|
64,868,464 | 64,868,545 | Win32 Multithreaded Programming | A totally noob question.
Inside Windows. Is it possible to make a thread without directly or indirectly calling a Win32 API function? For example using assembly language to call opcodes that make the CPU do atomic operations. I'm not certain but I'm guessing that the purpose of the OS is to provide this sort of thing. ... | Atomics are a feature provided by the CPU. In general, if there's a CPU operation that you can perform, you can perform it, excepting those instructions reserved for a lower "ring" level.
Threads are a feature provided by the operating system.
As such you can't create threads1 using assembly code, your user-space code ... |
64,868,836 | 64,869,014 | std::variant and std::visit: error: no member named 'valueless_by_exception' | I have the following block of code:
std::visit([&](auto &&arg)
{
using T = std::decay_t<decltype(arg)>;
if constexpr (
std::is_same_v<T, size_t> ||
std::is_same_v<T, int> ||
std::is_same_v<T, double> ||
std::is_same_v<T, bool>
) {
document->AddMember(value.first.c_st... | The arguments to std::visit (value) should be std::variants but seems to be a std::pair.
Example:
#include <string>
#include <utility>
#include <variant>
int main () {
std::variant<std::string> foo;
std::visit([](auto&&){}, foo); // OK
std::pair<std::string, std::variant<std::string>> bar;
std::vi... |
64,869,188 | 64,869,381 | Pass a pointer by const reference | Is passing a pointer by const reference not done for optimization?
Ex.
bool testHelper(const TreeNode*& p, const TreeNode*& q) {
return false;
}
TreeNode* test(TreeNode* root, TreeNode* p, TreeNode* q) {
recursiveHelper(p, q);
}
Error:
Line 17: Char 28: error: binding reference of type 'const TreeNode *' to v... |
Is passing a pointer by const reference not done for optimization?
No, it isn't, because it isn't any faster. The added indirection is potentially slower.
bool testHelper(const TreeNode*& p, const TreeNode*& q)
Those are not references to const. Those are references to non-const pointers to const.
Other bugs:
t... |
64,869,249 | 64,869,547 | Is *a+=*b same as int sum = *a+*b where sum = *a? | #include <stdio.h>
#include <cmath>
void update(int *a,int *b) {
*a = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*b = absDifference;
}
/*
void update(int *a,int *b) {
int sum = *a + *b;
int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b);
*a = sum;
*b = absDiff... | There is no difference between *a+=*b and int sum = *a+*b where sum = *a.
But! Where you put your condition check makes a lot of difference.
In first function, the *a is being added with *b and then condition check is for *a - *b which is nothing but original (or old) value of *a.
*a = *a + *b;
int absDifference = *a -... |
64,870,058 | 64,870,149 | How to cout all integers that user entered backwards | This is the first part that will get integers from user until zero is entered
int n ;
for ( int i = 1 ; n != 0 ; i++ ){
cin >> n ;
}
But I have no idea how to print all the given numbers backwards
| You should save all input numbers to container (for example std::vector). And after just make output in other order.
std::vector<int> vec;
for ( int i = 1 ; n != 0 ; i++ ) {
cin >> n ;
}
vec.pop_back();
std::copy(vec.rbegin(), vec.rend(), std::ostream_iterator<int>(std::cout, "\n"));
|
64,870,367 | 64,879,768 | cublasGemmEx result is always zero | I tried matrix multiplication using cublasGemmEx. A and b are 1X1 half matrix. The result is always zero if i set the compute type and output date type to CUDA_R_16F. And the result is correct if i set compute type and output date type to CUDA_R_32F.
Does anyone know that why the result is zero if i set types to CUDA_R... | According to the documentation for cublasGemmEx, specifically for alpha and beta parameters, both say:
of same type as computeType
However your code does not satisfy that requirement. For the (working) CUDA_R_32F case, your alpha and beta arguments of type float are matching. For the (non-working) CUDA_R_16F case, ... |
64,870,619 | 64,877,838 | Convert std::string to std::chrono::duration | My goal is to convert one single string in the form "%H:%M:%S" to chrono::duration in C++11.
As an example, in order to convert "00:15:00",
I came up with the following indirect solution where I calculate two timepoints (1) "00:15:00" and (2) "00:00:00", which are with respect to the system_clock or steady_clock: I th... | Your current solution has the potential to very rarely give you incorrect answers. If your two local times happen to straddle a UTC offset change in your local time zone (e.g. a daylight saving shift), then the amount of that shift is going to be included in the subtraction, subsequently giving you the wrong answer.
I... |
64,870,703 | 64,872,809 | Why can't Visual Studio find my main function once I add an hlsl/fx file? | Sidenode: I'm not asking anyone to help me with a directx tutorial. I think this error is a normal Visual Studio win32 API error.
Hey guys and girls,
I'm trying to learn some DirectX 11 for fun and I found those directx11 examples on github. Now I'm trying to understand each function and see how everything works togeth... | With the help of github demo, I can reproduce this problem. You can refer to the screenshots below to modify:
Tutorial02.fx properties:
Tutorial02_PS.hlsl properties:
Tutorial02_VS.hlsl properties:
You can also refer HLSL Property Pages to learn how individual HLSL shader files are built.
|
64,870,870 | 64,871,099 | Build error with Make for C++ code in OSX | I have been trying to compile a repository in OSX unsuccessfully.
The repository is in C++. When I use cmake and then make in Ubuntu, all is good. Even on Windows with MinGW, I am able to build the code.
However, in OSX 11.0.1 Big Sur, I get no errors with cmake, but make fails. I have installed the latest version of X... | You could try to force CMake to use gcc by setting the flags:
cmake -DCMAKE_C_COMPILER=/usr/local/bin/gcc -DCMAKE_CXX_COMPILER=/usr/local/bin/g++ ...
or maybe provide -Wno-c++11-narrowing flag to cmake.
This post is a good resource for adding compilerflags via the command line. But if you own the project you're trying ... |
64,871,437 | 64,871,505 | Template argument deduction for inherited member function | I struggle with the following issue but are somehow too blinded to see the (probably obvious) solution:
I'm writing a class to store invocables with a specific signature (which is given as template arguments to that class). For my MCVE, I left this part out and just assume void() because this part is not the issue.
So,... | Issue with inherited member is that you might have deduction as
void call(Derived *pObj, void(Base::*pFunc)())
So doesn't match your signature.
You might fix it with
template <typename C, typename C2>
void call(C *pObj, void(C2::*pFunc)())
{
std::cout << "call(C *pObj, void(C::*pFunc)()):\n";
(pObj->*pFunc)();
}
... |
64,871,494 | 64,871,959 | What is the correct order to traverse the states in the popular Coin-Change dynamic programming question? | I was solving this(https://www.hackerrank.com/challenges/coin-change/copy-from/188149763) problem on Hackerrank which can be summarized as follows :
Find the total number ways to exchange a certain value with the given set of coin denominations.
Here is my code which got accepted:
long getWays(int n, vector<long> c) ... | The first code updates number of ways to compose values dp[i] with new coin.
After k-th round of outer loop we have dp[] array filled with combinations of k coins only, and the rest of coins is not used yet. If we make output of combinations themselves for sorted coin list, we will see ordered ones like 1 1 5 - 5 nev... |
64,872,302 | 64,872,327 | For loop does not run C++ | The output is 21 meaning it has entered the printBoard function and has exited it. I have tried making a test variable and doing something with it in the for loop, but it didn't do anything, so therefore for some reason the for loop does not execute.
#include <iostream>
void printBoard(){
std::cout << "2";
fo... | The second part of the for loop is the condition that needs to be true for the loop to execute. i == 8 is not true (because i is 0), so the loop will never run. You want i <= 8 if you want to count until 8.
|
64,872,397 | 64,873,008 | passing function template prototype as argument | I am trying to pass a templated function to another, like this:
template<typename T = bool>
void fun() {}
template<typename F>
void higher_order_fun( const F & f) {
f();
}
int main () {
//higher_order_fun(fun<>); //works
higher_order_fun(fun);
}
In gcc10.2 I am able to pass fun (a template prototype) in ... | All standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS.
This is arguably a GCC bug (/extension feature), although I have not been able to find a ticket for it.
As per [temp.names]/1, you may refer to a template specialization by means of a template-id. The grammar for the latter doe... |
64,872,605 | 64,886,471 | How can I set the 'Enable Enhanced Instruction Set' in msbuild? | How can I set the value of the param 'Enable Enhanced Instruction Set' when compiling with msbuild from command line ?
| To realize this, it might be a complex but can be done. You only need to be with the help of a MSBuild property to transmit the value from msbuild command line into the EnableEnhancedInstructionSet Item matadata.
MSBuild can transmit the msbuild property rather then item metadata.
Solution
Modify these on your xxx.vcxp... |
64,872,623 | 64,873,409 | Print n-array tree from parent array | I need to write a recursive algorithm to pretty print an n-array tree with the parent array given.
This is my code:
int pretty_print_r1(int* parent, int i, int indent, int target, int size)
{
if (i > size) return NULL;
if (parent[i] != target)
{
pretty_print_r1(parent, i + 1, indent, target, s... | You might do
void pretty_print_r1(const int* tree, std::size_t size, int parent, int indent)
{
for (std::size_t i = 0; i != size; ++i)
{
if (tree[i] == parent) {
std::cout << std::string(indent, ' ') << i + 1 << std::endl;
pretty_print_r1(tree, size, i + 1, indent + 4);
}... |
64,872,783 | 64,873,269 | Connecting to gmail smtp server using c/c++ (sockets) | Im tryin' to connect to google smtp server ("smtp.gmail.com") with pure socket.
I created a socket, connect when i read data gives me only "54" or "52" or "53" or "54".
sockaddr_in service;
WSADATA wsaData;
struct hostent* remoteHost;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result !... | recv take as argument the buffer and return the number of bytes recieved, bytesRecv in your code is number of bytes recieved (54 bytes) and not the bytes, to find what google answerd you you need to display recvbuf
std::cout << recvbuf << std::endl;
|
64,872,962 | 64,874,689 | Determine if some relative directory is part of absolute path using std::filesystem::path | I can't figure out how to identify if absolute path contains some relative directory inside it using std::filesystem::path but still with no luck. I have the following peace of code:
const std::filesystem::path absolutePath = "/Users/user/Library/Preferences";
const std::filesystem::path relativePath = "Library/Prefere... | The std::filesystem::path class provides iterators to the first and one past the last element. So you could search for the relative path inside the absolute path using std::search:
#include <algorithm>
#include <filesystem>
namespace fs = std::filesystem;
bool isSubDirectory(const fs::path& absolutePath, const fs::pa... |
64,873,467 | 64,873,519 | How to break a loop when "enter" is pressed in C++ while taking input in an integer array | I have this loop, where arr is an integer array.
for(int i=0; i<=counter;i++)
{
cin>>arr[i];
}
I'm giving input like this
2 4 6 7
I want when enter is pressed after 7, just break this loop.
I think it can be done with something like
if(cin.get()=="\n")
But I can't understand how to implement it here... | If you wanted to exit your for loop when you press the Enter Key. You would need to check the given input before putting it in your array.
And if it is equal to '\n', leave the for loop with break.
for (int i = 0; i <= counter; i++) {
// Check if user pressed the Enter Key
if(std::cin.peek() == '\n') {
... |
64,873,544 | 64,873,613 | Passing the address of dereferenced smart pointers to functions that expect raw pointers | (assuming that I am working with a library or framework that expects usage of raw pointers,)
Is it valid practice to use a smart pointer which owns some data, and then pass the address of the derefenced smart pointer to a function that expects a raw pointer?
| Yes, that is valid practice. The std smart pointers have a get() member function exactly for that purpose.
In general, when you manage an object through smart pointers, you should only pass the whole smart-pointer-object as is to other functions when these functions imply ownership semantics: if a function will copy a ... |
64,873,884 | 64,874,280 | Storing multiple int values into one variable - C++ | I am doing an algorithmic contest, and I'm trying to optimize my code. Maybe what I want to do is stupid and impossible but I was wondering.
I have these requirements:
An inventory which can contains 4 distinct types of item. This inventory can't contain more than 10 items (all type included). Example of valid invent... |
Storing multiple int values into one variable
Here are two alternatives:
An array. The advantage of this is that you may iterate over the elements:
int variable[] {
1,
1,
1,
0,
};
Or a class. The advantage of this is the ability to name the members:
struct {
int X;
int Y;
int Z;
int W... |
64,874,212 | 64,874,278 | Integer literal with single quotes? | What exactly as been assigned to value? I am surprised that this has compiled at all.
//g++ 7.4.0
#include <iostream>
int main()
{
auto value = 123'456'7;
std::cout << value << std::endl;
value += 1;
std::cout << value << std::endl;
}
outputs:
1234567
1234568
| Since C++14,
from https://en.cppreference.com/w/cpp/language/integer_literal
Optional single quotes(') may be inserted between the digits as a separator. They are ignored by the compiler.
|
64,874,358 | 64,874,556 | Macro for nested i, j loop | How do you write a macro that can be used as follows:
FOR(n)
FOR(j, n)
//do stuff
and that expands to a valid nested C++ for loop, with:
FOR(n) will use a loop variable named i (default case) and with an invariant of less than (<) n,
FOR(j, n) will use a loop variable named as the first argument (j) and w... |
I'm aware it's bad practice to do things like this [...]
Let's start off by emphasizing this once more: yes, this is horrible practice.
Now, what looks like macro overloading is actually macro dispatch, as covered in detail in e.g. the following Q&A:
Can macros be overloaded by number of arguments?
Using the libra... |
64,875,040 | 64,912,690 | Replacing Field values in Word Document QAxObject QT / C++ | I'm really new to QT and I was tasked to update some field values in word document programmatically, currently I can replace text from word document fine, but when that field value is inside an object (table or anything) it's not working, my code is:
QString outFile("D:\\#test files\\output.docx");
QString ... | If you can change the nature of the target files, you would do well replacing your targets with real Word DocVariable or DocProperty fields. Then use your code to change the variable or properties and update the related fields in the documents. Some document properties (under the Quick Parts > Document Properties menu)... |
64,875,101 | 64,875,669 | How to match two C-style arrays into google mock? | I would like to check if the rbMapDataSecS_VerifySHA function is called with these two C-style arrays.
I can't write With twice.
How can I get it?
Process finished with exit code 1
Failure
.With() cannot appear more than once in an EXPECT_CALL().
EXPECT_CALL(g_objRbMapDataSecSMock, rbMapDataSecS_VerifySHA(_,size,_,bu... | Ok I read a more carefully error message and problem is quite simple.
Here is MCVE where I strip your implementation detail, reproduce it and fix it:
using testing::_;
using testing::AllOf;
using testing::Args;
struct TestMock {
MOCK_METHOD(bool, foo, (int a, int b), ());
};
TEST(MockUseWith, ReproduceIt)
{
... |
64,875,116 | 64,875,416 | C++ self registering class member | I'm looking for a way to achieve the following: A client class foo either inherits from a class named properties or uses it as a class member. The client class foo may also have zero or more members of type property. Each property member should self-register itself with the properties instance of the client class:
stru... | You can't do it fully automatically but you can get somewhere near:
#include <map>
#include <variant>
#include <string>
#include <memory>
template <typename T>
struct property {};
struct properties
{
std::map<std::string, std::variant<std::shared_ptr<property<int>>>> properties;
template <typename T>
std... |
64,875,125 | 64,875,286 | C++14 Function returns array of objects although copy constructor is deleted | from the old C++98 i am aware, that return types a copied (by value) if not mentioned in the function declaration/definition otherwise with the address operator '&'.
Now i am playing around with the concepts of auto and decltype to let the compiler determin the return type. In an example i worte a class A where with e... | decltype(auto) is used to determine the type and the value category of an expression. When used as a return type, it lets the function decide what the returned value type should be, based on the expression in the return statement. In this example, since you are using a temporary in the returned expression, it will dedu... |
64,876,161 | 64,876,756 | How do I call template array operator overloading function? | I need to create an adapter C++ class, which accepts an integer index, and retrieves some types of data from a C module by the index, and then returns it to the C++ module.
The data retrieving functions in the C module are like:
int getInt(int index);
double getDouble(int index);
const char* getString(int index);
// ..... | The simple answer is: No, not possible. You cannot overload a function based on its return type. See here for a similar quesiton: overload operator[] on return type
However, there is a trick that lets you deduce a type from the lhs of an assignment:
#include <iostream>
#include <type_traits>
struct container;
struct h... |
64,876,368 | 64,876,677 | this changes value in default and non-default constructor | I have a problem where I need to initialise a member object via a non-default constructor. However the compiler insists that I create a default constructor for the member object, which is called before the non-default constructor.
Consequently, the "this" pointer for the member object has different values in the defaul... | You're loooking at this in two different objects - the second is created in the assignment
B = my_object(0);
which creates another my_object and assigns its value to B (which has already been created).
The only way to initialize members is to use the initializer list:
my_first_object() : B(0)
{
}
The reason for the ... |
64,876,858 | 64,929,991 | Pointer is NULL even when directly assigned to non-NULL pointer | Okay so sorry if the title is hard to understand I wasn't sure what to call this.
I have a pointer in my gameObject object that points to a object called game and is by
default a nullptr.
class GameObject
{
public:
class Game* game = nullptr;
GameObject(float x, float y, const std::string &path);
};
In game I ... | When adding the GameObject to the m_objectList, the value of that GameObject is being copied so any changes made after that addition is worthless as the Game object is only awear of the copy.
Using a vector of pointers solves this issue.
void Game::addGameObject(GameObject& gameObject) {
GameObject* go = &gameObjec... |
64,876,968 | 64,877,142 | No client URI found in getBuildTasks() - VSCode - C++ | On trying to debug a C++ code on VSCode, I am getting the error, "No client URI found in getBuildTasks()"
I am an absolute beginner and am just learning C++ and just set up my VSCode from a tutorial to run C++ on VSCode with minGW-w64. But the debug button just won't work like it should have and is instead throwing tha... | You need to open the Folder that you're working in, into the Workspace.
To do this, select Explorer from the left side bar and click on the big blue Open Folder button over there and open the Folder that you're working on and containing the .vscode subfolder.
.
.
The Desktop is where I build most of my smaller, quicker... |
64,877,345 | 64,877,651 | Can I display a local variable as specific struct/data type while debugging? | I'm debugging a program that I have the symbols of, and I'm trying to check what is the value inside a given variable - data from the WinDbg console.
The declaration of data is as follow: std::vector<unsigned char> data;, but I know that it contains a struct, let's call it MY_STRUCT.
Is there any easy way to display th... | Well, after searching in the documentation and trying a few methods, I have found two possible solutions:
First - using dt command:
dt -a <ADDRESS_OF_DATA> MY_STRUCT
Second option:
dt MY_STRUCT <ADDRESS_OF_DATA>
|
64,877,472 | 64,877,605 | What is the purpose of std::chrono::duration::zero() | Why is there a static function that returns the zero representation of a std::chrono::duration type ?
Isn't:
std::chrono seconds s;
s = std::chrono::seconds(0);
exactly the same as:
std::chrono::seconds s;
s = std::chrono::seconds::zero()
?
And is there a generic chrono::duration::zero object/function, that has an i... | It is to give some flexibility to the implementation, in the case where the duration of zero is not represented by Rep(0).
std::chrono::duration<Rep,Period>::zero
If the representation rep of the duration requires some other implementation to return a zero-length duration, std::chrono::duration_values can be specializ... |
64,877,559 | 65,542,254 | Can't use iostream as module in C++20 (Visual Studio) | I can't get this code running in the newest version of MSVC. This code example is from the book called "Beginning C++20, From Novice to Professional" by Ivor Horton and Peter Van Weert.
import <iostream>;
int main()
{
int answer {42};
std::cout << "The answer to life, universe, and everything is "
... | The authors stated in the example and solution files provided for download, that due to compilers' implementations of the C++20-standard the files might not work yet (see the book's page for details and corresponding GitHub repository).
Therefore they provide "no modules" examples which use the "#include" directive.
|
64,877,821 | 64,880,995 | How can I delete terms with zero coefficient in linkedlist? | I add a node to poly. If there already
is a node with the same exponent, then I sum the coefficient
to the existing coefficient. But when I run this code, output is +0.0x^7 +0.0x^5 +0.0x^4 +0.0x^3 at the end. I'm trying to delete terms with zero coefficient in the function.How can I do this ?
struct PolyNode {
... | If we're keeping with the style you've established, then this should work.
PolyNode** first = &head;
PolyNode** second = NULL;
while (*first != NULL && (*first)->next != NULL) {
second = first;
first = &(*first)->next;
if ((*second)->exp == (*first)->exp) {
... |
64,879,297 | 64,880,239 | error C2440: 'initializing': cannot convert from 'const char *' to 'TCHAR *' | In a multibyte project (vs2017):
#ifndef _TCHAR_DEFINED
typedef char TCHAR;
typedef char * PTCHAR;
typedef unsigned char TBYTE;
typedef unsigned char * PTBYTE;
#define _TCHAR_DEFINED
struct _getopt_data
{
/* These have exactly the same meaning as the corresponding global
variables, exc... | In C++, _tcschr() is overloaded to take either a TCHAR* or a const TCHAR* as input. To return a non-const TCHAR*, you will have to call the non-const overload, which means casting away the const off of optstring, eg:
TCHAR *temp = _tcschr(const_cast<TCHAR*>(optstring), c);
Or else define _CONST_RETURN, per the docume... |
64,879,451 | 64,879,802 | How to make a common reusable function with different class types to reduce the code duplication using C++ | I am invoking the below function from different classes and files like as shown below.
And the implementation is almost similar. But it is initializing in the respective class constructor.
Can I create a common function for the below code for all the classes
and then when invoking, based on the class can I initialize a... | Not sure to understand what do you exactly want... but... what about as follows?
template <typename RetType>
shared_ptr<RetType> BaseClass::createTestObject (std::string const & f_strSFID,
short f_nID,
bool f_bIsVerified,
... |
64,879,496 | 64,879,716 | Editing a QVariantMap from QML | I have a QVariantMap created in C++ from a JSON object and I want to update this object from QML. I set it as a context property.
// main.cpp
engine.rootContext()->setContextProperty("myjson", myqvariantmap);
In QML I tried updating its properties but it seems to be read-only. The docs support this, saying
Mind that ... | One possible option is QQmlPropertyMap:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlPropertyMap>
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlPropertyMap qpropertym... |
64,879,738 | 64,879,819 | C++ Base class undefined while compiling | I get GameObject: base class undefined while trying to compile. I don't see anything wrong. I have a parent-child relationship between GameObject and player:
GameObject.h
#pragma once
#include "Game.h"
class GameObject
{
protected:
int x, y;
SDL_Texture* objTexture;
SDL_Rect srcRect{}, destRect{};
public... | It would help if you gave us the exact error message and pointed to the line number.
I suspect this is because your GameObject has a constructor that requires arguments but your Player class does not provide these arguments in its constructor initialization list.
But this is just a guess.
A new guess!
The #include "Gam... |
64,879,742 | 64,879,938 | How to concatenate name of variables in Cpp? | I have class Walls in my program. Inside of class are objects Wall1, Wall2 etc.
I want to do something like this:
class definition:
class Walls {
public:
Walls(){
nPositionX = nMapWidth - 1;
nHoleSize = 1;
nHolePosition = rand()%(nMapHeight - nHoleSize);
count++;
}
stati... | You can use an array or std::vector for that, eg:
std::array<Wall, MAX_WALLS> m_walls;
or
std::vector<Wall> m_walls;
...
// initialize m_walls[0], m_walls[1], etc as needed...
...
for (size_t i = 0; i < m_walls.size(); i++) {
int nPosx = m_walls[i].getPositionX();
...
}
Or, you can use a std::map, eg:
std:... |
64,879,890 | 64,880,521 | Why does assignment operator not work as expected? | UPD: I can see now how stupid this question is, it's just my misunderstanding of C++ constructions.
I got stuck with operator assignment problem - it doesn't work as expected. Here's the example code:
#include <iostream>
class TestClass{
private:
int pop;
public:
TestClass(){
std::cout<<"Default Constu... | I see several issues with this code:
pop is not being initialized in the default constructor (which you are not calling, but you should still implement it properly, if you are going to implement it manually at all).
operator= is not updating the value of this->pop at all, which is the root cause of your issue. If yo... |
64,880,014 | 64,880,107 | Is there a way to store a static pointer address in an enumeration in C++ | This might not be possible in C++, but I am not sure why. I have been searching stack overflow and google but I'm unable to find an answer.
First I will state the assumptions I'm working off of.
First Assumption: If I have this code at a global scope. I would expect it to be stored in the Data segment of the program wh... | test1's address is not known at compile time (things like address space layout randomization affect it), and it certainly isn't known while compiling (because variables aren't laid out together in the data segment until linking).
Your question really sounds like an XY problem. If you have a bunch of unique char*s, why ... |
64,880,362 | 64,881,732 | How does std::cout convert numerical types to base 10? | I've learned that numerical types, such as int and long long, are stored in a base-two format in C++. These individual bits can be accessed and modified using bitwise operators.
However, I recently wondered why numbers weren't printed to the screen from std::cout in base 2 as well, and thought that they must've been co... | I find the libstdc++ (gcc's standard library) source almost unnavigable, but I think the meat of it is done here:
https://github.com/gcc-mirror/gcc/blob/8e8f6434760cfe2a1c6c9644181189fdb4d987bb/libstdc%2B%2B-v3/include/bits/locale_facets.tcc#L794
Which appears to use the good ol' "divide by 10 and print remainder" tech... |
64,880,429 | 64,922,866 | I get this error code in VS: 0x80070002 c++ | When i try to run a code with the function "strtok" in it i get the error code 0x80070002. I included cstring, cctype, string.h and i also tried using /DEBUG FULL in Properties - Linker - Debugging, like a few other posts said but it still doesn't work. Any clues why VS doesn't work with strtok? I also tried reinstalli... | There are two methods to meet your needs;
Add _CRT_SECURE_NO_WARNINGS in Properties->C/C++->Preprocessor->Preprocessor Definitions.
Use strtok_s instead of strtok:
int main()
{
char *buf;
char s[100], *p;
cin.getline(s, 100);
p = strtok_s(s, " ", &buf);
cout << p;
return 0;
}
|
64,880,497 | 64,880,692 | C++ pointers vs std::vector: any implication for long size variables? | I have a C background and I am recoding some old code in C++...
In the process, I am starting to use C++ Vectors, which are so easy to use!
Would vectors deal well with very long streams of data? For example, in audio apps, loading a stereo 3 minutes song would need almost 16M floats
float *stereoSong = NULL;
stereoSon... | This is a false comparison.
For a start, vectors use pointers. They have to. Vectors are containers that use dynamic allocation to provide you with a buffer of data items. You could try to implement the same thing "with pointers", but you'd end up with something someway between a vector, and a worse version of vector.
... |
64,881,178 | 64,882,313 | Return folder path of graphics in Qt projects | For designing a custom made pushButton I added a picture source (1):
#include "mybutton.h"
#include <QDebug>
#include <QDir>
#include <QIcon>
#include <QPixmap>
MyButton::MyButton(QWidget *parent) : QPushButton(parent) {
QPixmap pixmap("/home/myCode/MyButton/MyButton/graphics/myPicture.png"); //(1) picture source
... | Like you mention adding resource file works fine.
Add new file: Qt->Qt Resource File (resource.qrc)
Project tree is added with "Resources"-folder
Open folder
Right-Click resource.qrc
Add Prefix /
Add image files to that prefix which are located in graphics folder
Right Click on object and copy path
Add copy as resourc... |
64,881,683 | 64,883,420 | Can't get SDL2 to work with MinGW, VSCode and CMake on Windows 10 | I want to use VS Code, mingw and Cmake on Windows 10. I made a simple app:
-SDL2
-main.cpp
-CMakeLists.txt
This is the current content of my CMakeLists.txt
cmake_minimum_required(VERSION 3.19.0)
project(main VERSION 1.0.0)
list(APPEND CMAKE_PREFIX_PATH SDL2)
find_package(SDL2 REQUIRED)
add_executable(main main.cpp)
... | If you use vcpkg you need to set the toolchain file somewhere.
Either in CMakeLists.txt or you can set it in a command line argument:
1. CMakeLists.txt:
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake
CACHE STRING "Vcpkg toolchain file")
NB! Make sure that you get the path... |
64,881,867 | 64,881,895 | C++: Is raw string literal null terminated like normal string literal? | I know that a string literal is always null terminated, even "" has a length of 1.
Is it the same case with raw string literal, ex: does R"()" has a length of 1?
| Raw string literals are just normal C strings that ignore escapes, which means they're still null-terminated. It's not like "foo"s, which is an actual c++ std::string, which isn't necessarily null-terminated.
|
64,881,885 | 64,881,953 | How to make a form in a panel stop moving in VisualStudio? | I created two forms and adding one panel on each. The button from the first form opens the second one, and the button from the second one opens the first form. The problem is that whenever i press the button to see the other form, the whole panel moves!
This is the code i have for the both buttons.
private void... | I would change the color of the whole Form like this
this.BackColor = Color.FromArgb(0, 0, 0); // this is black
|
64,881,925 | 64,895,694 | Convert a string with micro second precision to a chrono time_point | This is a quite trivial question. But I couldn't find a trivial answer for this.
I have a timestamp string with microsecond precision, say, 20:38:42.444491. How do I convert this into a proper time object so that I can use it in time comparisons etc...
I was trying to use the date lib by HowardHinnant. However I am not... | With just a time, you've got a couple of options. But you should definitely not put "just a time" into a system_clock::time_point. The reason for this is that system_clock::time_point has a specific meaning: This measures the time since (or before) 1970-01-01 00:00:00 UTC, excluding leap seconds.
To be fair, this me... |
64,881,966 | 64,882,363 | Trying to write a DLL for wallhack usw | I'm trying to write a DLL file that I can inject into a game. I'm pretty far but when I try to compile the code I always get the error
Error LNK2001 Unresolved external symbol "" unsigned char * __cdecl Detours :: X86 :: DetourFunction (unsigned char *, unsigned char *, enum Detours :: X86Option) "(? DetourFunction @ X... | You can't just replace function definition:
uintptr_t DetourFunction(uintptr_t Target, uintptr_t Detour, X86Option Options = X86Option::USE_JUMP);
with
uint8_t *DetourFunction(uint8_t *Target, uint8_t *Detour, X86Option Options = X86Option::USE_JUMP);
Why can't you use uint8_t? Can't you just add:
typedef unsigne... |
64,882,046 | 64,882,742 | Linking two separate cmake projects where one is dependant on the other | I have two separate projects, A and B. Both have large folder structures, lots of dependencies and both have their own CMakelists.txt structures as well. Neither depend on each other.
I am adding new functionality to project A that depends on a header from project B, along with the network of files in Project B that he... | Project B should export its targets.
That way, in project A, you could do something like this:
find_package(B REQUIRED)
target_link_libraries(A PUBLIC B::B)
And when invoking CMake, add B's build directory in the prefix path:
# in A/build
cmake .. -DCMAKE_PREFIX_PATH=/path/to/B/build
But in order for that to work, yo... |
64,882,090 | 64,882,149 | C++ : Size of the array didn't change even after deleting it | Assuming I have this program below
The size of the array is 3 and basically when deleting it and then try to print the size again , I still get the value 3 .
Why is that ?
#include <vector>
#include <iostream>
int main(){
std::vector<int*> v;
v.push_back(new int{1});
v.push_back(new int{2});
v.push_bac... | You have a vector of pointers. Using delete on a pointer in that vector will delete the thing the pointer is pointing at. It does not remove the pointer itself from the vector, and so does not change the size of the vector. Why should it? How could it?
Here the code you were looking for (I guess):
for (int i = 0; i <... |
64,882,187 | 64,882,791 | CUDA shows error as "Invalid Argument" for matrix - multiplication of N times | I am trying to multiply matrix A (n times) with matrix B. I have used kernel for matrix multiplication and using stream to do this multiplication N times. I have 3 conditions to test consequently. My 1st condition is running successfully.
I don't know why it is showing error of "Invalid Argument" in the second conditio... | Suggestion: Implement proper CUDA error checking. Use it on every cuda call. Your haphazard use of the error checking macro makes for a confusing output that seems to suggest a problem with stream creation.
That is not the case. The invalid argument is arising from your freeing operations at the end of the loop. Y... |
64,882,321 | 64,883,381 | allocate array from file data c++ | Here is my code where prime.txt contains some primes: 7, 11, 13, 17, 23... :
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string file= "primes.txt";
ifstream fichier;
fichier.open(file);
int count = 0, prime;
int *buff... | You can avoid writing the loop if you use iterators or ranges. Here is an equivalent example using ranges:
auto view = std::ranges::istream_view<int>(fichier);
auto copy_result = std::ranges::copy(view, buffer);
int count = std::distance(buffer, copy_result.out);
The loops are still there, inside the standard library.... |
64,882,524 | 64,882,782 | Number swapping: How do I get this program's main function to call the reference function? | So I have this program where it swaps the two numbers entered by the user, only problem is that I can't get the main function to call the function that does the swapping, here's the code:
#include <iostream>
using namespace std;
float first,
second;
void swap(float first, float second);
int main()
{
// Prompt ... | In your function declaration you have first and second passed by value:
void swap(float first, float second);
This needs to be passed by reference, as given in your function definition:
void swap(float &number1, float &number2);
Just as a heads up, you'll notice that when you run it it'll print out number2 twice. Whe... |
64,882,814 | 64,882,908 | Using a big struct as parameter with std async causes bug | I have a big struct that needs to be processed. So I use std async to do it on another thread. Here is a simple example below:
#include <iostream>
#include <future>
using namespace std;
struct teststruct{
float thisvalue[32][32][64];
};
void foo(teststruct thisdummy) {
this_thread::sleep_for(chrono::millis... | You are probably blowing the stack.
sizeof(teststruct) is 32*32*64*sizeof(float). Assuming a 4-byte float, that's 256KB that you are attempting to pass by value into foo.
While there are flags you can pass to the compiler to increase stack size, you really want to avoid passing large objects by value. As that require... |
64,883,044 | 64,883,147 | Why does is_invocable work differently with reference parameters? | It seems to work differently only for this one case. What is going on here?
#include <type_traits>
void foo_value(int i){}
void foo_ref(int& i){}
void foo_cref(const int& i){}
int main()
{
static_assert(std::is_invocable<decltype(foo_value), int>::value);
static_assert(!std::is_invocable<decltype(foo_ref), in... | The is_invocable and similar type traits allow you to specify not only the types of the arguments, but also their value categories. If T is some non-reference, non-void type, then for the purposes of is_invocable:
T means "rvalue of type T".
T& means "lvalue of type T".
Since foo_ref cannot be called with an rvalue o... |
64,883,142 | 64,883,437 | Why I can't pass an array to function template? | I have this example from C++ 5th ed.:
template <typename T> T fobj(T, T); // arguments are copied
template <typename T> T fref(const T&, const T&); // references
string s1("a value");
const string s2("another value");
fobj(s1, s2); // calls fobj(string, string); const is ignored
fref(s1, s2); // calls fref(const string... | For this function template:
template <typename T>
T fref(const T&, const T&);
when you make the call:
int a[42];
fref(a, a);
template argument deduction will deduce T to be int[42]. The call fails to compile, but the reason in your question, i.e. // error: array types don't match is incorrect, because the array typ... |
64,883,986 | 64,884,153 | C++ atomics: how to allow only a single thread to access a function? | I'd like to write a function that is accessible only by a single thread at a time. I don't need busy waits, a brutal 'rejection' is enough if another thread is already running it. This is what I have come up with so far:
std::atomic<bool> busy (false);
bool func()
{
if (m_busy.exchange(true) == true)
retur... | Your code looks correct to me, as long as you leave the critical section by falling out, not returning or throwing an exception.
You can unlock with a release store; an RMW (like exchange) is unnecessary. The initial exchange only needs acquire. (But does need to be an atomic RMW like exchange or compare_exchange_str... |
64,884,024 | 64,884,861 | How can I compare types in C++? | is there a way to compare types of variables in C++? For example, I want something that works like this: (using pseudolanguage)
template <class T> void checkType(T variable) {
if(type_of(T) == int) cout << "The variable is of type int.\n";
}
EDIT 1: I tried to use is_same, but it didn't work in Xcode...but when I ... | Looking at the code in EDIT 2, you may want to use if constexpr there instead (assuming a C++17-compliant compiler). The issue here is that normally the compiler will need to syntax check your code for all branches of the if statement, even if logically only one branch could possibly be taken for a given template insta... |
64,884,080 | 64,884,125 | std::out_of_range exception is not thrown | // The following code works fine, throwing a std::out_of_range exception:
std::vector<double> vd{ 1.5 };
try {
int i{ -1 };
double d = vd.at(i); // exception is thrown
}
catch (std::out_of_range& re) {
std::cout << "Exception is " << re.what()... | Because the loop does not execute. -1 < vd.size() is false.
size() returns an unsigned value. So before comparing the two numbers -1 is converted into an unsigned value. This conversion is done modulo the largest unsigned value plus one, which means that -1 is converted to the largest possible unsigned value. That is t... |
64,884,113 | 64,884,114 | How to make a callback in C++: use a class member function as a parameter | I started using C++ recently and at one point I needed to set up a callback, i.e. call a function of another class and pass to it as a parameter the name of one of my own functions so that it calls it back. At first I tried this:
void myOtherFunction(void (*oneOfMyFunctions)(void)) {
oneOfMyFunctions();
}
Unfortun... | Here is a working way to do that:
void myOtherFunction(std::function<void()> oneOfMyFunctions) {
oneOfMyFunctions();
}
And inside my class:
myOtherFunction([&] {
oneOfMyFunctions();
});
Some explanations:
In std::function<void()>, void is what is returned by the function and () contains the types of its param... |
64,884,174 | 64,884,359 | Polymorphism - using behavior class to compute new position for runner object | I'm creating a program that will simulate a race between various runners, using behavior classes to implement different types of runner movements.
To do this, an abstract MoveBehaviour class will be implemented, along with several other concrete sub-classes. One of these sub-classes is the JumpBehaviour class which kee... |
I'm confused as to what I'm supposed to put in move() in the JumpBehaviour class. I know I would generate a random number using my Random.cc class, but I'm stumped on how to achieve the 'moves it forward by a random number between 1 and 8 of columns to the right.' The oldPos and newPos parameters confuse me as I'm not... |
64,884,195 | 64,884,622 | MinGW g++ extremly slow compiling | I started using Vim for C++ competitive programming and i have a problem . For compiling i am using MinGW g++ compiler as in tutorials . Code compiles , but i have issue that , any program compiles and runs extremly slow . For example to compile and run next code:
#include <iostream>
using namespace std ;
int main()
... | It's an shame to say this , but problem was in Antivirus . As i think it slow downs process to check for some virus
|
64,884,297 | 64,884,429 | Typeinfo how to get the name/id of the class in a polymorphic collection? | In the following example I would expect not stdout : Base Foo Bar, but I get P4Base P4Base P4Base:
#include <iostream>
#include <typeinfo>
#include <vector>
#include <memory>
class Base {};
class Foo : public Base {};
class Bar : public Base {};
using Collection = std::vector<std::unique_ptr<Base> >;
int main() {
... |
Typeinfo how to get the name/id of the class in a polymorphic collection?
Firstly, the classes must be polymorphic in order for typeid to provide the dynamic type. Your classes are not polymorphic, so you would get the static type.
Secondly, you must use an lvalue to the pointed object instead of a pointer. Applying... |
64,884,491 | 64,884,550 | Why std::basic_fstream<unsigned char> won't work? | When trying to compile this code:
std::fstream file("file.name", std::ios::out | std::ios::binary);
uint8_t buf[BUFSIZE];
//Fill the buffer, etc...
file.write(buf, BUFSIZE);
compiler will give me warning about oh-not-so-healthy conversion from unsigned char to char in call to write(). As std::fstream is in fact just a... | std::basic_fstream<unsigned char> doesn't work because it uses std::char_traits<unsigned char> but the standard library doesn't provides such a specialisation, see std::char_traits for full details.
If you'd like to read/write binary data, you need to use std::basic_fstream<char>, open it with std::ios_base::binary fla... |
64,884,506 | 64,884,947 | 'file too short' error on g++ when compiling .o file | Here is the error:
g++ -lpthread -pthread -std=c++11 -g -D_GNU_SOURCE src/QuoridorMain.o src/Tree.o src/utility.o src/Game.o src/storage.o -o qbot
/usr/bin/ld: error: src/QuoridorMain.o: file too short
collect2: error: ld returned 1 exit status
make: *** [Makefile:12: qbot] Error 1
And here is the Makefile I'm using... | The core problem is that your .o file got damaged some time in the past.
The secondary problem is that your clean target does not actually clean up the OFILES, as it only removes *.o, not src/*.o.
## EDIT: removed -lpthread
CXXFLAGS = -pthread -std=c++11 -g -D_GNU_SOURCE -no-pie # openmp and pthread, g for debugging
O... |
64,884,745 | 64,884,969 | Is there a linux equivalent of _aligned_realloc | Is there a linux equivalent of _aligned_realloc?
I want to use realloc so I don't have to memcpy the data every time I resize it. Am I stuck with mmap? I only used mmap once is there a recommended way of implementing memory that will be resized a few times? I'm assuming I can't mix mmap with aligned_alloc and I would h... | No, there is neither standard alternative in C++, nor in POSIX standard, nor in the GNU C library.
Here is a proof of concept using only standard functions:
void*
aligned_realloc_optimistic(
void* ptr, std::size_t new_size, std::size_t alignment)
{
void* reallocated = std::realloc(ptr, new_size);
return is_... |
64,884,841 | 64,898,786 | Remove a property by name in OpenMesh | In OpenMesh, once a named property is added to an element, it will be permanent in the sense that the property survives the scope of the property manager as explained here. My question is, how to remove such a property by its name?
So far I tried removing by the property manager and even this one fails:
auto face_props... | Apparently one can define a lower level property handle and then use get_property_handle which takes a handle as reference and updates it in place. This works:
OpenMesh::FPropHandleT< FaceProp > fprop;
mesh.get_property_handle(fprop, "face_props");
mesh.remove_property( fprop );
I wish this was better docu... |
64,885,304 | 64,885,360 | Can I create fstream before main? | #include <string.h>
#include <fstream>
using namespace std;
ofstream fout(argv[1]);
main function
int main(int argc, const char * argv[]) {
//I try to add "new word" fstream file
fout<<"new words"<<endl;
}
How can I do this? The bottom one didn't work either. It is necessery. It must be before main function
#include... | You cannot initialize your fout before you know what argv is. So, in some sense, impossible. However, you can initialize it with nothing, and open it later when you get your argv:
ofstream fout;
int main(int argc, const char * argv[])
{
fout.open(argv[1]);
fout<<"new words"<<endl;
}
This way, the global fout ... |
64,885,809 | 64,886,189 | Why does my Tic Tac Toe logic have errors sometimes? | Im new to posting questions here so let me know if ive done something wrong. So this program works fine 90% of the time as seen here.
But then the logic is off sometimes as seen here.
Ive looked through my code for a while so ive finally given in and ask for help! My logic() function seems to be accurate. Ive matched a... | In the function logic(), you are missing a return statement, meaning that if none of the conditions are satisficed, the function will just return anything that could have been in that register. I found that if you add a return 0; to the end of the function, you don't get that behavior.
|
64,885,823 | 64,885,959 | Inheriting from a template class using the inheriting class with C++20 concepts | I'm trying to write a Singleton base class similar to Ogre3Ds Ogre::Singleton using C++20's std::default_initializable.
#include <concepts>
template <std::default_initializable T>
struct Singleton {};
class Foo: public Singleton<Foo> {};
This code does not compile:
error C7602: 'Singleton': the associated constraint... | Compiling this with GCC gives a more helpful error message:
...
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/type_traits:895:52:
error: static assertion failed: template argument must be a complete
class or an unbounded array
895 | static_assert(std::__is_complete_or_unbounded(__type_identity<_Tp>{}),
... |
64,885,862 | 64,886,368 | Is there a better way to assign many members in a class which are inherited from the same class? | I have codes as follows:
class CRedisGroupChecker :public CRedisClientBase
{
SINGLETON(CRedisGroupChecker)
public:
~CRedisGroupChecker();
private:
template<typename MessageType>
bool loadConfig(MessageType message) {
if (!connectAndSelect(DB_NO_ZONE_INFO_CONFIG)) {
return false;
... | With C++17, you might use fold expression instead of the (dummy) array trick
template<typename...MessageType>
bool doLoad(MessageType&... args) { return (loadConfig(&args) && ...); }
Another possible change is to use std::tuple for all members, and then use std::apply (we can get rid of doLoad which is an one liner):
... |
64,886,632 | 64,887,037 | nested map inner value with [] | I have a nested map with all self-defined objects as key and values
typedef map <Time,WindLogType> minuteIntervalData;
typedef map <Date,minuteIntervalData> DayData;
How can I access the the data in the inner map by using the operator [] when the inner key is unknown?
Eg.
DayData[date1] //gets time1,time2,time3..... a... | The only way to access a map (whether it is an "inner" map or otherwise) with operator[] is by passing the key as the operand. Thus if the key is unknown, you cannot access the values with operator[].
There are other ways to access values of a map though and not all of them require the knowledge of the keys. One way to... |
64,886,637 | 64,886,762 | Reading file of character data with while loop | I have a file with data like:
1F B8 08 08 00 00 00 00
I am reading it into an int, casting it to a character, and storing it in an array.
int n, i = 0;
char c;
while (ifs >> std::hex >> n) {
c = static_cast<unsigned char>(n);
r[i++] = c;
}
works fine. How do I go about doing this if there is no white space in t... | You could read the numbers as strings and use std::setw to limit the number of characters read. Then use std::stoi to convert to integers:
std::string ns;
while (ifs >> std::setw(2) >> ns) {
r[i++] = static_cast<unsigned char>(std::stoi(ns, nullptr, 16));
}
Will work with both the space-delimited and non space-del... |
64,886,652 | 64,886,751 | Problem manipulating local variable from FuncA to FuncB and return is not expected | I created a function to update a local variable in funcA in funcB. However, when funcB returns, the local variable's value in funcA does not seem to correspond to what I've set in funcB.
See code snippet below:
typedef enum {
A =0,
B,
C,
D,
MAX
} status_val;
int funcA(){
status_val test = ... | funcB is expecting a char *, but you're passing in a status_val *. Enumerated types are typically implemented as type int so you you're using an incompatible pointer type.
Change funcB to accept the proper type:
void funcB(status_val *val){
|
64,886,675 | 64,887,772 | Function that reads and stores values from configuration file | I'm relatively new to C++ programming and I am just trying to create a function that opens a configuration file, reads each line and column, then stores the values into some array.
So my config file will look like this which simply just stores values:
12345 10 20
67890 30 40
...
...
What I want to do is op... | This is C code :
#include <stdio.h>
int main()
{
FILE *fp;
int i = 0;
fp = fopen("configFile.conf", "r");
if(fp == NULL) // To check for errors
{
printf("Error \n");
}
char a[20][20]; // Declared a 2D array
char b[20][20];
char c[20][20];
while (fscanf(fp, "%s\t%s\t%s", a[i], b[... |
64,886,819 | 64,940,975 | C++ directx 11 how to interleave unknown number of vertex attributes | I have read many articles saying to interleave vertex attributes by putting the data in a structure
struct Vertex
{
XMFLOAT2A vertex;
XMFLOAT3A color;
.
.
.
}
This works fine for tutorials but for real world models loaded from obj,colladae files, etc. It is impossible to know how many attributes a mesh cont... | After days of typed structs and error's i have finally found a way using memcpy
you can interleave pretty much any types of objects or primitive datatypes into an char array using this technique
DirectX::XMFLOAT2 vertices[4] =
{
DirectX::XMFLOAT2(0.5f,0.5f)
,DirectX::XMFLOAT2(-0.5f,0.5f)
,DirectX::XMFLOAT2(-0.5... |
64,887,522 | 64,887,894 | how do I make multiple integers pass multiple functions? | In this code I am trying to output the sum and difference of two inputs.
When I run this program, the sum outputs fine, but instead of the difference, the first input outputs.
How can I make this program output the difference as well as the sum?
void Modify(int *x, int *y) {
*x = *x + *y;
if (*x >= *y)
... | void Modify(int *x, int *y) {
*x = *x + *y;
if (*x >= *y)
*y = *x - *y;
if (*x < *y)
*y = *y - *x;
}
Your first line *x = *x + *y; overwrites *x value with *x + *y, by consequence the next statements are misleading
if (*x >= *y)
*y = *x - *y;
if (*x < *... |
64,887,584 | 64,888,584 | Storing configuration values inside array | I have a config file of which will consist of three columns, and n number of lines. Each columns row has a corresponding set of values. My config file will look like this:
12345 10 20
67890 30 40
...
...
So id 12345 has corresponding values 10 and 20, and 67890 has 30 and 40.
I just want to know if there i... | There are multiple ways of reading and storing the values of config files.
eg1:
struct LineData
{
int a;
int b;
int c;
};
...
LineData ldata = {0};
std::vector<LineData> configFileData;
...
fscanf(fp, "%d\t%d\t%d", &ldata.a, &ldata.b, &ldata.c);
configFileData.push_back(ldata);
...
|
64,888,080 | 64,889,507 | How to access C/C++ arrays in Python via pybind11 | I'm trying to make some C/C++ codes available in Python via pybind11, and in the C/C++ codes, a pointer to an array is returned, and I'd like to access the array in Python either as a list or a NumPy array.
I tested the following implementation:
#include <pybind11/pybind11.h>
int* get_zeros(int n) {
int* a = new i... | You need to return a type that pybind11 interprets as an array. A pointer will not work, because pybind11 does not know the size of the array.
If you return std::vector or in case of fixed dimension std::array this will be converted to a list.
The drawback is that the data is copied, so modifications in python are not ... |
64,888,406 | 64,888,538 | Can I initialize references in a class? (perhaps in the constructor?) | I am a bit rusty on my C++, and in particular with references.
I have an old code, something like
TEST(SomeTest,someFunction){
AClass anObject= GetSomeObject();
ASingletonClass &aReference= ASingletonClass::GetInstance();
//... some more code
}
For reasons of design I have to rewrite this code, and this time I have t... | Yes, you can do it in the test constructor - and it is even the recommended way:
class ASingletonClassFixture: public testing::Test{
public:
ASingletonClassFixture() : aReference{ASingletonClass::GetInstance()} {}
void SetUp() override
{
anObject=GetSomeObject();
}
protected:
AClass anObject;
... |
64,888,470 | 64,888,528 | Macro definition not replaced as expected? | I followed the online tutorial and wanted to use #undef to design my debug output function. I wrote a debugOut.h file.
The content is as follows:
#include <stdio.h>
#define NOOP //(void(0))
#undef DEBUG_PRINT
#if DEBUG_OUT
#define DEBUG_PRINT printf
#else
#define DEBUG_PRINT(...) NOOP
#endif
#undef DEBUG_OUT
The... | The preprocessor basically scans the input from top to bottom. So it first processes the #if DEBUG_OUT included from #include "Header/debug_out.h" and only then it processes #define DEBUG_OUT.
You need to make sure DEBUG_OUT is defined before the contents of Header/debug_out.h are processed. The following should work:
... |
64,889,383 | 64,890,021 | How to enable `/std:c++latest` in cmake? | I can set CMAKE_CXX_STANDARD to 17 to get /std:c++17, but I can't set it to latest, can I? I guess I can just brute-force it with
if (MSVC)
add_compiler_options(/std:c++latest)
endif()
of course, but is there an idiomatic way to get /std:c++latest, maybe even toolchain-agnostic?
EDIT Why would anybody want this? U... | Until CMake 3.20.3, if you ask for C++20, using set(CMAKE_CXX_STANDARD 20), you'll get -std:c++latest. Proof:
if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.12.25835)
set(CMAKE_CXX20_STANDARD_COMPILE_OPTION "-std:c++latest")
set(CMAKE_CXX20_EXTENSION_COMPILE_OPTION "-std:c++latest")
endif()
(from ... |
64,890,742 | 64,890,840 | Is there any way to correctly std::move const data? | My problem is that I have to choose between copying const data, and moving non-const data, and I conceptually do not see a reason why, in my situation, it wouldn't be safe to move const data to a const destination. I am also aware that moving from a const object is illogical - so perhaps there's some other way to achi... | There is no way to std::move a const T as it would mutate the given object. (Unless you make the members mutable and make a T(const T&&) constructor to do the move, which I would not recommend).
A better solution in my opinion would be to make all the mutating functions private, such that only the builder can access th... |
64,890,922 | 64,896,722 | boost::adaptors::transformed for classes without const begin/end | I'm trying to pass an object to boost::adaptors::transformed. However, this only seems to work if that object's class defines const versions of begin and end. This is not the case for me however, because iterating over an object of this class modifies internal state of the object itself. Here is a minimal example using... | I'd say in general it's a code smell that iteration modifies a collection.
Of course, something can be logically const, which is what we have the mutable keyword for. There's roughly two approaches I can see
Keep in mind that threading-aware libraries might assume that constoperations are threadsafety guarantees (so e... |
64,890,976 | 64,893,364 | Is there a way to concat class names and other characters into a string with ## and # macros | I'm developing qt application and we know that qt's SLOT and SIGNAL can convert input as char * which is needed by connect function. But my signals are coded as macros:
//NOTE following line is NOT RIGHT way, but just my idea
#define TEST_SIGNAL(name) #name##Changed##(##)
If I call this macro somewhere as:
// given de... | If you really cannot escape the Qt4 style signals/slots:
#define TEST_SIGNAL(name) SIGNAL(name##Changed())
This makes TEST_SIGNAL(testInt) identical to SIGNAL(testIntChanged()).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.