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 |
|---|---|---|---|---|
70,515,157 | 70,519,392 | Trouble Creating a GLFW OpenGL Window in C++ | Here is the current bit of code I'm working on:
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowH... | According to the GLFW documentation, the value for the GLFW_OPENGL_PROFILE window hint must be GLFW_OPENGL_ANY_PROFILE if the requested OpenGL context version is less than 3.2 (and GLFW has a platform-independent check built-in whenever glfwCreateWindow is called).
See: https://www.glfw.org/docs/3.3/window_guide.html#G... |
70,515,349 | 70,516,422 | glm::rotate() changes the rotation axis, but why? | Easy test code
glm::mat4 m = glm::rotate(glm::mat4(1.0f), 0.78f, glm::vec3(0,1,0));
while (true) {
glm::vec3 axis = glm::normalize(glm::vec3(m[0])); // right vector
PRINT_VEC("{0:.3f} {1:.3f} {2:.3f}", axis.x, axis.y, axis.z);
m = glm::rotate(m, glm::radians(5.f), axis); // 5 degrees each iteration
}
So... | m[0] isn't truly the 'local right vector'. The local right vector is vec3(1,0,0), which is what you should use to achieve the desired rotation:
glm::mat4 m = glm::rotate(glm::mat4(1.0f), 0.78f, glm::vec3(0,1,0));
while (true) {
glm::vec3 axis = glm::normalize(glm::vec3(m[0])); // right vector
PRINT_VEC("{0:.3... |
70,515,424 | 70,515,823 | Can't push element into priority queue, when element type is std::pair<int, const std::string &> | I want to order some strings by their indexes. And I don't want to use two different types of priority queue.
#include <string>
#include <queue>
#include <utility>
int main() {
const std::string &a = "hello";
std::pair<int, const std::string &> p = std::make_pair(1, a);
std::priority_queue<std::pair<i... | This
const std::string& a = "hello";
std::pair<int, const std::string&> p = std::make_pair(1, a);
This will result in a dangling reference, because the type returned by make_pair is pair<int, string>, but you use pair<int, const string&> to receive it, which makes const string& bind the string in the newly created pai... |
70,516,508 | 70,516,645 | casting int32_t to std::complex<float> | I receive some data over a wire protocol. One of the packets I receive has some int32_t values that represent complex numbers. i.e. 10 complex numbers come in the form of 20 int32_t values (real,imag).
I need to convert the int32_t's to float's and copy these values into a vector<std::complex<float>>. I am not sure ... | Don't overthink it
complexFloatVector.resize(10);
for (size_t i = 0; i < 10; i++)
{
complexFloatVector[i] = std::complex<float>((float)(packet.coef[i * 2]), (float)(packet.coef[i * 2 + 1]));
}
I'm assuming complexFloatVector is a std::vector<std::complex<float>> type and packet.coef is an array of 20 integers.
|
70,516,557 | 70,516,599 | C++ reference wrapper as function argument | From my understanding, reference wrapper is just a wrapper on reference, nothing too special about it. But why it is treated as the reference itself (rather than the wrapper) inside the function when passed as a function argument?
#include <iostream>
#include <functional>
using namespace std;
void f(int& x){
cout<... |
f(ref(x)); // f on int called, why?
Because std::reference_wrapper has a conversion operator to the stored reference; ref(x) returns an std::reference_wrapper, which could be converted to int& implicitly.
void f(reference_wrapper<int>& x) takes lvalue-reference to non-const, std::ref returns by-value, i.e. what it r... |
70,516,584 | 70,516,840 | Is erasing a range more efficient than erasing each of the elements separately? | If you have defined a range of elements you want to "erase", is it more efficient to call vector::erase(iterator) for every element in the range, or to call vector::erase(iterator,iterator once?
| Of course it depends on circumstance but you can have a feeling by running some specifics. Let's see one example:
#include <iostream>
#include <vector>
uint64_t now() {
return __builtin_ia32_rdtsc();
}
template< typename T >
void erase1( std::vector<T>& vec ) {
while ( !vec.empty() ) {
vec.erase( vec.... |
70,517,333 | 70,583,289 | How to store Key / Value Pair wxDataViewListCtrl without using wxDataViewModel | I have below sample data available in database
SrNo | String
1 | Data1
2 | Data2
3 | Data3
4 | Data2
5 | Data1
String column value can be duplicate. User can also filter data displayed in wxDataViewListCtrl using wxSearchCtrl, so ID number displayed inside wxDataViewListCtrl might change based on filter used by user.
... | Use the "wxUIntPtr" parameter in AppendItem/InsertItem etc... to store your internal index.
wxVector<wxVariant> data;
data.push_back( wxVariant("Data1") );
listctrl->AppendItem( data, wxUIntPtr(1) ); // <<HERE, your index 1>>
data.clear();
data.push_back( wxVariant("Data2") );
listctrl->AppendItem( data, wxUIntPtr(2) ... |
70,517,433 | 70,517,479 | Why does this code have different outputs if pointers are incremented differently c++ | #include <iostream>
using namespace std;
int main() {
int num=10;
int *ptr=NULL;
ptr=#
num=(*ptr)++; //it should increase to 11
num=(*ptr)++; //it should increase to 12 but im getting 10
//if i dont initialize num and just use (*ptr)++ it gives me 11
cout<<num<<endl;
return 0;
}
I w... | (*ptr)++ increases num to 11 but returns its previous value (10), because the ++ is postfix.
So with num = (*ptr)++, you are temporarily increasing num to 11, but then (re)assigning it with 10.
|
70,517,692 | 70,650,632 | C++ Apache Orc is not filtering data correctly | I am posting a simple c++ Apache orc file reading program which:
Read data from ORC file.
Filter data based on the given string.
Sample Code:
#include <iostream>
#include <list>
#include <memory>
#include <chrono>
// Orc specific headers.
#include <orc/Reader.hh>
#include <orc/ColumnPrinter.hh>
#include <orc/Exce... | Finally after trying multiple scenarios, I have resolved the above issue with ORC data filtering.
It was because of using the incorrect column number, I am not sure why there is a difference between the column id of the columns to fetch and columns to filter.
In above example I tried to filter data with column name and... |
70,517,866 | 70,517,997 | Bit shifting a floating-point | I am working on a project of converting any real number into fixed point.
For example, the code below:
float ff = 8.125f;
std::cout << std::bitset<32>(ff) << std::endl; //print binary fotmat
Output:
00000000000000000000000000001000
Only the integer part is printed out.
When I do:
float ff = 8.125f;
int va = ff * (1... |
Only the integer part is printed out.
Well, of course, because that's all you've given the bitset: there is no std::bitset constructor that takes a float argument, so your ff is being converted to an unsigned long long, which will lose the fractional part (as any conversion of a floating-point type to an integral typ... |
70,517,952 | 70,518,420 | How flutter determine written code is for android or ios? | Could anyone please explain behind the scenes of the flutter determines written code is for android or ios.
| Dart is ahead-of-time (AOT) compiled into fast native X86 or ARM code for Android and iOS devices. Flutter can also call out to Android and use Android features only available in Java (same with iOS). Flutter is written in DART so we can't call that it compiles but DART does and it's rendering engine does.
Flutter Fr... |
70,518,554 | 70,519,302 | How to invoke method which using c++ operate | I wante to invoke method operator id () const below ,which writing by C++ opreate
struct CKBoxedValue {
CKBoxedValue() noexcept : __actual(nil) {};
// Could replace this with !CK::is_objc_class<T>
CKBoxedValue(bool v) noexcept : __actual(@(v)) {};
CKBoxedValue(int8_t v) noexcept : __actual(@(v)) {};
CKBoxedV... | You can call the user-defined conversion function operator id() const; like any other member function:
// (Assuming `x` is some value of type `CKBoxedValue`)
x.operator id();
But it is usually called during a type conversion, for example:
// Explicit conversions:
id(x)
static_cast<id>(x)
id value(x);
// Implicit con... |
70,518,606 | 70,518,683 | Why does a compiler allow a user to change the type of an 'auto' variable? | I expected the auto keyword to deduce the type of a variable from an intializer once and keep that type throughout the code. To my surprise, my compiler (g++ 9.3.0) allows me to change it's type and it still works. This is sort of acceptable to me when I first use the variable as an int and then as a float. But when I ... | To show you what's going on I extended the example with some compile time type checks:
#include <type_traits>
#include <iostream>
int main()
{
auto x = '2';
// decltype(x) is the type for variable x
// compare it at compile time with char type
static_assert(std::is_same_v<decltype(x), char>);
std... |
70,519,306 | 70,519,738 | fill an array of type class inside another class | I am new in c++ recently i started learning poo I want to create a class movies and a class.
directors a class movie should have an array of directors and I want to fill that array from the console. When I run the code it show me the first and second line and stop executing :
enter image description here
this is my cod... | A better way wold be to use std::vector as shown below. The advantage of using a std::vector is that you don't have to worry about manual memory management(like using new and delete explicitly). vector will take care of it(memory management). You can use the below given example as a reference.
#include<iostream>
#incl... |
70,520,081 | 70,520,296 | How to change the widgets property if I use QT Designer | I am using Visual Studio 2022 and C++ QT 5.14.2.
I used QT Designer to setup a PushButton and a LineEdit, and I gave them some initial property. But I met problem in button clicked signal slot function, this is my code:
void SocketChat::on_connectButton_clicked() {
appendMessage(ui.connectButton->text()); // outpu... | You are missing some else keywords.
Note that when your button is clicked the first if-block (labeled "// disabled") is execute and it disables the ui.addrEdit button. Due to the missing else keyword the program then also checks the conditions of the other if statements. And since the button is now disabled the last co... |
70,520,112 | 70,522,191 | Compiler doesn't see the C++11 identifiers | When I was trying to build the Google test c++ project I caught the errors
Error C3861 't1': identifier not found
Error C2065 't1': undeclared identifier
Error C2039 'thread': is not a member of 'std'
Error C2065 'thread': undeclared identifier
Error C2146 syntax error: missing ';' before identifier... | #include "pch.h" must be first. Other #include directive prior #include "pch.h" are ignored.
|
70,520,308 | 70,520,560 | C++ variant containing a map of itself | I would like to be able to create a variant that contains a std::map<std::string, MyVariant> as one of its cases. The ideal would be able to write something like
using MyVariant = std::variant<int, std::string, std::map<std::string, MyVariant>>;
but this requires forward declaration.
I'm aware that similar questions h... | This is not possible (at least by standard guarantees), since std::variant requires the used types to be complete and std::map requires key and value type to be complete types at the point of instantiation. But your construction will be complete only after it's instantiation.
The only standard containers allowing such ... |
70,520,869 | 70,520,941 | How to make a class public only to another class | I have two separate distinct classes in C++, Node and Graph. I want to make the contents of Node accessible via the methods in graph but not public, how do I do this?
| You can use a friend declaration to specify classes or functions that you'd like to give full access to the private and protected members.
Example:
class Node {
// ...
private:
friend class Graph;
int x;
};
class Graph {
public:
void foo(Node& n) {
n.x = 1; // wouldn't work without `friend` a... |
70,521,298 | 70,521,978 | Is this correct: std::views::reverse on infinite range? | See this example code:
#include <ranges>
int main() {
for(auto i : std::ranges::iota_view(1) | std::views::reverse)
break;
}
It compiles on gcc (I cannot check on clang/msvc - since they do not support ranges).
Of course -- it runs "forever" and does nothing.
I also checked that doing std::ranges::rbegin... | According to [iterator.requirements.general-10]:
A sentinel s is called reachable from an iterator i if and only if
there is a finite sequence of applications of the expression ++i that
makes i == s. If s is reachable from i, [i, s) denotes a valid range.
And [iterator.requirements.general-12]:
The result of the app... |
70,521,545 | 70,521,638 | Why is my C++ output not showing in VS Code Terminal (GCC) | Trying to get the output of my basic C++ program in VS Code but it's not displaying in terminal
Using the run icon
This is what is being in the terminal Terminal screenshot
However, if I do this, then the output is shown as usual
Using Run tab and debugging
Final-Terminal
Please let me know what is happening here, I do... | Your source code file is named "full pyramid". This is causing the compiler to try to compile it as two separate files, called "full" and "pyramid". Try naming the file "full_pyramid" instead.
|
70,521,607 | 70,523,009 | How do I set up a CMake project with subfolders? | I'm new to CMake so I apologize if my question turns out to be a noob one.
I'm trying to set up a project in C++ with a directory structure similar to what Maven would create if I was coding in Java (src directory and build directory):
root
├── build (where to build)
├── CMakeLists.txt (main one)
├── compile_commands.j... |
Can you please tip me if this project/cmake structure is best practice or not?
There are none, or endless, best practices, and every day someone invents a new one. Especially as to how to structure your project, which is unrelated to CMake. Structure it in a way that you want, and you judge is the best. Your structur... |
70,522,231 | 70,522,361 | How to know if some data type is from std? | Is there any list of types inside std namespace? I'm writing translator from uml diagram to c++ code, that should add std:: when it's needed. How my program should know that string has prefix std:: and int doesn't.
|
Is there any list of types inside std namespace?
All of them are mentioned in the standard, as well as any documentation that covers the standard. There's no plain list that I know of however.
How my program should know that string has prefix std:: and int doesn't.
Your program should know that int isn't in a names... |
70,522,630 | 70,522,885 | Why do gcc and clang give different results in aggregate initialization? | #include <iostream>
struct U
{
template<typename T>
operator T();
};
template<unsigned I>
struct X : X<I - 1> {};
template<>
struct X<0> {};
template<typename T>
constexpr auto f(X<4>) -> decltype(T(U{}, U{}, U{}, U{}), 0u) { return 4u; }
template<typename T>
constexpr auto f(X<3>) -> decltype(T(U{}, U{... | U is a type which claims convertibility to any other type. And "any other type" includes whatever T is provided to the f templates.
Therefore, 1 is always a potentially legitimate overload; SFINAE permits it to exist.
A is an aggregate of 3 elements. As such, it can be initialized by an initializer list containing anyw... |
70,522,815 | 70,523,024 | Right-angled triangle pattern with recursion numbers C++ | I'm trying to print a right angled triangle with ascending and descending numbers using recursion only.
void straightTriangular(int num)
{
if (num == 0)
{
return;
}
straightTriangular(num - 1);
for (int i = 1; i <= num; i++)
{
cout << i;
}
cout << endl;
}
How can I do ... | You can have:
a printTriangleRec function that goes on printing every line recursively,
two printAscendingRec and printDescendingRec functions that print the two halves of each line recursively.
[Demo]
#include <iostream> // cout
void printAscendingRec(int cur, int top)
{
std::cout << cur;
if (cur != top)
... |
70,523,110 | 70,523,168 | Memory leak warning when using dependency injection using a unique_ptr containing a mocked interface | My main question is about a specific gmock error but to provide some background. I have been working on a larger project where I have different implementations of the same interface. I want to be able to instantiate a class using the interface and choose which interface implementation it has to use (when creating the c... | std::unique_ptr<Base> base = std::move(mock); is where the memory leak happens: *base will be destroyed as a Base, not a Mock, when base is destroyed.
The best fix is to add a virtual destructor (virtual ~Base() = default;), which you should have for a struct that has any other virtual members.
|
70,523,134 | 70,523,572 | Global variable and static global variable | Is there any difference in C++ between global variable/const and global static variable/const? Declared in cpp file or a header file.
static const int x1 = someFunction(5);
const int x2 = someFunction(6);
static int x3 = someFunction(5);
int x4 = someFunction(6);
int main()
{
...
| Case I: For const objects
Similarity
In both versions, the variables have internal linkage. That is, both x1 and x2 have internal linkage.
Difference
In case of static const int x1 the variable is explicitly static while in case of const int x2 the variable is implicitly static. But note that they both still have inte... |
70,523,217 | 70,523,478 | How does gcc compile C functions in a constexpr context? | Given that the C++ standard library doesn't (currently) provide constexpr versions of the cmath functions, consider the program below.
#include <cmath>
#include <cstring>
int main()
{
constexpr auto a = std::pow(2, 10);
constexpr auto b = std::strlen("ABC");
}
As expected, MSVC++ and clang++ fail to compile t... | The resolution of LWG 2013 was that implementations are not allowed to declare non-constexpr functions as constexpr, so gcc is non-conformant by allowing these to be evaluated at compile time.
That said, GCC does not actually mark the needed functions as constexpr. What it instead does is replace those calls very early... |
70,523,455 | 70,523,581 | Assignement and addition overload for template objects | I am trying to learn templates and overloads at the same time. I have wrote the code below but I fail to do assignement of the data object with built-in types. What am I dooing wrong and how to solve it and yet better what is the best practice that can result in no intemediate-copy constructors to be called?
I want to ... | For starters you may not overload an operator just by the return type as
void operator=(const T& t) {
this->d += t;
}
Data operator=(const T& t) { // FAIL
return Data(this->d + t);
}
As for other problem then in this statement
d = c + 1;
the expression c + 1 has the return type void due to the declaration of... |
70,523,731 | 70,523,846 | I am getting C++ compilation issues while compiling my project | I am trying to implement the zoom sdk and want to prevent my screen to be captured and by screen shots for this purpose they have given some functions to be placed inside the project. When I place the code inside the function I start getting some errors and when I remove then the errors are gone.
The code which need to... | You need to add a reference to the respective library(dll) you're using in the function you're trying to put inside the library.
As seen in your code above you're trying to use standard Windows libraries. Have you tried editing your project properties then linker input options to include user32.lib?
|
70,523,821 | 70,524,136 | (C++) Writing and reading a dynamic array to a binary file | I'm new here so forgive me if I make some mistakes.
Anyway, I've got this code here:
class List{
private:
int dim;
Reservations *res; //Dynamic array of reservations that composes "List"
public:
List();
List(int dm, Reservations *resv);
~List();
int getDim();
... | To be able to read/write a structure to/from a file as a binary blob, that structure must be standard layout type (aka POD) and not contain any pointers within. Your structure obviously does not satisfy that requirement (std::string object is not a standard layout type and does contain a pointer(s) inside) so you have ... |
70,523,952 | 70,524,035 | Why am i getting numbers in scientific form in simple calculations? | Background: So I basically googled projects for beginners for C++ and one recommendation was currency converter. So I decided to do this, at first I tried to do it by creating a class, objects etc but I got lost with constructors and header files etc but that's a story for another day. I am very new to programming and ... | A typical case of uninitialized variable. Here you are operating on euro variable before asking(cin) value for it, The correct implementation would be something like:
#include <iostream>
int main()
{
double euro = 0; //always put some values beforehand
//accepting input from the user
std::cout << "Amount i... |
70,524,164 | 70,524,204 | CMAKE_C_COMPILER not set, after EnableLanguage | I installed CMake on windows in addition to gcc and g++ compiler
I added the variables to the path but still getting the following error could you please help.
-- Building for: NMake Makefiles
CMake Error at CMakeLists.txt:6 (project):
Running
'nmake' '-?'
failed with:
The system cannot find the file spec... | These variables need to be passed on the command line as:
$ cmake -DCMAKE_CXX_COMPILER=/pathto/g++ -DCMAKE_C_COMPILER=/pathto/gcc /pathto/source
or set up before the project() line in CMakeLists.txt:
set( CMAKE_CXX_COMPILER "/pathto/g++" )
set( CMAKE_C_COMPILER "/pathto/gcc" )
project(mytest)
...
or alternatively br... |
70,524,574 | 70,524,808 | How to return a string with no overhead inside helper function | I want to put this logic into a helper function:
std::stringstream ss;
std::string str = "some str";
if (do_check(str)) {
ss << str;
} else {
ss << do_edit(str);
}
and instead write it like
std::string edit_str(const std::string &str) {
if (do_check(str)) {
return str;
}
return do_edit(str);
}
main()... | The standard library sets the standard for how to do this with functions like std::quoted. The function actually does no work; it just stores references to the arguments into an object, called the IO manipulator. Then the operator<< for that object is what does the actual work. We can simply follow their example.
struc... |
70,524,923 | 70,525,269 | C++ - Convert any number of nested vector of vector to equivalent vector of span | following situation: I work with data that falls into the categories of
std::vector<T> data1;
std::vector<std::vector<T>> data2;
std::vector<std::vector<std::vector<T>>> data3; //etc...
T usually refers to numerical data like double.
Sometimes I would like to get the data in a form where the last std::vector is replac... | You might do:
template <typename T, typename F>
auto transform(std::vector<T>& v, F func)
{
std::vector<std::decay_t<decltype(func(v[0]))>> res;
res.reserve(v.size());
std::transform(v.begin(), v.end(), std::back_inserter(res), func);
return res;
}
template <typename T>
std::span<T> to_span(std::vector... |
70,525,253 | 70,525,712 | std::set of MyElement with MyElement::SomeMethod as custom comparator | I have a simple MyElement class, and I would like to use a bool MyElement::SomeMethod(...) {...} as the custom comparator for a std::set of MyElement items.
I have made my research, and I am already aware of some alternative solutions, which I list below.
I also know how to change, for example, the comparator with std:... | You can use std::mem_fn to bind a member function.
#include <functional>
#include <iostream>
#include <set>
#include <utility>
struct S {
int i;
bool cmp(const S& other) const { return i < other.i; }
};
// Define make function to avoid having to write out template types.
template <typename T, typename Cmp>
std::... |
70,525,450 | 70,525,555 | Why move constructor and assignement not being called for initializing a vector with initialize_list | I have the class below and tried to add copy and move constructor and assignment operator. My goal is to have least amount of copy and be as optimized as possible.
I expect the vectors to be filled in place, that is no copy constructors be called while creating the vector. What am I doing wrong and how to force it to u... |
I expect the vectors to be filled in place
Both push_back and the initializer list constructor expect that the element is already constructed and passed through the parameter. Therefore the elements must first be constructed via conversion and then moved/copied into the vector's storage. If you don't want that, then ... |
70,525,752 | 70,525,904 | Is it possible to check the type of a derived class from an array element which is of the base type? | I created two objects from derived classes (Dog and Cat), which I assigned to one common array, which is the Animal type. Now I want to check a single element of the array to see if it is a dog. If there is, I want it to execute a method from Dog class and bark.
#include <iostream>
using namespace std;
class Animal{
p... | Others have commented as to why you are having this issue but have not really suggested a fix. You should get into the habit of using dynamically allocated objects and ensuring they behave nicely by using std::shared_ptr and std::vector.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
clas... |
70,526,117 | 72,820,737 | How to patch 3rd party .so file, to access non-exported symbol (C++) | I have some binary .fic files in a proprietary format , I have a wd250hf64.so from this vendor that contains a C++ method CComposanteHyperFile::HExporteXML(wchar_t* const path)
that I can see using nm
$ nm --demangle wd250hf64.so --defined-only
0000000000118c90 t CComposanteHyperFile::HExporteXML(wchar_t ... | If you really want to be able to get at that symbol in any way possible, you could try to get its address relative to that of a known exported symbol, assuming that they're in the same section. For example, I made a simple dummy library with one exported function and one non-exported function.
0x0000000000003890 12 ... |
70,526,654 | 70,526,711 | Where is the rvalue coming from? | I learning about references and value categories because the latter are mentioned in some C++ errors.
I have a function, referenceToDouble that takes in references to double. From watching this video on value categories, I believe that left and right below are lvalue references to double.
In main when I make variables ... |
Is there a temporary variable that contains the double value of a that was cast from float? And is this temporary then the rvalue?
Yes. left and right with type double& can't bind to floats directly. They have to be converted to doubles firstly, which are temporaries (rvalues) and can't be bound to lvalue-reference t... |
70,526,932 | 70,527,714 | How to understand the coalesced access in this CUDA matrix copy code? | __global__ void Matrixcopy(float *odata, const float *idata)
{
// threadblock size = (TILE_DIM, BLOCK_ROWS) = (32, 8)
// each block copies a 32 * 32 tile
int x = blockIdx.x * TILE_DIM + threadIdx.x;
int y = blockIdx.y * TILE_DIM + threadIdx.y;
int width = gridDim.x * TILE_DIM;
for (int j = 0; j < TILE_DIM;... |
So this code is with coalesced access. Am I correctly understood?
Yes, pretty much. I would have said the threads are x = [0, 1, 2, 3, 4, 5, 6...], and they access contiguous addresses [0, 1, 2, 3, 4, 5, 6...] but basically we are in agreement.
if we have a complex cuda kernel, how can we quickly determine whether ... |
70,526,946 | 70,527,266 | Best way to display hierarchal data using Windows API (like that of the Registry Editor) | What is the best way to display data hierarchally, like that of the registry editor, with the Win32 API? Are there any controls that could do this? I know of this method in .NET, but I really don't feel like creating a ton of interactions between managed code and C++.
| After you have created the TreeView control and added it to your window (see link in comments), you can load the registry keys like this. You would need some more code to add the values in a list view.
void LoadRegRec(HWND tree_view, HTREEITEM parent, HKEY root)
{
DWORD index = 0;
TCHAR name[512];
while (ER... |
70,527,237 | 70,527,731 | Why does assigning 256 to a char raise a warning, but assigning 255 don't, but both result in integer overflow? | Consider this example:
#include <iostream>
int main()
{
char c = 256;
std::cout << static_cast<int>(c);
}
Raise a warning:
warning: overflow in conversion from 'int' to 'char' changes value from '256' to ''\000'' [-Woverflow]
But this:
#include <iostream>
int main()
{
char c = 255;
std::cout << static... | It is important to specify whether char is signed in your example or not, but going by your link it is signed.
If you write
char c = 256;
256 has type int, so to store the value in c a conversion to char has to happen.
For signed target types such integer conversions produce the same value if it is representable in th... |
70,527,832 | 70,527,928 | safe way to get the n-th element of a union | I am writing a variant class(yes i know about std::variant, its just for fun), and this is what i have so far
template<typename First, typename... Rest>
union Variant<First, Rest...>
{
template<size_t N>
using Types = typename Type<N, First, Rest...>::_Type;
First first;
Variant<Rest...> rest;
uint1... | What you essentially want to know is if the operation:
*(Types<N>*)&first
adheres to strict aliasing. The answer is yes, so long as the type returned by Types<N> is a compatible type:
The types T and U are compatible, if they are the same type (same name or aliases introduced by a typedef)
In your example i am guess... |
70,528,043 | 70,528,077 | Shellcode execution in C++ | Working on some test projects, and I have this code, which works fine:
#include <windows.h>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
char shellcode[] = "..snip..\xa0\x4e\xbc\x0b\x45\xee\xb3\x1b\xf9..snip..";
void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXEC... | In your first example, sizeof shellcode is the size of the array itself. In your second example, sizeof shellcode is the size of the pointer. It will always be either 4 or 8.
Change the VirtualAlloc and subsequent memcpy statements to this:
void* exec = VirtualAlloc(0, test.size(), MEM_COMMIT, PAGE_EXECUTE_READWRITE... |
70,528,232 | 70,528,360 | implementing a cpp const iterator crashes and burns | Many posts about const iterators (example), but none in the context of loops like:
for (const auto it: container) { ... }
When I started implementing, I was encouraged by the compiler's complaints about missing begin and end, hoping such complaints can guide me to fill in the missing pieces. I was wrong. The following... | You have not defined ++ and !=, but they are perfectly well-defined for your iterator type, const List<T>*, because is a pointer type. However, the default behavior of ++ does not do what you want, which would be to follow the tail pointer.
To imbue your iterator with special knowledge of how ++ should be implemented, ... |
70,528,885 | 70,565,337 | How do I assign a value from a SQL query to a variable? QT | void Registration::introductionDate(QString email){
QSqlQuery *query = new QSqlQuery();
int dailyCalorieIntake = query->prepare("SELECT dailyCalorieIntake FROM [dbo].[User] WHERE email = :email");
query->bindValue(":email", email);
int dailyProteinIntake = query->prepare("SELECT dailyProteinIntake FROM ... | void Registration::introductionDate(QString email, Days *daysArg){
QSqlQuery *query = new QSqlQuery(daysArg->getDataBaseKnowFood());
query->prepare("SELECT dailyCalorieIntake FROM [dbo].[User] WHERE email = :email");
query->bindValue(":email", email);
if (!query->exec())
{
QMessageBox:... |
70,529,228 | 70,555,421 | Using a user-defined class as template type and using it's non-static data members for decision making. Is it possible? | I have class like this :
class B{
public:
const char* const getX() const {return X_;}
const char* const getY() const {return Y_;}
const char* const getZ() const {return Z_;}
protected:
B(const char* const x, const char* const y, const char* const z) :
X_(x), Y_(y), Z_(z) {}
pr... | The idea here was not to go with non-static type but rather I could achieve this by using CRTP.
#include <string>
class Types {};
template <typename T>
class BaseTempl : public Types {
public:
static std::string A;
static std::string B;
static std::string C;
static std::string D;
};
class Derive... |
70,529,499 | 70,530,947 | In-class initialization of vector with size | struct Uct
{
std::vector<int> vec{10};
};
The code above creates vector that contains single element with value 10. But I need to initialize the vector with size 10 instead. Just like this:
std::vector<int> vec(10);
How can I do this with in-class initialization?
| I think there are 2 aswers:
std::vector<int> vec = std::vector<int>(10);
as said in the comments and:
std::vector<int> vec{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
this is less preferable since it's less readable and harder to adjust later on, but I think it's faster (before c++17) because it doesn't invoke a move constructor ... |
70,530,736 | 70,530,841 | C++: How to override method of a specific class with same interface | I have a situation where I need to inherit from two classes with same interface, but to override them separately and I definitely cannot tweak interfaces. See code example below
template<typename T>
struct Foo
{
virtual ~Foo() = default;
virtual void foo() = 0;
};
struct Derived : public Foo<int>, public Foo<d... | You can always define intermediate classes that declare their own interfaces:
template<typename T>
struct Foo
{
virtual ~Foo() = default;
virtual void foo() = 0;
};
struct ProxyFooInt : public Foo<int>
{
virtual void fooInt() = 0;
void foo() override
{
return fooInt();
}
};
struct... |
70,531,120 | 70,531,706 | Generate truly random numbers with C++ (Windows 10 x64) | I am trying to create a password generator. I used the random library, and after reading the documentation, I found out that rand() depends on an algorithm and a seed (srand()) to generate the random number. I tried using the current time as a seed (srand(time(0))), but that is not truly random. Is there a way to gener... | It is true that PCs cannot generate truly random numbers without dedicated hardware, however remember that each PC has at least one hardware random generator attached to it - that device is you, the user sitting in front of the computer. Human is a very random thing. Each one has its own speed of key presses, mouse mov... |
70,531,728 | 70,532,033 | Transfer data from library to upper level and then back without naming it inbetween | I need to get some complex data from a library then use this data at the upper level. The data consists of 2 parts: while evaluating the data A, i get some additional data B, and the data B should be returned back in the library "as is" in order to not reevaluate it again.
So to simplify this: i get data A and data B f... | How about
using LibraryData = std::pair<A, std::any>;
// Get aata of type A and B, store B in std::any -> hiding it's type
// and return both values, but with B's type hidden
LibraryData GetDataAandB()
{
A someValue;
B someValueB_HiddenType;
return LibraryData(A, std::any(B));
}
// Work with the first part ... |
70,532,063 | 70,535,300 | Make right wall of a maze in c++ | I want to make a maze in C++, however I keep running into a problem with the right outer wall. I was wondering if you guys know a way so I can make the outer wall. Ive been trying to work from up to down using \n, but when \n is used the next symbol just goes to the left wall. Thanks in advance!
#include <iostream>
#in... | You may want to treat your printable maze as a matrix of chars instead of strings:
You can consider each cell of the maze border having a horizontal fill +--- and a vertical fill +|, and a cell_width and cell_height.
Your maze would be then defined as a matrix of chars sized maze_height * cell_height + 1 and maze_widt... |
70,532,083 | 70,532,313 | Generic overflow detection in C++ types | I want to have a generic method that can detect overflows in all types such as char, unsigned char, short, unsigned short, int32, unsigned int32, long, unsigned long, int64, unsigned int64 etc
On later C++ we can use __builtin_add_overflow_p to detect the overflow on addition. The macro can be like this
#define ADD_OVE... | __builtin_add_overflow_p does work with 8 and 16 bit types. The problem is that (__typeof__ ((a) + (b))) is int, and it doesn't overflow in int.
What you probably want is for a and b to be the same type and to check if the addition overflows in that type:
template<typename T>
constexpr bool add_overflow(T a, T b) {
... |
70,532,241 | 70,532,373 | how can i hold pointer object in array? | I'm a newbie. since my code is so long I can't edit it for being reproducible so I will show you what I did in a simple way
I have a Team class. I want to hold all my objects in an array so that I can reach them somewhere else and map for some data.
so I did a function basically doing this (exactly this part b[1] = a;)... | A better way would be to use std::vector to hold your class objects. The advantage of using a std::vector is that then you won't have to deal with memory management explicitly. vector will take care of it.
In addition, i will also recommend using smart pointers.
To solve your error above you can use the following examp... |
70,532,488 | 70,533,609 | What is the best way to return value from promise_type | I'm a bit stuck with coroutines in C++20. My attempt to create an asynchronous task:
template <typename T>
struct Task {
public:
struct promise_type {
using Handle = std::coroutine_handle<promise_type>;
promise_type() = default;
~promise_type() = default;
Task get_return_object() { return Task{Han... | I'm just learning coroutines myself, but I believe that the way to fix this is to change how the Task is destroyed.
At the moment, you have final_suspend return std::suspend_never. So control returns immediately to the caller (main) and the promise is destroyed. In that case, you have to do something like this:
I'm tr... |
70,532,514 | 70,532,802 | Undefined reference to a virtual function | booking.h
#ifndef _BOOKING_H_
#define _BOOKING_H_
#include <string>
class Event {
private:
std::string event_option;
public:
Event(std::string event_option);
virtual ~Event();
void list_specific_event_details();
virtual void list_details();
};
class Films : public Event {
private:
std::string m... | You have not defined your method Event::list_details(). If you only want to declare the function but do not want to implement it, that is what is called an Interface, you can make it a pure virtual method with:
class Event
{
...
virtual void list_details() = 0;
...
};
|
70,532,706 | 70,533,674 | Is there any difference in passing &arr(address of entire block) or just passing name of array (address of first element)? | void func1(int* ptr)
{
printf("func1 :%d\n",++ptr);
}
int main()
{
int arr[4] = {0,1,2,3};
printf("Addr enter code here`f arr: %d\n",arr);
func1(arr); // first way:
func1(&arr); // second way: How this will be different from func1(arr).
}
| The difference between &arr and arr is that the type of former is a pointer to an array int (*)[4], and the type of latter is an array int[4] which can decay to pointer to the first element int*. Both the pointer to the array, and the decayed pointer to the first element point to the same address because the first byte... |
70,532,839 | 70,533,181 | Discrepancy in result of Intrinsics vs Naive Vector reduction | I have been comparing the run times of Intrinsics vector reduction, naive vector reduction and vector reduction using openmp pragmas. However, I found the result to be different in these scenarios. The code is as follows - (intrinsics vector reduction taken from - Fastest way to do horizontal SSE vector sum (or other r... | Naïve loop adds by 1.0, and it stops adding at 16777216.000000, since there's not enough significant digits in binary32 float.
See this Q&A: Why does a float variable stop incrementing at 16777216 in C#?
When you add computed horizontal sum, it will add by 8.0, so the number since when it will stop adding is about 1677... |
70,532,961 | 70,533,006 | Comparison of two Character Arrays in C++ using Comparison Operator | How does the comparison operator work when doing a comparison between two character arrays?
Consider the following program,
#include <iostream>
using namespace std;
int main()
{
char arr1[5] = { 'T','e','s','t' };
char arr2[10] = { 't','e' };
if (arr1 < arr2)
cout << "Yes";
else if (arr1 > arr... | In the condition of the if statement
if (arr1 < arr2)
the both arrays are implicitly converted to pointers to their first elements and these addresses are compared that results in undefined behavior for the operator <.
Pay attention to if you will compare string literals like
if ( "Hello" == "Hello" )
//...
then the ... |
70,533,382 | 70,533,616 | Questions about CUDA macro __CUDA_ARCH__ | I have a simple cuda code in ttt.cu
#include <iostream>
__global__ void example(){
printf("__CUDA_ARCH__: %d \n", __CUDA_ARCH__);
}
int main(){
example<<<1,1>>>();
}
with CMakeLists.txt:
cmake_minimum_required(VERSION 3.18)
project(Hello)
find_package(CUDA REQUIRED)
cuda_add_executable(sss ttt.cu)
Then I got the ... | __CUDA_ARCH__ is a compiler macro.
can we use valid __CUDA_ARCH__ in host code
No, it is intended to be used in device code only:
The host code (the non-GPU code) must not depend on it.
You cannot print a compiler macro the way you are imagining. It is not an ordinary numerical variable defined in C++. You could ... |
70,533,459 | 70,533,890 | C++ n-arry tree with different elements | I want to build a n-arry tree from a document. For that i have 3 different types of elements for the tree:
Struct Nodes
Have a name
can contain other Nodes
Depth
Element Node (Leaf of the tree)
Have a Key
Have a value
Depth
Element Template Node (Leaf of the tree)
Have a placeholder which should be resolved lat... | This is a typical structure for implementing a tree with different kind of nodes. Another variant would be the composite pattern.
The problem that you describe, is usually caused by asking the nodes about what they know, instead of telling them what to do. If you'd do it the other way round (tell, don't ask), you cou... |
70,534,022 | 70,535,436 | SWIG Python C++ struct as in/out parameter | Honestly I read and re-read a lot of post on this site regarding to the struct theme. But I need your help.
I have C-style structures
struct Time
{
uint16_t year; // year with four digits like 2016
uint8_t month; // 1 .. 12
uint8_t day; // 1 .. 31
uint8_t hour; // 0 .. 23, 24 hou... | You can write a typemap to append the Time output argument. SWIG generates a proxy for the structure that can be generated as needed via SWIG_NewPointerObj(). Full example below:
DeviceInterface.h (minimal implementation)
#include <stdint.h>
struct Time
{
uint16_t year; // year with four digits like 2016
u... |
70,534,521 | 70,534,554 | getting None instead of a integer value | I am calling c++ code from python and I was wondering why I am not getting an integer value back from my function which returns an int. I keep getting None in python.
This is my c++ code:
#include <wiringPi.h>
#include <wiringPiI2C.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <unistd.h>
using nam... | Fix your Python returnDistance function to return the value:
def returnDistance(self):
return lib3.Ultrasonic_returnDistance(self.obj)
|
70,534,577 | 70,667,842 | Specify the cuda architecture by using cmake for cuda compilation | I have the following cmake and cuda code for generating a 750 cuda arch, however, this always results in a CUDA_ARCH = 300 (2080 ti with cuda 10.1). I tried both set_property and target_compile_options, which all failed. Do we have a solution for both cuda_add_executable and cuda_add_library in this case to make the -... | Change my comment to an answer:
project(Hello CUDA)
enable_language(CUDA)
set_property(TARGET oounne PROPERTY CUDA_ARCHITECTURES 75)
|
70,534,894 | 70,534,910 | vector as an argument for recursive function in c++ | I want to have function like one in the title, but when I declare it like this,
void function(vector<int> tab, int n)
{
if(n > 0)
{
tab.push_back(n);
function(tab, n - 1);
}
}
it isn't working, because tab is still blank.
| You're taking tab by value - each recursive call will operate on a new copy of tab.
You'll want to pass tab by reference:
void function(std::vector<int>& tab, int n) { ... }
|
70,535,405 | 70,535,555 | initialisation of atomic init | So in my code there is the snippet:
std::atomic<uint>* atomic_buffer = reinterpret_cast<std::atomic<uint>*>(data);
const size_t num_atomic_elements = svm_data_size / sizeof(std::atomic<uint>);
for (i = 0; i < num_atomic_elements; i++)
{
std::atomic_init(&atomic_buffer[i], std::atomic<uint>(0));
}
Howe... | In your code it appears that you're trying to create std::atomic<uint> objects out of "raw memory". If that's the case then you need to use placement new to begin the lifetime of such an object before using it. Also, &atomic_buffer[i] can be spelled atomic_buffer + i. So your code should be:
new (atomic_buffer + i) std... |
70,535,429 | 70,535,464 | Can a using declaration refer only to a specific overload based on const qualification? | If the base class has both const and non-const version of a function, can I refer to only one or the other in the derived class by the using keyword?
struct Base
{
protected:
int x = 1;
const int& getX() const {return x;}
int& getX() {return x;}
};
struct Derived : public Base
{
publ... | using always brings the entire overload set for the given name with it. You cannot invoke using for a particular function, only for its name, which includes all uses of that name.
You will have to write a derived-class version of the function, with your preferred signature, that calls the base class. The simplest way w... |
70,535,616 | 70,535,798 | What's the special value of `co_yield` in contrast to a simple stateful lambda in C++20? | From the well-known C++ coroutine library (search "Don't allow any use of co_await inside the generator coroutine." in the source file generator.hpp), and from my own experiments, I know that a coroutine using co_yield cannot use co_await meanwhile.
Since a generator using co_yield must be synchronous, then, what's the... | For trivial generators with minimal internal state and code, a small functor or lambda is fine. But as your generator code becomes more complex and requires more state, it becomes less fine. You have to stick more members in your functor type or your lambda specifier. You have bigger and bigger code inside of the funct... |
70,535,707 | 70,535,783 | C++ using template type with unordered map | I am new to C++ so this is likely a simple mistake but this code is giving me problems for hours now. I am really just not sure what to try next.
EratosthenesHashMap.h
#pragma once
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include "SieveOfEratosthenes.h"
template<class T>
class EratosthenesHashMa... | It is rather difficult to have a template class split between header file and .cpp file and be easy to consume by callers. Instead, inline your entire template class in EratosthenesHashMap.h:
template<class T>
class EratosthenesHashMap
{
public:
EratosthenesHashMap(SieveOfEratosthenes& sieve)
{
this->s... |
70,536,066 | 70,536,155 | c++ 2D vector(matrix) how to delete the nth row? | Here is the 2d vector [[1,3],[2,6],[8,10],[15,18]]
I want to delete the 2nd row which is [2,6]
I tried following to erase the 1st row
matrix[1].erase(intervals[1].begin(),intervals[1].end());
after erasing the row when I printed the matrix, I got
[[1,3],[],[8,10],[15,18]]
I wanted to remove the brackets also, how to d... | From what you showed, I believe the correct code would be
matrix.erase( matrix.begin()+1 );
|
70,536,235 | 70,536,365 | What is wrong with my C++ heap implementation? | I am trying to implement a heap structure for an online judge. I am very happy with the implementation, it stands all of my test cases, but the online judge rejects it.
The insert function appends the new element and then bubbles it up the binary tree. The removeMax function replaces the greatest element with the last ... | You are using the heap equations:
parent of node i is node i/2
children of node i are nodes 2*i and 2*i + 1
which only works if you use 1-based array indexing (index 1 is the first element of the array)
But C++ uses 0-based indexing for vectors (and arrays), so this doesn't work. You need
parent of node i is node (... |
70,536,337 | 70,549,910 | C++ FMT issue formatting a custom abstract class | I'm working on an events system for a personal project and I'm trying to make the events be logged to a console as easy as LOG(event).
In this case, events are defined by an Event class which has some methods and a virtual ToString() function that returns a string with the event info and whatever I like to output on ea... | The format string should be passed as fmt::format_string and not as a template parameter. Here's a working example (https://godbolt.org/z/xYehaMWsG):
#include <fmt/format.h>
struct Event {
virtual std::string ToString() const = 0;
};
struct MyEvent : Event {
std::string ToString() const override {
return "foo... |
70,536,361 | 70,536,599 | Why does my hashing program fail the tests | Task:
To register in the system, each resident must come up with a password. The password consists of letters of the Latin alphabet (uppercase and lowercase), as well as numbers from 0 to 9, that is, it is possible to use 62 characters in total. The password length is from 5 to 20 characters. The password is stored in ... | You have a few logic problems in your code. When you are rotating your upper and lower-case characters to their "encrypted" forms, you iterate through the password twice, and sometimes incorrectly rotate the characters. Take for example just the line
if (pas[i] + big >= 'A' && pas[i] + big <= 'Z') pas[i] = pas[i] + big... |
70,536,538 | 70,536,578 | How to correctly include classes in c++? | I would like some clarification about including classes in c++. I don't know the good way to do it because i don't know the differences between theme
#pragma once
#include "B.h" // Is it enough to include like this? ?
class B; // what this line does ?
class A : public B // what public B does here ?
{
// .......
... |
#include "B.h" // Is it enough to include like this? ?
Yes.
class B; // what this line does ?
This is an alternative to including B's header. Doing both is redundant.
It gives you less freedom. It allows you to create pointers and references to B, but not create instances of it, nor inherit from it, nor access i... |
70,536,642 | 70,537,196 | C++ executing a shellcode from caesar cipher does not work | In my code example, I hardcoded my shellcode, and execution works fine:
Delete pls
| Your Caesar-decoded shellcode does not match your hard-coded shellcode, that is why you are getting different outputs.
Let's look at the first character as an example, but this applies to the whole data as a whole:
Your Caesar-encoded string begins with the ASCII _ character, which has a hex value of 0x5F. When decrem... |
70,536,934 | 70,537,265 | unsorted array, find the next greater element for every element, else print -1 | the requirement is a little bit complicated
let's say we have an unsorted array, for example: {12, 72, 93, 0, 24, 56, 102}
if we have an odd position, we have to look for the next greater element in his right, let's say we take v[1] = 12, the nge for '12' is 24;
but if we have an even position, we have to look for the ... | For starters instead of the array it is much better to declare an object of the type std::vector<int>.
Pay attention to that indices in C++ start from 0.
In this if statement
if (v[j] > v[i]) {
next = v[j];
break;
}
you are exiting the loop as soon as the first e... |
70,537,094 | 70,537,095 | C++ vector stack overflow in constructor | I have the following code snippet:
#include <vector>
struct X {
std::vector<X> v;
X(std::vector<X> vec) : v{vec} {}
};
int main() {
X{{}};
}
Compiling and running this snippet locally results in a stack overflow originating from X's constructor. Inspection with gdb shows me that the constructor is someho... | The problem has to do with how C++ chooses which constructor to execute. Notice that X's constructor uses curly-brace syntax in the member initialization list, meaning that it's using list-initialization syntax. According to the C++ reference:
When an object of non-aggregate class type T is list-initialized, two-phase... |
70,537,165 | 70,541,517 | How to override preprocessor definition for a single unit when using precompiled headers? | Initial problem:
I have a bug caused by an old debug MSVCRT library.
It throws an exception in debug mode for std::string initialization:
std::string str{vecBuff.cbegin(), vecBuff.cend()};
The old debug runtime library detects that std::vector<char>::cend() points to an invalid address and causes an error about HEAP C... | Defining _ITERATOR_DEBUG_LEVEL to either 1 or 2 changes the representation of iterators. Instead of being lightweight wrappers for e.g. plain pointers into container data, iterators compiled with this option contain a pointer into the data and a pointer to a container proxy object, which contains more info about the co... |
70,537,282 | 70,537,384 | C++20 coroutines. When yield is called empty value is retrieved | I watched the Björn Fahller - Asynchronous I/O and coroutines for smooth data streaming - Meeting C++ online talk. Following up this presentation, I gave a try to execute a similar example myself. There is a bug in my code and when yield is called , the value that is printed is zero. Debugging the code , I detected th... | This is returning a copy of the promise:
auto get_promise()
{
std::cout << "get_promise " << &_coroutine.promise() << std::endl;
return _coroutine.promise();
}
So instead of calling into the promise for the task, you're calling into just some other, unrelated promise object.
Once you fix that, you'll find tha... |
70,537,311 | 70,538,158 | Friending a typedef-ed class (c++) | I am going through a bit of a crisis where I need to friend a template class that is typedefed, but I am getting loads of errors(too many to paste here). I have put the MRE here so you guys don't have to set up the files.
Here are the .h files for completeness-sake:
//Keyboard.h
#pragma once
namespace wm
{
namespac... |
to make the SomeServerFunc function in both keyboard and mouse classes private and make MessageHandler a friend of Keyboard and Mouse.
I add class declaration to mouse.h and keyboard.h,to make the compiler happy.Here is the code:
#pragma once
namespace wm
{
template < class Keyboard, class Mouse >
class _Mes... |
70,537,324 | 70,537,388 | Warnings vs optimization gcc | I wonder if the warnings reported by compiler such as variable unused or control reaches end of a non-void function can impact a program (i.e crash) when the optimization is enabled (O2 or O3)
Could you please give me some examples ?
| Warnings indicate likely mistakes in your code. However, whether or not the warning is there or whether or not optimizations are enabled doesn't affect whether the code is correct.
Warnings such as unused variable simply indicate that you probably meant to use the variable somewhere but forgot to do so. Otherwise there... |
70,537,383 | 70,537,600 | Is there a way to extract outer loops of multiple similar functions? | Example: I want to extract the nested for loops from these operator functions that are the same except the one line.
// Add two matrices
Matrix& operator+=(const Matrix& other)
{
for (int i = 0; i < this->m_rows; i++)
{
for (int j = 0; j < this->m_cols; j++)
{
(*this)(i, j) = (*this)... | You can write a function template that accepts a binary function and applies it on all pairs of elements inside the loops
template<typename Op>
void loops(const Matrix& other, Op op)
{
for (int i = 0; i < this->m_rows; i++)
{
for (int j = 0; j < this->m_cols; j++)
{
(*this)(i, j) = o... |
70,537,434 | 70,537,626 | C++ question regarding how ifstream reads lines and columns | I was reading some old codes of mine and I realize that I don`t know exactly how ifstream works. The following code should just read a file, save its contents into an object and create another file with exactly same data, which is written as:
#include <iostream>
#include <fstream>
using namespace std;
class grade {
... | In read_file() the reading occurs in this loop:
int i=0;
while(myfile >> data[i].grade1){
myfile >> data[i].grade2 >> data[i].grade3;
i=i+1; }
First, this assumes that data[] was already allocated with sufficient number of elements. It's strange since the file was not yet read, so how to know how many... |
70,537,605 | 70,537,641 | How do I stop a C++ program from calling a function body from the wrong source file, when it's defined in 2 places? | I've tried creating a static library with two copies of the same function, defined in two seperate header/source files.
These 2 source files should be mutually exclusive and not includable within the same file as each other.
I've recreated the issue with the example code below.
This was written and tested on VS2019, I ... | I'm surprised the linker didn't give you a warning about this. When it links together the final executable program, it's going to pick one of the foobar implementations and discard the other.
Pre-processor hack. foobar is defined as a macro or inline function that invokes a unique function name. Define foo.h and foo.c... |
70,538,029 | 70,538,192 | Boost 1.45 dataset workaround | I'm making an attempt at setting boost's unit test framework up for myself, but due to having to use C++98, I also have to use boost 1.45. Due to this, I find I can't make use of datasets the way I'd like (have test cases that have an arity of 2 and a dataset of pairs (input_val,expected_val)). It's looking like I'll b... | @ provided the info I needed. If anybody else is looking for a good unit testing framework for C++98, Catch seems great so far!
|
70,538,129 | 70,538,219 | C++ wininet fetching data in 513 byte chunks | I am trying to fetch my server html text data using wininet, but it seems to be reading it and breaking it into 513 byte size chunks. However I would prefer the data to be fetched as a whole. Is there a way I can go around this?
Here is a full code for references:
#include <windows.h>
#include <wininet.h>
#include <st... | dwFileSize = BUFSIZ;
If you look at your header files you will discover that BUFSIZ is #defined as 512.
buffer = new char[dwFileSize + 1];
// ...
Read = InternetReadFile(hHttpFile, buffer, dwFileSize + 1, &dwBytesRead);
Your program then proceeds to allocate a buffer of 513 bytes, and then read the input, 513 bytes... |
70,539,175 | 70,539,202 | Couldn't free allocated memory using delete | I'm allocating memory in a member function like below:
void Wrapper::PutData() {
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
}
where the mpeople object is declared as
QList<QObject*> m... | You're attempting to do scalar delete on an object that wasn't allocated with scalar new. That is delete, not delete [].
Just do this:
void Wrapper::RemoveClient(int index){
if(index >= 0){
delete mpeople[index];
mpeople.removeAt(index);
}
resetModel();
}
A more modern way, is to use share... |
70,539,361 | 70,539,396 | Can I cast a memory area with a class type? | class RW {
int a;
public:
int read() const {
return this->a;
}
void write(int _a) {
this->a = _a;
}
};
#define PHYSICAL_ADDRESS (0x60000000)
#define SIZEOF_PHY_ADDR (sizeof(RW))
// assume physical memory area is already assigned for the sizeof(RW)
void main()
{
int val;
vo... | You don't need to cast: you may just create the object at that address with placement new operator.
void main()
{
int val;
void *phy_ptr = PHYSICAL_ADDRESS;
//RW *rw_ptr = (RW *)phy_ptr;
RW *rw_ptr = new(phy_ptr) RW;
rw_ptr->write(1);
val = rw_ptr->read();
rw_ptr->~RW();
}
|
70,541,155 | 70,541,310 | How to assign char* variables dynamicly in C++? | I encounter a scenario to register arbitrary addresses as char* in a program.I need to pass each one as char* to the third party library for further action.
The third_party_function is describe as such in its header file:
virtual void RegisterFront(char *pszFrontAddress) = 0;
First, the program have to read from a con... | Let's say your config line is this:
std::string s = "tcp://18.19.20.22:7778; tcp://18.19.20.24:7778; tcp://18.19.20.25:7778;"
s can also be a char*, it doesn't matter. At some point in your code, you've got a string representation of that config line that you've read from file or wherever.
Then to loop through that s... |
70,541,449 | 70,541,685 | C++ Templates: expected constructor, destructor, or type conversion | I am trying to build a library with a templated class having a constraint on the value of the integer passed:
library.h
template<int N>
requires (N == 1)
class example {
public:
example();
};
library.cpp:
#include "library.h"
main.ccp:
#include "library.h"
int main() {
return 0;
}
However, when trying to... | As Charles Savoie already wrote in his comment, the requires keyword is new since C++ version 20.
Older compilers do not know that keyword; for such compilers requires is just an identifier like example or helloWorld.
You might try to replace requires by helloWorld to check if your compiler supports requires:
template<... |
70,541,494 | 70,541,798 | Postfix to Infix conversion in C++. "Process returned -1073740940 (0xC0000374) execution time : 5.538 s". No clue why | The question is to convert a postfix expression to an infix expression using stacks and without stack library.
Im getting a statement after i run it and enter my postfix expression saying : "Process returned -1073740940 (0xC0000374) execution time : 5.538 s"
The second i enter my postfix expression, the computer free... | For one, You have undefined behavior in your program. This is because you're going out of bounds when you wrote string op1 = s.topele(); at:
else{
string op1 = s.topele(); //this will call topele
//...
}
Now the member funciton topele is called and you have
string topelement = arr[top]; //this will result in(w... |
70,541,587 | 70,541,934 | Running until a certain value linked list | I want to sum the nodes until 0 is reached and update the original linked list with the new values.
Note: it skips 0 until it reaches a number to calc sum or the end of the linked list.
Definition of node:
struct Node {
int data;
Node* next;
};
void updateLinkedList(Node* head)
{
Node* currentNode = head;
int temp = ... | The function can be implemented for example the following way
void updateLinkedList( Node * &head )
{
for ( Node **current = &head; *current != nullptr; )
{
if ( ( *current )->data == 0 )
{
Node *tmp = *current;
*current = ( *current )->next;
delete tmp;
... |
70,541,687 | 70,646,402 | Linking local Openssl to Nodejs C++ addon | I am writing a C++ addon for Nodejs which uses OpenSSL 3 and I keep getting this error when trying to compile the code with the command node-gyp build:
/Users/myuser/Library/Caches/node-gyp/17.0.1/include/node/openssl/macros.h:155:4: error: "OPENSSL_API_COMPAT expresses an impossible API compatibility level"
I can see ... | This is a problem in Node.js: https://github.com/nodejs/node/issues/40575
And here is a workaround: https://github.com/mmomtchev/node-gdal-async/commit/85816cbeff104b5484aae840fe43661c16cb6032
Add those two defines to your gyp:
"OPENSSL_API_COMPAT=0x10100001L",
"OPENSSL_CONFIGURED_API=0x30000000L"
I am the author of b... |
70,541,910 | 70,542,161 | How to avoid a virtual function for a single derived class implementation? | I have a an Accessor class defining my interface to other classes and multiple base class objects within this Accessor class implementing stuff in various flavors.
class Accessor
{
std::shared_ptr<Base> object1;
std::shared_ptr<Base> object2;
}
The Accessor class implements of course more than just calls to th... | If you are sure that object_1 always points to a Derived1, then make it a std::shared_ptr<Derived1> object1. And if the sole purpose of Base::f() is for Derived1, make it non-virtual and remove it from the classes that don't need it.
But if one of those assumptions is not true, keep it as it is:
Making an extra test t... |
70,541,941 | 70,541,967 | How does my code get a value for my variable? C++ | I'm following this book called C++ Primer Fifth Edition and it had this code:
#include <iostream>
int main() {
int currVal = 0;
int val = 0;
if (std::cin >> val){
int cnt = 1;
while (std::cin >> val){
if (val == currVal){
++cnt;
}
... | No. The first time the if() statement is run, it checks against zero.
currVal will only be updated when the else is executed.
|
70,542,093 | 70,542,324 | using the current type in typedef in cpp | I need a data type which will hold either a string or a vector of the current data type. Here is a typedef I've written for that:
typedef std::variant<std::vector<value>, std::string> value;
Apparently this isn't valid, as value is an undeclared identifier when executing this line. So I tried first declaring value as ... | I think this is what you're asking for:
struct Type
{
using Value = std::variant<std::vector<Type>, std::string>;
Value v;
};
|
70,542,579 | 70,542,751 | C++ atomic is it safe to replace a mutex with an atomic<int>? | #include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
using namespace std;
const int FLAG1 = 1, FLAG2 = 2, FLAG3 = 3;
int res = 0;
atomic<int> flagger;
void func1()
{
for (int i=1; i<=1000000; i++) {
while (flagger.load(std::memory_order_relaxed) != FLAG1) {}
res++; // maybe a ... | std::memory_order_relaxed results in no guarantees on the ordering of memory operations except on the atomic itself.
All your res++; operations therefore are data races and your program has undefined behavior.
Example:
#include<atomic>
int x;
std::atomic<int> a{0};
void f() {
x = 1;
a.store(1, std::memory_ord... |
70,542,870 | 70,542,971 | How to store unordered_set to a vector? | I want to use a vector to store several unordered_set.
Here is my test codes:
#include <unordered_set>
#include <vector>
using namespace std;
int main(){
vector<unordered_set<int>> v1;
unordered_set<int> s1 = {1,2}, s2 = {3,2};
v1[0] = s1;
v1[1] = s2;
for (auto &s : v1[0]) {
cout << s << " ... | The problem with your code is that your vector does not have elements 0 and 1. Either initialize the vector with required number of elements, or insert the elements into an empty vector as below:
int main(){
vector<unordered_set<int>> v1;
unordered_set<int> s1 = {1,2}, s2 = {3,2};
v1.push_back(s... |
70,542,878 | 70,542,954 | Is it permissible to specialize mathematical constants for custom numeric types? | Suppose I create my own floating point type MyFloatingPoint (e.g. to provide increased precision relative to the built-in types). Is it permissible to specialize the constants in the C++20 <numbers> header for this type, or is this undefined behavior?
| According to C++20 draft it seems fine:
26.9.2
(...)
2. Pursuant to 16.5.4.2.1, a program may partially or explicitly specialize a mathematical constant variable
template provided that the specialization depends on a program-defined type
|
70,542,909 | 70,542,996 | SDL is sent me on a bad trip with FillRect | SDL_Rect r3;
r3.h = 10;
r3.w = 10;
r3.x = 10;
r3.y = 10;
SDL_Rect r4;
r3.h = 10;
r3.w = 10;
r3.x = 20;
r3.y = 20;
SDL_FillRect(surface, &r3, SDL_MapRGB(surface->format, 100, 0 ,100));
SDL_FillRect(surface, &r4, SDL_MapRGB(surface->format, 100, 100 ,0));
So the crazy th... | After declaring the SDL_rect r4, you set the coordinates for r3.
SDL_Rect r4;
r3.h = 10;
r3.w = 10;
r3.x = 200;
r3.y = 200;
This may result in uninitialized coordinate values for r4. This should work:
SDL_Rect r3;
r3.h = 10;
r3.w = 10;
r3.x = 10;
r3.y = 10;
//Set r4's coordinates instead of r3's
SDL_Rect r4;
r4.h = 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.