question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
72,491,412 | 72,495,481 | Getting Qt Test output in GitHub actions | Currently the only thing I can see is the executable exit code, so I can see if any tests failed or not, but I don't get any other output.
Is there a way to show something similar to what you see in Qt Creator when running tests?
I am using CMake and the Qt Test framework.
| You can use -junitxml option to output test results to xml file(s) and use one of actions to watch detailed reports:
action-junit-report
publish-unit-test-results
junit-report-action
test-reporter
report-junit-annotations-as-github-actions-annotations
|
72,491,968 | 72,492,095 | CreateProcessWithLogonW can't read 0xCCCCCCCC Error | I am currently trying to inject a username and password into lsass.exe with c++, i am pretty new to c++ so this might be a stupid question but it always throws me the error '0xC0000005: Access violation reading at location 0xCCCCCCCC'. Here is my code:
#include <iostream>
#include <windows.h>
#include <processthreadsap... | You need more initialization of the STARTUPINFO structure. In particular, the size of the structure. The operating system uses the size of the structure to determine what members are present. It is like a structure version.
STARTUPINFO si = {0};
si.cb = sizeof(si);
|
72,492,238 | 72,492,351 | Invalid application of incomplete type 'Test::Impl' | Please have a look at directory structure first [ attached at the bottom of the question end].
Following are my Cmake files :
Main cmake
cmake_minimum_required(VERSION 3.9)
set (CMAKE_CXX_STANDARD 14)
add_executable (test main.cc)
target_include_directories(test PUBLIC test_include_interface)
target_link_l... | The Test does not contain a user defined destructor, so the compiler generates a inlined version of this destructor. Since this destructor involves logic to delete the Test::Impl object when the destructor of std::unique_ptr<Test::Impl> is invoked, you get the error your compiler complains about.
You can fix this by de... |
72,492,416 | 72,494,236 | Missing libgcc_s_seh-1.dll starting the .exe on Windows | Intro
I have a CMake-based C++ project. Until now I build and ran the project via CLion. Everything worked fine until I tried to run the .exe-file directly (not via CLion).
Problem
When I navigate to the cmake build directory in order to start my program via the executable file, it fails with the following message in t... | I found the cause of my problem: I had two MingGW installations on my machine. Once the installation that comes with CLion and a separate one. The latter did not have the required dll. However, CLion used its own installation, which in turn owns the DLL. So the solution was to remove the separate installation and inclu... |
72,492,589 | 72,493,650 | How to overlay 2 Images in QT | I have 2 images that I load in QImage and my question is :
How can I overlay these 2 images in the simplest way, to then save it in a QPixmap ?
Here are the following images :
And the awaited result :
(The final image will be used in a QTableView to show the user if it has more of the same potion)
| I was able to find the answer on my own after some more research.
Here is my code that I came up with (if you can do it better I would like to see it because I would like to implement any better approach if there is any):
QPixmap base = QPixmap::fromImage(QImage("Your 1st img"));
QPixmap overlay = QPixmap::from... |
72,493,507 | 72,493,647 | Line 1034: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'int' | class Solution {
private:
void make_zero(vector<vector<int> >& matrix,vector<pair<int,int>>v,int n,int m)
{
for(auto i:v)
{
for(int j=0;j<n;j++)
{
matrix[i.first][j]=0;
}
for(int j=0;j<m;j++)
{
matrix... | n and m are swapped around in make_zero(), you confused the row and column dimensions.
|
72,493,660 | 72,493,692 | Why does 0.125, formatted with 2 digits of decimal precision, show "0.12" not "0.13"? | Consider:
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::fixed << std::setprecision(2);
std::cout << 0.125 << '\n'; // Prints "0.12"
std::cout << 0.126 << '\n'; // Prints "0.13" as expected
}
Demo
I know that floating point math isn't perfectly precise, but isn't 0.125 one of the v... | Yes, 0.125 is one of the rare floating point values that should have an exact binary representation.
Your rounding mode is probably set to round-half-to-even.
|
72,493,712 | 72,493,772 | Why does the "size_of_array" template fucntion does not work with int a[n] (size defined at runtime) while it works fine with int a[4]? | template <typename T, int n >
int tell_me_size(T (&) [n]){
return n;
}
this code works fine with
int a[4];
cout<< tell_me_size(a)<<endl;
while does not work with
int n;
cin>>n;
int a[n];
cout<< tell_me_size(a)<<endl;
The later gives the error "no matching function for call to ‘tell_me_size(int [n])"
| According to the C++ 20 Standard (13.4.3 Template non-type arguments)
2 A template-argument for a non-type template-parameter shall be a
converted constant expression (7.7) of the type of the
template-parameter.
Pay attention to that variable length arrays like this
int n;
cin>>n;
int a[n];
are not a standard C++ fe... |
72,493,969 | 72,494,031 | Unexpected behavior of c++ program on executing two equivalent statements | I was trying to solve this problem,
while doing so,
it looks like
for (int i=row1; i<=row2; i++) {
if (col1 != 0) sum -= mat[i][col1-1];
sum += mat[i][col2];
}
and
for (int i=row1; i<=row2; i++) {
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
}
are equivalent, but executing the later results i... | This statement
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
is equivalent ti
sum += (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0;
So for example if this expression (mat[i][col2] - (col1 != 0) ) is not equal to 0 then you will have in fact
sum += mat[i][col1-1];
even when col1 is equal to 0.
It see... |
72,494,117 | 72,497,888 | Compile time check that lcm(a,b) doesn't overflow | I would like to have a compile-time check that taking the least common multiple of two numbers doesn't overflow. Difficulty: regarding std::lcm,
The behavior is undefined if |m|, |n|, or the least common multiple of
|m| and |n| is not representable as a value of type
std::common_type_t<M, N>.
(Source: https://en.cpp... | Assuming that both a and b are positive, there is the relationship
a * b == lcm(a,b) * gcd(a,b)
that you can use to your advantage. Computing gcd(a,b) does not overflow. Then you can check whether
a / gcd(a,b) <= std::numeric_limits<CT>::max() / b
where CT is std::common_type_t<decltype(a),decltype(b)>.
|
72,494,498 | 72,494,834 | How do i print the path to a node in C++ if the nodes only contain pointers to their parents? | The task was to make a kind of file system in c++, where the user can create, remove, cd into and out of folders and list subfolders. After every operation the program should print out the path to either the current folder or the created/removed folder. I stumbled on the path printing:
struct dir
{
std::string ... | As you push new elements into sys it will eventually fill up and have to reallocate its elements, at that point all the pointers you've saved into parent become invalid and your program has undefined behaviour.
An easy solution would be to call reserve before creating any elements, you'll need to ensure you never excee... |
72,494,618 | 72,494,688 | Undefined behavior allowed in constexpr -- compiler bug? | My understanding is that:
Signed integer overflow in C++ is undefined behavior
Constant expressions are not allowed to contain undefined behavior.
It seems to follow that something like the following should not compile, and indeed on my compiler it doesn't.
template<int n> struct S { };
template<int a, int b>
S<a * ... | According to [expr.const]/5, "an operation that would have undefined behavior as specified in [intro] through [cpp]" is not permitted during constant evaluation, but:
If E satisfies the constraints of a core constant expression, but evaluation of E would evaluate an operation that has undefined behavior as specified i... |
72,494,684 | 72,495,061 | restore broken cpp libs linux | So, I was trying to compile dlib but it spitted out many errors. Appearently, my cpp files are broken.
Even as simple as compiling a cout << "Hello World"; with g++ resolves in issues.
Here's the log:
https://pastebin.com/bTkdaycn
Is there any way to "restore" broken cpp files? I haven't really messed around with the l... | So, I got it.
For everyone wondering, I went to my windows pc, which had wsl on it.
I scp'd the entire /usr/include/c++/11 directory to myself and replaced. Now everything works. Like a dirty wooden-hammer solution, but it's a solution
|
72,494,822 | 72,494,879 | Max Heap Insert Function Implementation C++ | I'm trying to insert key values into heap. I'm using TestUnit.cpp for errors. I got these errors:
Assert failed.
Expected:<[(10,100),(7,70),(6,60),(5,50),(2,20),(1,10),(3,30),(4,40)]>
Actual:<[(7,70),(5,50),(6,60),(4,40),(2,20),(1,10),(3,30),(10,100)]>
Assert failed.
Expected:<[(10,100),(4,40),(5,50),(1,10),(2,20),(3,3... | Your loop starts at the wrong value. It should be:
for (int i = (asize - 1) / 2; i >= 0; i--)
Not your question, but:
calling heapify is not the fastest way to bubble a value up, since that function needs to check also the sibling value, which is unnecessary.
i-- will make this loop O(n), which is not the complexity ... |
72,494,915 | 72,495,027 | How do you get the component of a vector in the direction of a ray | I have an object moving in the direction of vector A.
There's another vector B which points in an arbitrary direction (but can be considered an infinite line)
I want to get vector C, which is a vector in the direction of B, but with the magnitude of the A's component in the direction of B.
To illustrate, if vector A wa... | Let C = normalize(B). (divide B by its length)
Then dot(A, C) gives you the length of the desired vector, and dot(A, C) * C is the vector itself.
|
72,495,247 | 72,495,489 | Implementing Game Outcomes with While Loop: Turn-based Dueling Game | Background
I'm making a turn-based dueling game against a computer. Right now, I'm trying to get the barebones of the game to work without player input. After each turn (one action by the player or computer) one of four possibilities can happen:
Player lives and computer lives
Player lives and computer dies
Player die... | you only test the status at the top of the loop,
do this if you want to exit immediately
// game should continue while the player is still alive
while(gameStatus(gameCondition, player, computer) == 1)
{
playerTurn(player, computer);
// attempt at checking the game status after each turn
... |
72,495,369 | 72,495,428 | Build a generic `map` like function in cpp | Consider
template <typename S, typename T, typename F>
vector<T> map(const vector<S> &ss, F f){
vector<T> ts;
ts.reserve(ss.size());
std::transform(ss.begin(), ss.end(), std::back_inserter(ts), f);
return ts;
}
int main(){
vector<int> is = {...};
vector<double> ts = map(is, [](int i){return 1.2... | Something like this:
template <typename S, typename F>
auto map(const std::vector<S> &ss, F f) -> std::vector<std::decay_t<decltype(f(ss[0]))>>
{
std::vector<std::decay_t<decltype(f(ss[0]))>> ts;
ts.reserve(ss.size());
std::transform(ss.begin(), ss.end(), std::back_inserter(ts), std::move(f));
return ts... |
72,495,509 | 72,495,555 | Filling the array horizontally alternately C++ | I'm trying to fill the array horizontally alternately such as:
My default ArrayFill function is :
void fillArray(std::array<std::array<int, maxColumns>, maxRows> & array, size_t rows, size_t columns)
{
if (rows == 0 || rows > maxRows || columns == 0 || columns > maxColumns)
throw std::invalid_argument("Inv... | there are two properties which you should obey:
start filling not from top (row=0) but bottom (row=rows-1)
each row (from bottom to top) changes the order of columns
so, finally it can look like this:
int value = 1;
int colOrder = 1; // 1 means from left to right, 0 from right to left
for (size_t row = 0; row < rows;... |
72,496,216 | 72,496,296 | Builder patterns with vectors evaluated at compile time (with `consteval`) | I am attempting to create a class that follows the builder pattern and also runs completely at compile time (with the use of the new consteval keyword in C++20), but whatever I try doesn't work. For example, this won't work:
#include <vector>
class MyClass
{
private:
std::vector<int> data;
public:
consteval M... | Your code does not compile because current C++ only permits "transient" allocation in constant expressions. That means that during constant expression evaluation, it is permitted to dynamically allocate memory (since C++20) but only under the condition that any such allocations are deallocated by the time the constant ... |
72,496,693 | 72,496,729 | Why is my code with chars messing up a counting variable? | This is Arduino code, but I have a feeling my error is with C++ in general and not specific to Arduino. I'm new to pointers and strings, so I probably am doing something wrong in that regard.
This is from a much larger program, but I've whittled it down to as little code as I can where I can still reproduce the bug.
It... | static char newText[][10] = {};
This creates a zero sized array (to be more precise a matrix of 0 rows and 10 columns). This would be illegal in C++ but gcc has an extension to allow it. Nevertheless even with gcc's extension, it's UB when you access newText[0][0] which is outside the size of the array. When you have ... |
72,496,829 | 72,496,834 | Changing the value of a const variable using pointer in C++ | Run the code below:
#include <iostream>
int main()
{
const int NUM = 1;
int *p = (int *)&NUM;
*p = 2;
std::cout << *p << "\n";
std::cout << NUM << "\n";
return 0;
}
The output of the program above is:
2
1
The expected output was:
2
2
Can anyone please explain why the value of NUM is 1?
The same can... | A const is a read-only value. You are trying to do something that is not allowed so you should have Undefined behaviours like this one.
|
72,497,582 | 72,497,938 | Couldn't deduce template paramter even if it is known at compile time | I have a variadic template class SomeClass that looks like this (basically):
template<std::size_t SIZE_>
class SomeClass {
public:
static constexpr std::size_t SIZE = SIZE_;
};
It has a constexpr member that simply contains the std::size_t template parameter used to instantiate it. I want a constexpr function that... | There's a reason people call structs metafunctions in c++ template metaprogramming.
In our case the major advantage of doing metaprogramming in a struct is that resolving function overloading by template arguments is different and more limited than that of class specialisation.
So I suggest:
template <class ...> // onl... |
72,497,636 | 72,497,811 | Getting class' method address | I'm asking you to help me understand this concept. Maybe I don't understand something, I don't know.. So I have this sample code:
#include <iostream>
class X{
int a;
public:
void do_lengthy_work();
};
void X::do_lengthy_work(){
std::cout << a << std::endl;
}
int main(){
X my_x;
pri... | You can basically think of X as being implemented something like this:
struct X{
int a;
int b;
};
void X__do_lengthy_work(X* this);
Methods are pretty much the same as a normal function just with the addition of a hidden parameter of a pointer to the instance of the class.
Each instance of a class uses the sam... |
72,497,910 | 72,498,394 | why was invalid substitution of class template deriving template arguments in alias declaration not resulting in error | I have tested these several templates to show the validity of the template instantiation:
template <typename T>
using LRef = T&;
template <typename T>
using Ptr = T*;
template <typename>
requires false
class A {};
// ...
using T0 = LRef<int>; // expected ok
// using T1 = LRef<void>; // expected error, forming vo... |
Is this valid in standard C++ or just not implemented properly?
The second snippet without the use of T5{}; and T7{}; is well-formed.
This is because typedefs, using and do not require a completely defined type. And from implicit instantiation's documentation:
When code refers to a template in context that requires ... |
72,497,912 | 72,497,949 | Why getting runtime-error even after declaring size of vector? | I am solving leetcode problem : https://leetcode.com/problems/number-of-islands/
It gives me this error:
Char 34: runtime error: addition of unsigned offset to 0x6080000000a0 overflowed to 0x60800000008c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../... | In this line:
if(newX<n && newY<m && visited[newX*m+newY]==-1 && grid[newX][newY]=='1')
You never check if newX or newY are less than 0. If so, accessing grid[newX][newY] could give a runtime error.
Just add two conditions, as shown below:
if(newX<n && newY<m && newX >= 0 && newY >= 0 && visited[newX*m+newY]==-1 && gr... |
72,498,003 | 72,498,880 | C++ Program with matrix class ending abruptly | I am writing a matrix class where I need to perform some matrix calculations in the main program. I am not sure why the program is ending abruptly when user chooses a matrix of size more than 2x2 matrix. The std::cin works fine until two rows but program ends after the loop reaches third row. Only part of the code is s... | Since the 2D array, vtr is created when declaring the Matrix object, you can move the vtr creation after reading the console input like below.
Matrix(int m = 2, int n = 2)
{
/*rows = m;
cols = n;
vtr = new int*[m];
for (int i = 0; i < m; i++)
{
vtr[i] = new int [n];
}
for (int i = 0... |
72,498,346 | 72,498,391 | Question about linking compute shader program in OpenGL | I'm trying to create a single compute a shader program computeProgram and attach two source codes on it. Here are my codes:
unsigned int computeProgram = glCreateProgram();
glAttachShader(computeProgram, MyFirstComputeShaderSourceCode);
glAttachShader(computeProgram, MySecondComputeShaderSourceCode);
gl... |
Why is this difference happen?
When you link a vertex shader and a fragment shader to the same shader program, then those two (as their names imply) are in different shader stages. Every shader stage expects exactly one definition of the main() function.
When you attach two shaders that are in the same shader stage, ... |
72,498,843 | 72,498,942 | C++ doesn't display array values | My code doesn't display array values that I input, instead it only prints zero. It supposed to print the values if I choose case 2 after completing the case 1. My code doesn't display array values that I input, instead it only prints zero. It supposed to print the values if I choose case 2 after completing the case 1.
... | There is a mismatch between the variable used in the for loop vs variable used to print the values.
case(2):
cout<<"Precinct\tCandidate: "<<candidate[0]<<"\tCandidate: "<<candidate[1]<<"\tCandidate: "<<candidate[2]<<"\tCandidate: "<<candidate[3]<<endl;
for(int i=0; i<5;i++)
cout << i+1 << "\t\t" <<... |
72,499,077 | 72,499,516 | 3 dimensional vector in c++ | i want to store a vector of objects for a node and subset of set.
so I want to implement a 3 d vector where the first dimension has size #nodes = n and the second dimension has size 2^|set| = m. the last dimension shouldn't have fixed size, because I want to append new objects in my program.
vector< vector < vector<Obj... | The method of initialisation is
vector< vector < vector<Object>>> Vector3d(n,vector<vector<Object>(m))
This will work, as it will initialize the first dimension's size as n, which would contain n no of vector<vector<Object>(m) which is the default value. Now the size of the second dimension is defined as m, which has ... |
72,499,080 | 72,499,106 | Accessing Enum defined within a class C++ | I have the following code:
// Piece.h
class Piece
{
public:
enum class Color {BLACK, WHITE};
Piece();
Piece(int x, int y, Piece::Color color);
private:
int m_x;
int m_y;
Piece::Color m_color;
static const int UNINITIALIZED = -1;
};
How do I access the enum from the method func... | You access enum (class) members like you would access any static member.
Piece::Color::BLACK in this case.
In the constructor, you could omit the "Piece" part and just write the following:
Piece::Piece() :
m_x(UNINITIALIZED),
m_y(UNINITIALIZED),
m_color(Color::BLACK)
{}
Regarding your hint about this being bad... |
72,499,201 | 72,499,562 | define / use a Macro inside a fcuntion - good style/practice? | I folks, I have a question for the C/C++ Syntax / Coding-Style Gurus out there:
The situation: I am working on an STM32 Microcontroller and in some functions I have to do a lot of bit shifting, logical operations (and, or, xor) on bits, set/clear bits and writing / reading this code is really painfull.
An example: lets... | Alternate solution:
#include <stdbool.h>
void DeviceOn(void)
{
uint8_t DIOPort = ReadDIOPort();
bool PowerIsOK = DIOPort & 1 << SENSOR1;
bool SafetyIsOK = ! (DIOPort & 1 << SENSOR2);
bool LightIsOn = DIOPort & 1 << SENSOR3;
bool CoffeeMugIsFull = DIOPort & 1 << SENSOR4;
... |
72,499,298 | 72,499,380 | C++ wrong calculation and no percentage showing | The calculation is only right in a and c, it is very wrong on b and c is off by 1. And the percentage only shows zero. Although the formulas is the same I can't figure out why the two is wrong, And why the percentage only shows zero and doesn't follow my formula.
Here the output
enter image description here
And here is... | Use double instead of int to represent the variables that are used to store the percentages.
Initialize the variables that are used to store the totals.
You can find more about double conversion here. How to convert integer to double implicitly?
And you are printing the same percentage value i.e. ap for all the candida... |
72,499,538 | 72,502,221 | Understanding clang-tidy "DeadStores" and "NewDeleteLeaks" warnings | I am relatively new to c++ programming, especially when dealing with OOP and pointers.
I am trying to implement a binary search tree, and here is the code I have
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(NULL), right(NULL){};
TreeNode(int v) : val(v), left(NULL), r... | Q1: How do I insert into a binary tree?
The main problem with the fragment:
void insert(TreeNode* root, TreeNode* v) {
// inserts v into root, assuming values distinct
if (root == NULL) {
root = v; // L52
return;
}
is, although you have set a new value for root, root is a parameter to the insert function... |
72,499,630 | 72,499,807 | Chaining return-by-reference calls to access underlying data | I worked previously only with pointers and i don't know if references behave the same way in return-statements.
Can I chain multiple return-by-reference methods to access data without fearing for a "dangling" reference which contains garbage? Or would the reference go out of scope before passing it to the function-call... | Yes, this is a valid way of chaining references.
You can chain references within functions without worrying about dangling references (which you should worry with pointers). As long as m_Container exists, the reference is available, after that it points to NULL.
|
72,499,700 | 72,499,749 | Could not find a package configuration file provided by "boost_json" | While following this link to setup boost for json parsing, I am unable to find the boost json component.
Link:
Using boost::json static library with cmake
Here's my CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
set (CMAKE_CXX_STANDARD 14)
set( Boost_USE_STATIC_LIBS ON )
#set( Boost_USE_MULTITHREADED ON )
#set( ... | Boost JSON was introduced in version 1.75.0. It's not available in version 1.71.0. You need to install a more recent version of boost on your system.
From the boost version history page (emphasis mine):
Version 1.75.0
December 11th, 2020 19:50 GMT
New Libraries: JSON, LEAF, PFR. Updated Libraries: Asio, Atomic, Beast,... |
72,501,170 | 72,501,327 | C and C++ see which compiler used for which code | Im currently working on a big project that uses C and c++ code in one project using the extern "c" keyword in my declartions.
However I am unsure whether the compiler is actually doing anything with this as my output is the same when using the C keyword.
Is there a way to print something to the console to show what com... | to answer your specific question about knowing if its a c or c++ compiler processing your code you can look for
__cplusplus
standard define
It's common to see:
#ifdef __cplusplus
extern "C"{
.....
|
72,502,085 | 72,502,937 | undefined reference issue with latest gcc | I have link-time error when trying to compile following code with gcc 12.1.0.
With clang, msvc and older gcc it compiles as expected.
template<typename T>
void def()
{}
template<void (*foobar)() = def<int>>
void bar()
{
foobar();
}
template<typename T>
void foo()
{
bar();
}
int main()
{
foo<int>();
}
Er... | Reported this bug to GCC Bugzilla: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105848
|
72,502,150 | 72,503,227 | Wrap an interface around a class from library | There is a class defined in a library:
class fromLib{};
used as argument to invoke a method implemented within the library :
method_from_lib(const fromLib& from_lib){};
I want wrap this method within an interface
class Methods{
virtual invoke_method(const& genericArg)
}
where class genericArg is generic... | I think you're looking for an adapter.
https://refactoring.guru/design-patterns/adapter/cpp/example
Usage examples: The Adapter pattern is pretty common in C++ code. It’s
very often used in systems based on some legacy code. In such cases,
Adapters make legacy code work with modern classes.
Identification: Adapter is ... |
72,502,526 | 72,502,632 | segfault with self-declared hash function | ChunkCorner.h
#pragma once
#include <filesystem>
#include <iostream>
class ChunkCorner
{
public:
int x;
int y;
std::filesystem::path to_filename();
};
size_t hf(const ChunkCorner &chunk_corner);
bool eq(const ChunkCorner &c1, const ChunkCorner &c2);
ChunkCorner.cpp:
fwiw: The hf and eq function impleme... | You need to pass the hash and equals functions to your constructor. You've declared their type in the type arguments, which is going to be a pointer to function, but you haven't passed them in. So they're likely being zero initalized, so nullptr. Using them correctly should be done like this:
unordered_set<ChunkCorn... |
72,502,840 | 72,503,023 | Is two-way BFS not supposed to work in this case? | I am solving a problem on LeetCode:
In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the ending string end, return True if and only if there ex... | Debugging: if I comment the "swap first and last" line, the solution works on this test.
The culprit: when considering the actual last instead of first, the program should do inverse operations: not XL to LX and RX to XR, but LX to XL and XR to RX.
Perhaps keep a boolean value (switching whenever you swap first and las... |
72,503,214 | 72,503,666 | Using constexpr vectors in template parameters (C++20) | Recently, I've been playing around with C++20's new constexpr std::vectors (I'm using GCC v12), and have run into a slight problem (this is actually an extension of my last question, but I thought it would just be better to make a new one). I've been trying to use constexpr std::vectors as members to a class, but this ... | You still (in C++20 and I don't think there is any change for C++23) can't use a std::vector as a non-type template argument or have any std::vector variable marked constexpr or have any constant expression resulting in a std::vector as value at all.
The only use case that is allowed now in C++20 that wasn't allowed be... |
72,503,312 | 72,503,395 | How to implement a destructor | I am having trouble to understand vector and heap. So far, I want to create a vector of int. The element of this vector should be stored in the heap. I have implemented a class, but I don't think that I have implement the destructor correctly. There is also a problem with the move constructor. If I want to move vector ... | Please find below a working example.
#include <vector>
#include <iostream> // Debug only
class Vector
{
private:
std::vector<int> _myVec;
int _val;
size_t _size;
public:
// "Regular" Construtors
Vector() : _val(0), _size(0) {}
Vector(size_t size) : _size(size), ... |
72,504,041 | 72,504,110 | Reinterpret cast conversions | To my understanding of the standard regarding [expr.reinterpret.cast]—but please correct me if I'm wrong—converting a pointer to member function to some other pointer to member function and back to its original is actually legal, well-defined behavior. As laid out in section 7.6.1.10:
A prvalue of type “pointer to mem... | You simply misread the second quote. In the highlighted sentence everything in the subordinate clause before the main clause "the result of such a pointer conversion is unspecified" is stating an exception to that main statement.
The reinterpret_cast round-trip conversion guarantee works for function pointers exactly l... |
72,504,525 | 72,504,643 | What's the difference of "co_await other_co" and "other_co.resume"? | The following code doesn't work as my expectation.
#include <iostream>
#include <coroutine>
#include <vector>
struct symmetic_awaitable
{
std::coroutine_handle<> _next_h;
symmetic_awaitable(std::coroutine_handle<> h) : _next_h(h) {}
constexpr bool await_ready() const noexcept { return false; }
std::... | If a function is a coroutine, it can only become suspended in one of the following ways:
When the coroutine starts, if the promise initially suspends.
When a co_await expression (or equivalent, like co_yield) is directly invoked.
When the coroutine co_returns, if the promise finally suspends.
Nothing else can cause a... |
72,505,009 | 72,505,254 | Why can't I initialize this std::vector with an l-value? | I've come across an interesting issue, and I can't understand what's happening:
/* I WANT 6 ELEMENTS */
int lvalue = 6;
std::vector<int*> myvector { 6 }; /* WORKS FINE */
std::vector<int*> myvector{ lvalue }; /* DOESN'T WORK */
/* Element '1': conversion from 'int' to 'const unsigned __int64 requires a narrowing conve... | TL;DR
The problem is not specific/limited to std::vector but instead is a consequence of the rule quoted below from the standard.
Let's see on case by case basis what is happening and why do we get the mentioned narrowing conversion error/warning when using lvalue.
Case 1
Here we consider:
int lvalue = 6; // lvalue is... |
72,505,267 | 72,505,375 | Rotate a vector in right direction using std::rotate() | How to rotate a vector in right direction by K steps using std::rotate? Is there a better or faster method to rotate a vector(array) than std::rotate?
|
How to rotate a vector in right direction by K steps using std::rotate?
The second parameter to std::rotate is an iterator to the new first element after the rotation. So, to do a right rotate by 1 step, that would mean the end() - 1 should be the new first etc.
Generalized:
template<class... T>
void rotate_right(std... |
72,505,524 | 72,676,373 | SysTick_Handler works as a normal function but not on SysTick interrupt (on QEMU) | I am trying to implement a simple RTOS with round robin scheduling. Since I do not have a physical board yet, I am running the ELF file on QEMU (qemu-system-gnuarmlinux). For development I am using Eclipse CDT. I use the following command to run the code on QEMU:
/opt/xpack-qemu-arm-7.0.0-1/bin/qemu-system-gnuarmeclips... | The problem was setting the T-bit in the Execution PSR register for individual task stacks. The course content that I was following skipped over the fact that the PSR is composed of 4 bytes, and the T-bit in the most significant byte.
Initially, I was setting it as: TCB_STACK[threadNumber][STACK_SIZE-1] = (1U << 6);. ... |
72,505,589 | 72,505,610 | How to pass a variable's pointer? | This is my code:
GLint framebuffer_handle = 0;
void glGetIntegerv(GLenum pname, GLint * data){ ... }
glGetIntegerv(GL_FRAMEBUFFER_BINDING, *framebuffer_handle);
The last line reports an error:
indirection requires pointer operand ('GLint' (aka 'int') invalid)
What's the problem with this code?
| framebuffer_handle is not a pointer, so you can't dereferenced it with the * operator. That is what the compiler is complaining about.
glGetIntegerv() wants a pointer to a GLint. A pointer holds a memory address. You need to use the & operator to get the address of (ie, a pointer to) the framebuffer_handle variable, e... |
72,505,726 | 72,505,786 | Having trouble accessing a list value inside a map | C++ | I've made a map that has string keys with either string values or list values. It gives me no syntax errors and has worked fine for me so far until I've tried accessing the list value. I've tried setting it as a variable, using auto, and no go. Don't know what else to try, any help is appreciated.
using map = std::map... | The problem is that m["TAGS"] is of type std::variant and so doesn't have a begin method. Since you want to get the list out of your variant you can use the std::get function to do that
auto it = std::get<std::list<std::string>>(m["TAGS"]).begin();
|
72,505,769 | 72,505,863 | How to put 3 elements in priority_queue in c++ |
I been studying priority_queue in c++ from Leetcode and I found this code from solution
I understand that this is minimum heap but don't understand how is this storing 3 elements to minHeap.
is vector<int> gets matrix[r][0], vector<vector<int>> gets r and greater<> gets 0????
Why do we need to put priority_queue<int,... | First, let's look at the meaning of the template arguments in the class of minHeap.
From cppreference:
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
class priority_queue;
Template parameters
T - The type of the stored elements. ...
Contain... |
72,506,092 | 72,506,169 | How are unknown attributes supposed to be treated before C++17? | cppreference says that
All attributes unknown to an implementation are ignored without causing an error.
... but that this edict was introduced in C++17. What about earlier versions of C++? Are unknown attributes supposed to be errors? Is it implementation-defined what to do with them?
| It was implementation-defined since its introduction in C++11.
See [dcl.attr.grammar]/5:
For an attribute-token not specified in this International Standard, the behavior is implementation-defined.
|
72,506,335 | 72,506,497 | Concatenate 2 string using operator+= in class C++ | I've seen some similar questions before asking, but I'm still stuck at the part of concatenating two strings using operator+=.
Currently, I can get separate strings correctly by constructor method. But when I compile code, the line str[length+i] = s[i]; in the method String& String::operator+= (const String& s) shows a... | In many of your constructors, you do not set length which leaves it with an indeterminate value - and reading such values makes the program have undefined behavior. So, first fix that:
#include <algorithm> // std::copy_n
// Constructor with no arguments
String::String() : data{new char[1]{'\0'}}, length{0} {}
// Cons... |
72,506,759 | 72,508,650 | How to convert std::chrono::duration to boost duration | I have two time_point objects in my code and I need to use Boost condition variable for the difference:
template<class Clock, class Dur = typename Clock::duration>
class Time {
std::chrono::time_point<Clock, Dur> a;
std::chrono::time_point<Clock, Dur> b;
}
....
boost::condition_variable var;
....
var.wait_for(l... | I'd do what I always do: avoid duration_cast by using arithmetic with UDL values.
You have to select a resolution for this, let's choose microseconds:
#include <boost/thread.hpp>
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;
template <class Clock, class Dur = typename Clock::duration> //
... |
72,506,834 | 72,506,928 | What is the different of ::std::cout and std::cout | There is a simple code with the different aspects of usage of :: operation.
namespace test{
int add(int x, int y){
return x + y;
}
}
int main(){
int x=3, y=5;
int r = ::test::add(x,y);
r = test::add(x,y);
}
or in another example
::std::cout << "Hello";
std::cout << "Hello";
The functio... | The difference is that one is a fully qualified name, and the other is not a fully qualified name. Whether the fully qualified name is used or not doesn't make a practical difference in these examples. It could make a difference in another context. See the further down for an example.
To understand the concept it may h... |
72,506,840 | 72,506,958 | C++ problem adding elements to a std::list | I'm working on a project in which I have to assign missions to timetables. Timetables are divided in three classes : Semaine, Journee and Mission.Each class contains a list of elements of the lower level. Here's the definition of each class :
class Mission{}
class Journee{
list<Mission> missions;
bool addMissi... | I think the problem is in
for(Journee j : jours){
This gives you a copy of Journee.
Using a reference instead, i.e.
for(Journee& j : jours){
should solve the problem
Similarly for
for(Mission m : missions) s.addMission(m);
That should rather be:
for(Mission& m : missions) s.addMission(m);
or even better:
fo... |
72,507,367 | 72,507,434 | Why can't I create Tree using the code below? | It's a function to bulid a binary tree,but it can't work,can someone tell me what's wrong with my code
typedef struct treeNode* BT;
struct treeNode {
int val;
treeNode* left;
treeNode* right;
};
BT createTree(BT root) {
int data = 0;
cin >> data;
if (data == -1) {
return nullptr;
}
... | You're ignoring the result of createTree(root->left); and createTree(root->right);
What's more, in your implementation the argument root is meaningless. You're not using it at all. Code below should work.
BT createTree() {
int data = 0;
BT root;
cin >> data;
if (data == -1) {
return nullptr;
... |
72,508,057 | 72,508,866 | Can .gch files generated from CMake's target_precompile_headers be shared across targets? | My initial attempt at incorporating precompiled header files in my project resulted in very large (~200MB) and nearly identical .gch files for each target directory. I tried the following approach, which I was hoping would produce a single .gch file generated and shared among targets. However, CMake still generated s... | You need to use target_precompile_headers per each target you want PCHs for. With one producer you use like you did and then the consumers should look like this:
target_precompile_headers(target1 REUSE_FROM pch)
And you do not need to link against your pch "library".
Docs actually have the section for it.
|
72,508,842 | 72,608,223 | Can't build Qt-Widgets Application using CMake | I am trying to setup a CMake Project building a Qt-Widgets application but can't compile it properly. My project structure is as follows:
include/
mainwindow.hpp
resources/
mainwindow.ui
src/
main.cpp
mainwindow.cpp
CMakeLists.txt
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
find_package(Qt5 COMPONENT... | The solution to this is, adding include/mainwindow.hpp to the sources.
add_executable(App src/mainwindow.cpp src/main.cpp include/mainwindow.hpp resources/mainwindow.ui)
This seems to be required for the generated ui_mainwindow.h to see the vtable entries of the MainWindow class.
|
72,508,862 | 72,574,124 | QT OCI driver isn't working with MSVC compiler | QT version 6.2.x
I have compiled the oci driver for MinGW and MSVC. It works with MinGW compiler but not with MSVC. When I use MSVC compiler in my project I get the error "QOCI driver not loaded".
The driver is compiled according to the instructions:
qt-cmake.bat -G Ninja F:\Qt\6.2.0\Src\qtbase\src\plugins\sqldrivers -... | The problem has been fixed by using the VS Command Prompt.
|
72,509,401 | 72,509,457 | Template specialization with only one parameter | If you have a class template such as this:
template <typename T, unsigned CAPACITY>
class Collection
{
T m_array[CAPACITY]{};
T m_dummy{};
unsigned m_size{};
}
public:
void display(std::ostream& ostr = std::cout) const
{
ostr << "-----------------... | It's called a partial template specialization:
template <class T, unsigned Capacity>
struct Collection {
};
template <unsigned Capacity>
struct Collection<Pair, Capacity> {
// Specialize
};
One thing to note is that you cannot partially specialize a single function. You have to specialize the whole class template,... |
72,509,526 | 72,509,912 | Deducing variadic template arguments with default arguments | I am trying to create a basic logger. Here is a small example.
template<typename ...str>
struct log {
log(
str &&...args,
const char *file = __builtin_FILE(),
const char *func = __builtin_FUNCTION(),
const size_t line = __builtin_LINE()
) {
std::cout << "[" << file << ... | You cannot use CTAD on some arguments, but not on the others. You could make a similar syntax work though using tag dispatch. You need to move the specification of the log level to the argument list to accomplish this.
Note that in the following example I'm using std::source_location (C++20) to be compiler independent:... |
72,509,832 | 72,509,979 | Changing inherited class' member variables | Background
I've been reading about inheritance and messing around with some code, and I'm trying to better understand how to implement virtual functions, and more broadly, how to change member variables in derived classes. Here's what I've got so far:
Code
#include <iostream>
class Base
{
private:
int m_value {};
... | Please find below your sample working the way you want. I'll explain below the code.
#include <iostream>
class Base
{
protected: // HERE change n°1
int m_value;
public:
Base(int value = 5) : m_value{ value }
{
}
int getValue()
{
return m_value;
... |
72,510,149 | 72,510,381 | Appending line from a file into char array | char wordList[200];
ifstream wordListFile ("wordlist.txt");
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
}
This code currently returns the line at the end of the wordListFile (wordlist.txt),
is there any way to append the lines to wordList?
because when I use the append() ... | In the loop
for(std::string line; getline(wordListFile, line); ) {
wordListFile >> wordList;
you are reading one line of input with getline(wordListFile, line);, but not doing anything with that line. Instead, you are reading the first word of the next line with wordListFile >> wordList;. This does not make se... |
72,510,195 | 72,510,453 | What is the effective way to replace all occurrences of a character with every character in the alphabet? | What is the effective way to replace all occurrences of a character with every character in the alphabet in std::string?
#include <algorithm>
#include <string>
using namespace std;
void some_func() {
string s = "example *trin*";
string letters = "abcdefghijklmnopqrstuvwxyz";
// replace all '*' to 'letter of alphabet'
... | You can just have a function:
receiving the string you want to operate on, and the character you want to replace, and
returning a list with the new strings, once the replacement has been done;
for every letter in the alphabet, you could check if it is in the input string and, in that case, create a copy of the input s... |
72,510,236 | 72,511,114 | How to define class with overloaded methods for each std::variant alternative? | I have some std::variant classes, each with several alternatives, and I would like to define a visitor class template that takes a variant as its template parameter and will automatically define a pure virtual void operator()(T const&) const for each alternative T in the variant. This way, I can define subclasses that ... | After some some googling and lots of trial and error, I managed to come up with something that does what I want. I'm sharing the solution here for anyone else who comes across the same issue.
Here is a proof of concept.
#include <iostream>
#include <variant>
template <typename> class Test { };
using Foo = std::varia... |
72,510,589 | 72,510,732 | A temporary object in range-based for-loop | In Range-based for loop on a temporary range, Barry mentioned that the following is not affected by the destroyed temporary object, and I tested member v indeed exists throughout the for-loop (as the destructor ~X didn't get called throughout the for-loop). What is the explanation?
struct X {
std::vector<int> v;
... | This is an obscure form of temporary lifetime extension. Normally you have to bind the temporary directly to the reference for it to work (e.g. for (auto x : foo())), but according to cppreference, this effect propagates through:
parentheses ( ) (grouping, not a function call),
array access [ ] (not overloaded; must u... |
72,510,636 | 72,524,194 | Parametrized tests with parametrized SetUp()/TearDown() | I have a test fixture that shares most of the test code. The variations are mostly from a parameter value. I would like to create SetUp() / TearDown() for them, but they (obviously) can't be called with a parameter.
What would the best strategy to use SetUp() / TearDown() mechanisms while avoiding code duplication?
Thi... | The example of Value-Parameterized Test.
#include <string>
#include <gtest/gtest.h>
struct FileTools {
static bool RemoveFile(const std::wstring&);
};
struct FileToolsTestParam {
const std::wstring testFilename;
const std::wstring testContent;
} kFileToolsTestParam[] = {
{
L"testfile",
L"This\nis\ndummy... |
72,510,822 | 74,018,151 | Cannot load Qt5Compat.GraphicalEffects module in Qt 6.3 | I'm using the Qt 5 Core Compatibility APIs in my Qt 6 applications. In particular, I need the QtGraphicalEffects module in my Qt Quick Scene.
This is the full code of my main.qml file:
import QtQuick
import QtQuick.Window
import Qt5Compat.GraphicalEffects
Window {
width: 640
height: 480
visible: true
t... | As this thread said, You need install Shader tools module after Qt 6.4. Install it by MaintenanceTool, then it will be ok.
|
72,511,182 | 72,511,228 | Error while loading shared libraries when running executable | When I make the Makefile everything works fine, I get a library in the directory dir. And when I run "Make test" I get a testfile that I want to run. But when I want to run this file I get this weird error: ./programma: error while loading shared libraries: libprogramma.so: cannot open shared object file: No such file ... | Executables on Linux don't look for shared libraries in the directory they're located in, at least by default.
You can either fix that at link-time, by passing -Wl,-rpath='$ORIGIN', or at runtime, by setting LD_LIBRARY_PATH env variable to the directory with the library. (LD_LIBRARY_PATH=path/to/lib ./programma)
|
72,511,203 | 72,512,191 | How to convert an arbitrary length unsigned int array to a base 10 string representation? | I am currently working on an arbitrary size integer library for learning purposes.
Each number is represented as uint32_t *number_segments.
I have functional arithmetic operations, and the ability to print the raw bits of my number.
However, I have struggled to find any information on how I could convert my arbitrarily... | You do it the same way as you do with a single uint64_t except on a larger scale (bringing this into modern c++ is left for the reader):
char * to_str(uint64_t x) {
static char buf[23] = {0}; // leave space for a minus sign added by the caller
char *p = &buf[22];
do {
*--p = '0' + (x % 10);
x /=... |
72,511,217 | 72,511,247 | How Can I instantiate a class template without a cast | I would like to run the first instantiation instead of the second, but the compiler takes the arguments as integers and returns errors.
Note that the use of optional is to allow the object to receive a boost::none (C++ version of python's None).
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/optional.hpp>
... | You can always put the explicit casts inside of the Point constructor.
template<typename S>
explicit Point(S x, S y): x(T(x)), y(T(y)) {}
But I suspect that doing so will introduce more confusing type errors in the long run. My recommendation is to explicitly call the boost::optional constructor like you're supposed t... |
72,511,236 | 72,511,237 | DirectSound crashes due to a read access violation when calling IDirectSoundBuffer8::Play (inside LFQueuePut, a dsound.dll internal function) | I am working on a game, and am sporadically observing crashes inside of dsound.dll.
This happens right after creating a IDirectSoundBuffer8 audio buffer, when calling the Play method on it. At this point I haven't written to the buffer or done anything to the sound system besides creating the audio device, setting the ... | After hunting this bug down by process of elimination, it seems to be a Windows/Driver issue. In short: DirectSound may crash your application if you reserve 10 TiB of address space. I'm using this address space for a debug allocator that helps hunting down use-after frees, and for some reason DirectSound seems to inte... |
72,511,490 | 72,521,236 | c++ statically assert that a function is never called | For some complicated reasons I want to create default constructor (alongside my normal constructors) that always throws. I want it to be there, but I also want it never to be called. It is pretty obvious that during runtime I can check for that thrown exception and for example terminate program when I catch it, but the... | As you've stated in your comments that you never want to instatiate Base, Left or Right object, then you should make them abstract, even by some empty method:
class Base {
private:
// ...
virtual void DefineIfNonAbstract() = 0;
};
class Bottom: public Left, public Right {
void DefineIfNonAbstract() final {};
... |
72,511,624 | 72,511,653 | C++ error: "pointer being freed was not allocated" | I never invoke free in my code, so I don't know why I'm getting this error.
I wrote a program to find integer partitions of a number. It worked fine. Then I decided I wanted to try and use a pointer to the vector to avoid unnecessarily copying my std::vector<ints>'s between iterations of a loop. It compiles (using g++ ... | if (current_sum == sum)
{
// ...
vector<int> next_xs;
As you can see here: next_xs is declared inside the if statement. When the if statement finishes, next_xs gets destroyed. That's how locally-declared object, in automatic scope, work.
xs = &next_xs;
A pointer to this object... |
72,511,754 | 72,511,972 | Safely type punning POD-like structures in-place in C++20? | There have been multiple questions asking about mmap and accessing structures in the shared memory while not invoking UB by breaking the strict aliasing rule or violating object lifetimes.
mmap and C++ strict aliasing rules
Dealing with undefined behavior when using reinterpret_cast in a memory mapping
How to properly... |
Guaranteed O(1) initialization without overwritting the data.
Not so much.
Indeed, P0593 explicitly mentions that this will not work:
Symmetrically, when the float object is created, the object has an indeterminate value, and therefore any attempt to load its value results in undefined behavior.
[basic.indent] cont... |
72,511,936 | 72,512,047 | Is there a value of type `double`, `K`, such that `K * K == 3.0`? | Is there a value of type double (IEEE 64-bit float / binary64), K, such that K * K == 3.0? (The irrational number is of course "square root of 3")
I tried:
static constexpr double Sqrt3 = 1.732050807568877293527446341505872366942805253810380628055806;
static_assert(Sqrt3 * Sqrt3 == 3.0);
but the static assert fails.
... | Testing with Python is valid I think, since both use the IEEE-754 representation for doubles along with the rules for operations on same.
The closest possible double to the square root of 3 is slightly low.
>>> Sqrt3 = 3**0.5
>>> Sqrt3*Sqrt3
2.9999999999999996
The next available value is too high.
>>> import numpy as ... |
72,511,999 | 72,524,080 | Pass context through composed promises in KJ | Playing with the KJ library, I wrote a small TCP servers that reads a "PING" and responds a "PONG". I managed to compose the promises like this:
char buffer[4];
kj::Own<kj::AsyncIoStream> clientStream;
addr->listen()->accept()
.then([&buffer, &clientStream](kj::Own<kj::AsyncIoStream> stream) {
clientStream =... | It seems your problem is that your second lambda wants access to the scope of the first lambda, but the way you've organised things prevents that. You've worked around that by just adding variables to their shared "global" scope.
Instead, you could put the second lambda inside the first, something like this:
addr->list... |
72,512,383 | 72,512,448 | Getting unhandled exception in double linked list in C++ | I created a doubly-linked list in C++. Everything works great if I insert a node at the beginning of the list or if I just insert a node at the end of the list; but, when I insert a node at the beginning and then try to insert a node at the end, I get a null pointer error!
Here is the code and the problem is in the Ins... |
the problem is in the InserAtEnd function
How do you know?
In fact the problem isn't in InserAtEnd but in Insert:
You never set list.tail.
Tip: use Node **tail = &head; for a more efficient MyList and add member initializers and a Constructor.
This is C++ with classes. Use member functions.
|
72,512,432 | 72,512,563 | Is it possible to pass an object as a parameter to a function without copying it? | Look at this code
#include <iostream>
#include <vector>
class Entity {
public:
Entity(int x, int y) : x(x), y(y) {std::cout << "DEFAULT\n";}
Entity(const Entity& that) {
std::cout << "COPY\n";
this->x = that.x;
this->y = that.y;
}
Entity(Entity&& that) {
std::cout << "... | When you call
L.Add(Entity(10, 20));
the following operations happen:
Entity(10, 20) creates a temporary
List::add is called with temporary
std::move() makes the temporary movable
vector::emplace_back is called with the temporary
vector resizes
vector calls construct_at with the temporary
construct_at calls placement ... |
72,512,492 | 72,513,551 | How to scale without changing object translated position | I have a problem to scale an object without changing translated position. I tried to apply translate and scaling using keybind for my car but when i click the keybind for scaling, only my body repositioned it self but the car's tire scaled at the fixed position i translated. Below is my code:
#include <windows.h>
#incl... | Each glVertex is transformed by the current model view and projection matrix when it is specified.
You have to scale the complete object (car and wheels) before any other transformation. Use glTranslatef and glScale to multiply the current matrix by a general scaling matrix, glPushMatrix to save the matrix on the matri... |
72,512,612 | 72,512,638 | How to get pair from a map using key in C++ | I have the following map:
std::map<char, std::pair<int, int> > robots;
I am using this function to populate the map given the input meets certain conditions:
bool World::addRobot(int row, int col, char robot_name) {
// This if block checks if the desired location is a valid 1 and keeps a track of all the robots a... | An iterator for a map "points to" a std::pair<const KEY, VALUE>.
For your map, the KEY is char and the VALUE is std::pair<int, int>
So in your code, instead of:
std::pair<int, int> location = robots.find(robot_name);
you need to:
std::pair<int, int> location = robots.find(robot_name)->second;
Also, you need to check ... |
72,513,081 | 72,785,671 | cv-qualifier propagation in structured binding | As quoted in dcl.struct.bind,
Let cv denote the cv-qualifiers in the decl-specifier-seq.
Designating the non-static data members of E as m 0 , m 1 , m 2 , ... (in declaration order), each v i is the name of an lvalue that refers to the member m i of e and whose type is cv T i , where T i is the declared type of that... | decltype has a special rule when the member of a class is named directly as an unparenthesized member access expression. Instead of producing the result it would usually if the expression was treated as an expression, it will result in the declared type of the member.
So decltype(rf.x) gives int, because x is declared ... |
72,513,273 | 72,513,383 | How can I trigger copy constructor of a parent templated class inside the child class | How can I call the copy constructor of the parent templated class inside the copy constructor of the child class?
// Type your code here, or load an example.
#include<vector>
#include <iostream>
template <typename T>
class Parent {
public:
Parent() {};
const std::vector<T>& getDims() const { return m_dims; };
... | template <typename T>
class Child : public Parent<T> {
public:
Child() {};
Child(const Child& c): Parent<T>(c) {
m_center = c.getCenter();
}
private:
std::vector<T> m_center;
};
Your base class is Parent<T> here.
|
72,513,282 | 72,513,306 | Correlation Id and Message Id in IBM MQ | For a c++ and c program, I am trying to set a value for msgId or CorrelId for a particular message in IBM MQ, that will be later put to a topic. But there's an error of "Expression must be a modifiable L-value" for both the ids.
I defined the ids as
MQBYTE24 MsgId;
MQBYTE24 CorrelId;
and the MQMD is defined as default... | I would expect you to have some code that looks like the following:-
memcpy(md.CorrelId, CorrelId, MQ_MSG_ID_LENGTH);
Please also remember that the message ID that you MQPUT to a topic does not end up at the subscribers. A new message ID is created for each copy of the published message that is given to each subscribe... |
72,513,351 | 72,513,472 | How to update values in C++ std::pair<int, int> | I have this function that returns the location of a robot (which is just a [row][col] pair of indices from a matrix):
std::pair<int, int> World::getRobotLocation(char robot_name){
auto const & location = robots.find(robot_name);
if (location == robots.end()) {
std::cout << "Robot " << robot_name << " do... | Your first function has a bug. It reports when a robot is not found, but still dereferences the end iterator, which causes undefined behavior. Instead, you should return a pointer, which is conditionally null:
// Returns null if the robot is not found:
std::pair<int, int>*
World::getRobotLocation(char robot_name){
... |
72,513,631 | 72,516,141 | Compile each cpp file in separate directory | The results for this topic strangely all did not work.
Finally I found a variant that is logical for me and works from the same order.
CC := g++
CFLAGS := -g -Wall
objects = test helloworld
all: $(objects)
$(objects): %: %.cpp
$(CC) $(CFLAGS) -o $@ $<
I have tried a lot and probably fail to fully understand t... | Try this:
CXX := g++
CXXFLAGS := -g -Wall
TARGETS=obj/test.out obj/helloworld.out
all:$(TARGETS)
obj/%.out:src/%.cpp
$(CXX) $(CXXFLAGS) -o $@ $^
clean:
rm obj/*
|
72,513,933 | 72,514,405 | Why my logic is failing in certain test cases? | I am solving this problem on codeforces :
https://codeforces.com/contest/1492/problem/C
My code:
#include <bits/stdc++.h>
using namespace std;
#define int long long
int32_t main() {
int n,m;
cin>>n>>m;
string str1,str2;
cin>>str1;
cin>>str2;
int i=0;
int p=0;
... | Your code doesn't seem to be implementing your algorithm. In the loop you have
vec.push_back({i,i});
vec.push_back({i+q-p,j});
So the resulting vector would be alternating pairs of equal indexes and (potentially) different indexes. But:
[(0,0) , (1,3) , (4,8) ,(9,9)]
The (4, 8) pair can't be produced by {... |
72,514,145 | 72,514,204 | Address of an array different with the address of the first element? | As I know address of array a is the address of first element of this array.
void func(int a[])
{
cout << "address in func: " << &a << endl;;
cout << "GT: " << &a[0] << endl;
}
int main ()
{
int a[] = {0,1,2,3};
cout << "address in main: " << &a << endl;
cout << "address in main a[0]: " << &a[0] << ... |
Why address of array a in func() difference with address of a[0]?
Because you're calling the function func() passing a by value. This means the a inside the function func() is actually a copy of the original decayed pointer that you're passing to func() from main(). And since they're different variables, they have di... |
72,514,271 | 72,514,696 | Adding a char matrix as a function argument throws syntax error | I have a function that validates whether certain coordinates are within a matrix and returns true/false depending on the answer:
bool validateNextLocation(char robot, int proposed_row, int proposed_col, char map[7][7]){
auto const robot_location = World::getRobotLocation(robot);
int row = robot_location -> firs... | Just change
if (World::validateNextLocation(robot, robot_location->first,
++robot_location->second, char a[7][7])){
to
if (World::validateNextLocation(robot, robot_location->first,
++robot_location->second, a)){
Declaring an array, and using an array are two different things, you don't use the same syntax f... |
72,514,475 | 72,556,597 | In C++, how to pause and resume a thread from outside? | I want to pause and resume a thread from outside, and at any time (not at certain breakpoints, and thus wait and notify won't work).
For example, we create a thread in foo(), and then it keeps running. (the Thread could be any thread class similar to std::thread)
void A::foo() {
this->th = Thread([]{
// Thi... | @freakish said it can be done with pthread and signals, but no portable way.
In Windows, I just found SuspendThread(t.native_handle()) and ResumeThread(t.native_handle()) (where t is of type std::thread) are available. These would solve my problem.
|
72,514,674 | 72,569,768 | Why SQLite queries run slower in Windows [server] machine compared to Ubuntu & MacOS? | We have 3 machines: One has Windows server OS 2012-r2 installed with decent specs (12 GB RAM, 3.6 GHz, 4 cores, 600 GB hard disk). The others are home laptops with regular specs of Ubuntu 20.04 & MacOS. All are dealing with an SQLite DB.
In a loop, simple 4000 SELECT - COUNT queries are run to calculate certain value ... | Turns out that the performance was worsening due to a Mutex lock every time before a SELECT + UPDATE. This was meant for the thread safety as the DB is expected to be accessed from the multiple threads.
After changing the design where the DB is now accessed from the single thread, the performance improved manifold. In ... |
72,514,822 | 72,517,366 | How to make glog output not fill 0 before number? | When I use glog to print an Eigen matrix in console, I found the output format has difference when using std::cout against using LOG(INFO). Here is the source code, in which 'sophus_R' is a 3x3 matrix.
LOG(INFO) << "using glog, sophus_R is:\n" << sophus_R.matrix();
std::cout << "using std::cout, sophus_R is:\n" << soph... | It seems the glog stream's fill character has been set to 0. I suggest explicitly setting it back to a space, ' ' using std::setfill:
#include <iomanip>
LOG(INFO) << "using glog, sophus_R is:\n" << std::setfill(' ') << sophus_R.matrix();
|
72,515,812 | 72,516,052 | VS code c++ debugger setup using GDB does not work | So here's my problem. I have downloaded mingw g++ by using msys according to the official vs code website
Here are my files:
Now, when I try to build I get this error:
> Executing task: g++ -std=c++14 -g -o myfile.exe myfile.cpp <
cc1plus.exe: fatal error: myfile.cpp: No such file or directory
compilation terminat... | I would make this a comment if I could. What is the name of the file where you have written #include <iostream>?* I think if you change the name of that file to "myfile.cpp", you might stop getting that error. You will probably get a different error saying that "main() cannot be found" or something like that, but that'... |
72,516,302 | 72,517,450 | C++ skip template instantiation for cases that don't satisfy requires clause | I'm writing something like STL red-black tree for practicing coding.
My TreeSet, TreeMap, TreeMultiSet, TreeMultiMap all share implementation of RedBlackTree, whose declaration is like this:
template <Containable K, typename V, typename Comp, bool AllowDup>
requires std::invocable<Comp, K, K>
class RedBlackTree {
//... | V is fixed by the class, so you cannot use SFINAE on it in member function.
You might introduce extra template parameter as workaround:
template <typename V2 = V, typename T>
std::add_lvalue_reference_t<typename V2::second_type>
operator[](T&& raw_key) requires (!std::is_same_v<K, V> && !AllowDup);
or use auto/decltyp... |
72,516,333 | 72,517,467 | Why is my code giving time-limit exceeded while a near identical code works just fine in LeetCode? | Ref: https://leetcode.com/problems/word-search/submissions/
Brief problem statement: Given a matrix of characters and a string, does the string exist in this matrix. Please refer the above link for details.
Solution-1 Gives time-limit exceeded.
class Solution {
public:
int n;
int m;
bool search(vector<vecto... | I am not sure about the time complexity of auto type! But if you remove the 2D vector construction from the recursive function, and instead of auto use the normal index-based loop to access the vector then you would pass the timelimit.
class Solution {
public:
int n;
int m;
vector<vector<int>> dir = {{-1, 0... |
72,517,177 | 72,559,317 | debug WINE 32bit C/C++ app in vscode using gdbserver | Problem
Trying to debug win hello world app cross compiled using i686-w64-mingw32-g++-posix in VSCode. But VSCode fails to attach to dbgserver.
Repo
VSCode project repo is located HERE.
Setup
Cross compile win app on nix
Compiler is configured to use i686-w64-mingw32-gcc-posix and i686-w64-mingw32-g++-posix for C and C... | Some gdbserver configs were missing
After changes dbgserver running wine app works fine. Boiler plate project for 32 bit wine app acn be found HERE.
|
72,517,940 | 72,518,049 | Why are there so many zeros in the binary file? | Let me use this simple Hello world program as an example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!";
}
Compile using: g++ hello.cpp
From quick inspection of the binary file in a text editor, it seems that about half of the resulting binary is only zeros, most of them in large bl... | A program file consists of some metadata, executable code, read-only data, data. Each of those is aligned to the page size of your system so that they can be mapped into memory. Those "large unused blocks" are just padding to bring everything to alignment. It's only looks large because your program is basically nothing... |
72,518,552 | 72,518,660 | Send and receive uint32_t over a socket via iovec | I'm trying to send a uint_32t type variable over iovec sturct over unix domain socket.
My iovec declaration:
uint32_t request_id = 123456;
struct iovec io = { .iov_base = &request_id, .iov_len = sizeof(uint32_t) };
on the receiving side:
char dup[4];
struct iovec io = { .iov_base = dup, .iov_len = sizeof(dup) };
msg.m... |
When I print msg.msg_iov[0].iov_base I get a different number every time.
Yes, on the sending side it's the address of request_id and on the receiving side it's address of dup. These addresses do however not matter. They are only used to tell writev and readv where to read/write the data and they will often be differ... |
72,518,792 | 72,520,174 | Wrap a C header in C++ | Suppose I have some C code that I want to wrap using C++ without exposing the C code to the user.
My first attempt was to manually include all headers used in the C code before including the C headers inside a namespace, to hide them from the global scope. This seemed to initially work and compile, however, after tryin... | You could use the pimpl idiom to hide all the C headers and structs inside your .cpp file.
Example .hpp file:
#pragma once
#include <memory>
class Wrapper {
public:
Wrapper();
Wrapper(const Wrapper&);
Wrapper(Wrapper&&) noexcept = default;
Wrapper& operator=(const Wrapper&);
Wrapper& operator=(Wrap... |
72,519,240 | 72,823,567 | How to get Nokia S30+'s MRE vxp file to run on nokia 225? | The setup
Ok let's me talk a bit about the setup:
I have installed Visual Studio 2008 (the edition that let you try for 90 days), MRE SDK 3.0 from this Github issue, Sourcery Codebench Lite for ARM EABI and also ARM Realview Development suite 3.1 (but it requires license, and I am too lazy to cr@ck it, also I prefer th... | Delivered from my answer at RE.SE
First I want to say thanks to people at 4pda forum. See their thread here.
Can you figure out informations about the MRE VXP format
Well I haven't found yet, need further research
how to get it signed
Short answer:
Step 1: Get your SIM 1's IMSI number (NOT IMEI, they are DIFFERENT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.