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 |
|---|---|---|---|---|
68,432,021 | 68,432,058 | Is this the right way to implement a return statement in a function? My function won't return a value | #include <iostream>
using namespace std;
int add(int x, int y) {
int sum = x + y;
return sum;
}
int main() {
int num1, num2;
cout << "enter" << endl;
cin >> num1 >> num2;
add(num1, num2);
return 0;
}
Add() function does not return sum when I run the code. However, when I replace return sum... | Your add function is returning the sum just fine. You just do nothing with it. Consider
#include <iostream>
using namespace std;
int add(int x, int y) {
int sum = x + y;
return sum;
}
int main() {
int num1, num2;
cout << "enter" << endl;
cin >> num1 >> num2;
cout << add(num1, num2) << endl;
return 0;
}
... |
68,433,089 | 68,433,112 | How to use std::format to create width and declare precision(in C++20)? | I am trying to create a table using #include < format > in the C++20. However I do not know how to create a centre alignment of 17 and precision of 2 decimal places at the same time. I know width of 17 centre alignment would be simply: cout<<format("{:^17}",numb[i]) but how to output at 2 decimal places?
This is my cod... | Try including the f specifier (for floating-point numbers): {:^17.2f}
|
68,433,745 | 68,433,780 | Arithmetic overflow using all 32-bit ints in C++? | This should simply be adding 1 to an unsigned int: prev = nums[nextIndex + 1]; but it gives a warning saying
Arithmetic overflow: Using operator '+' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '+' to avoid overflow
But I'm not using any 8 b... | Vector indexes (and std::vector::size()) are size_ts, not unsigned ints, and that's where your problems are coming from.
To fix this, declare all your unsigned int variables as size_t and get rid of all those casts:
void rotate(std::vector<int>& nums, size_t k) {
k %= nums.size();
if (k > 0) {
size_t of... |
68,433,851 | 68,433,947 | Cannot open source file "GL/glew.h" when using CMake find_package() | as stated in the title, I am trying to add glew.h to my project built with CMake on Visual Studio 2019 (Windows 10), and in doing so am experiencing an error thrown during the building stage fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or directory.
I am including it in engine.hpp as such #inc... | If you use vcpkg, you should just use vcpkg's CMake integration and let it handle details. Your CMakeLists.txt should not contain any absolute path, it's supposed to be a file you share with other people alongside your source.
That being said, the immediate issue at hand comes probably from this problem:
target_link_l... |
68,433,991 | 68,434,143 | Problem with very simple variadic function | I am trying to use a very simple log function using variadic templates in C++:
void log(){}
template <typename T, typename... Types>
void log(T first, Types... arg)
{
std::cout << first << " ";
log(arg...);
}
int main()
{
log(1,2);
log(3, "four");
log(5);
log(6,"seven",8,9,10,11,12);
log(1... | Mystery solved - when compiling with MSVC your choice of the name log is clashing with the log function in the standard library when there is only one numeric parameter. Since this doesn't print anything, output is missing.
Just use another name and it works.
|
68,434,128 | 68,434,176 | C++ use async with member function | I just study and try to use async function in class member function like example in
MS document.
using namespace std;
Class Worker
{
private:
vector<int> work_list;
public:
void WorkA(int A, vector<int> B)
void Work_MP()
}
void Worker::Work_MP()
{
vector<std::... | There are a number of typos in your code, but what I think you are trying to get at is that you have the wrong syntax for a pointer to a member function. It should be &class_name::function_name. Also, you need to pass this as before any other parameters to emplace_back, and the last parameter should be work_list, not... |
68,434,397 | 68,440,459 | How do I find out where the size of the final executable comes from in C++? | Let's say that I have a C++ program, which when compiled, produces an executable binary many megabytes in size. How do I find out where this size came from? Is there a tool that can show that X% of the size came from file or class Y, etc?
Ideally, I'm looking for a tool similar to Disk Usage Analyzer that can break dow... | You could take a look at Bloaty McBloatface, which claims to be designed to do exactly this:
Ever wondered what's making your binary big? Bloaty McBloatface will show you a size profile of the binary so you can understand what's taking up space inside.
Bloaty performs a deep analysis of the binary. Using custom ELF, D... |
68,434,501 | 68,434,618 | Why is covariance not allowed with an abstract class? | class GameObject {
public:
virtual ~GameObject() {}
};
class Player: public GameObject {};
struct IGameController {
virtual GameObject* GetPlayer() = 0;
};
class CameraOnlyController : public IGameController {
public:
GameObject* GetPlayer() override { return nullptr; }
};
class PlayerController : publi... | IGameController* playerController = new PlayerController();
playerController is of type IGameController*.
The C++ compiler type checking does not remember anything else about playerController. It forgets the fact it was constructed from a pointer to PlayerController.
Player* player = playerController->GetPlayer();
s... |
68,434,793 | 68,434,890 | Adding element in the end of linked list is not throwing output when I am setting head as NULL | Here is my c++ code which inserts an element in the NULL list and then adds an element in the end. But I am unable to find what went wrong with my code. Function insert works fine but when function end is called it returns an empty linked list.
#include <bits/stdc++.h>
using namespace std;
class Node
{
publi... | There is a small issue in your code as below in while loop.
while(ptr!=NULL){
ptr = ptr->next;
}
ptr->next = temp;
You are checking ptr!= NULL. That means while loop will exit when ptr is NULL and you are doing NULL->next = temp; which is wrong.
And one more issue.
You declared end function will return Node *... |
68,434,923 | 69,722,701 | How to capture keyboard & mouse events even when the Qt app is minimized / in background / out of focus? | Here the requirement is just to check if any key was pressed or any mouse click or movement has happened. Capturing other specific details is not required.
I am fine to do every 1 second polling as well to see if any mouse or key event happened.
Will QAbstractNativeEventFilter be of any help?
Any other platform indepen... | Have written minimal working code for the 3 platforms below. Using Qt is optional.
#include<iostream>
#include<thread>
#include<chrono>
struct Activity
{
Activity ();
};
// You may need to put Qt equivalent part here; The core logic is after main()
#include<QGuiApplication>
int
main (int argc, char *argv[])
{ // Q... |
68,434,969 | 68,437,259 | rabbitmq-c send nlohmann json | Want to send image through RabbitMQ-C but the image file too big. Receiver cannot retrieve the image. So, I converted image to base64 then put it in JSON.
const char *msg;
FILE *image1;
if (image1 = fopen(path, "rb")) {
fseek(image1, 0, SEEK_END); //used to move file pointer to a specific position
... | amqp_cstring_bytes expects a C string, which is normally terminated by a NUL byte. Your PNG file is almost guaranteed to contain a NUL byte, so that explains why your message got cut off midway through.
As for the code in your paste: the pointer returned by sa.c_str() is only valid while sa is alive and unmodified. Onc... |
68,435,070 | 68,435,612 | How to realize template class type in template function? | I want to design a print function for STL container, include: std::vector, std::map, std::unodered_map, std::set, std::unordered_set, std::list ....
The ideal function looks like:
template<typename T>
void Show(const T& t)
{
if (istype(t, std::vector))
{
// here is a presudo code
// print vec... |
But it seems it just can operate on int or float, cant be operated
on std::vector, can you help on this?
For template classes like stranded containers, you need to specify the template argument to get the concrete type and thereafter you can compare usingstd::is_same. That means something like std::is_same_v<T, std::... |
68,435,398 | 68,435,513 | i am trying to sort a vector of certain user defined data type but it is giving me syntax error c++ | While solving a certain ds algo question,I had to sort the array using a custom comparator.I don't know why is it showing me errors at that particular line
Code
#include"bits/stdc++.h"
using namespace std;
struct train{
int platform,arrive,depart;
};
bool compare(train x,train y)
{
return ... | There are several things wrong.
First, This line is really saying vector<train>* arr, Pointer to a vector. But you used vector so array and memory management is totally internal to it. And you are using sort which is in-place sorting algorithms means, it modifies the original array, so you have to pass it via reference... |
68,435,578 | 68,435,743 | How to remove from a list inside a for loop in c++ | Is there any way to remove a list item inside a for loop that loops through that list?
example:
std::list<int> myList;
myList.push_back(5);
myList.push_back(8);
std::list<int>::iterator i;
for (i = myList.begin(); i != myList.end(); i++)
{
if (i == 8)
// myList.remove(*i);
}
Is there any way to replace t... | First and foremost: if iterating over the whole list just to delete the desired items, just use list::remove without the loop. It will do the trick for you.
However when the loop is needed for this or other reason list::erase is the way to go, however it will require manual iterator adjustments:
See:
https://stackoverf... |
68,436,155 | 69,391,114 | SteamVR override Controller inputs? | I want to override my controller inputs. Like swapping controller button actions for example. My approach was creating a custom controller using OpenVR, but then I cannot retrieve my controller inputs and feed them to the controller I created.
I know that I can get controller inputs, just to read. But how do I override... | The hard way
Making your own wrapper driver, its not gonna be easy, openvr driver API is mostly undocumented(and barely functional on Linux...) and very confusing
It is possible though, if i understand your question correctly, you want to achieve something like the DecaMove(which can be used with a phone now if i under... |
68,436,407 | 68,436,474 | How to define multiple operators using macros | I'm going to use a single macro to set the ==, ! =, >, >=, etc. for an array in one macro.
#define COMPARE(operator, function) \
template <typename T> \
void function(T *compArrayA, T *compArrayB, bool *resArray, int size... | operator is a C++ keyword. Avoid using it to avoid compilation issues. Standard practice is to use full caps for all the macro arguments; e.g.
#define COMPARE(OPERATOR, FUNCTION) \ ...
Moreover, here the ## part is unwanted, since there is no string concatenation happening in your code. Simply use OPERATOR argument as... |
68,436,487 | 68,439,097 | Modify hash value on replacing a single character in string (c++) | I am using a polynomial hash function to calculate the hash value of a string (consisting of only lowercase english letters) as follows:
int SZ = 105, P = 31;
long long M = 1e12 + 9;
vector <long long> pw;
pw.resize(SZ, 1);
for(int i = 1; i < SZ; i++) {
pw[i] = (pw[i - 1] * P) % M;
}
long long calculateHash(string... | In principle your idea of changing the resulting value ist correct, but what you need is a modulo operator, which result is always positiv, also for negativ input numbers.
To emulate this behaviour with C++ modulo you could do the following:
long long tmp=(h1 + ((s2[idx] - s1[idx]) * pw[idx])) % M;
h1=(tmp+M)%M;
The f... |
68,436,804 | 68,436,915 | SFINAE using scope resolution operator in decltype | The question How does `void_t` work shows an example of SFINAE using void_t on a class data member T::member. However, it doesn't work if member is a function. Why is that the case ? It works if I change the code from decltype( T::member ) to decltype( T().member() ).
#include <iostream>
using namespace std;
template... | decltype( T::member ) doesn't work because T::member is not a valid expression expected by decltype when member refers to a non-static member function.
You can change it to decltype( &T::member ) instead. &T::member returns pointer to member, it works with both member functions and data members, static or non-static.
B... |
68,436,920 | 68,436,988 | Getting unexpected result when combining [[no_unique_address]] with empty base class inheritance | Consider following:
struct Base {};
struct Empty {};
struct X : Base {
int i;
[[no_unique_address]] Empty e;
};
static_assert(sizeof(X) == 4);
The X inherits the empty Base and gains EBO, and since its member e also uses [[no_unique_address]] attribute, this makes the size of X only the size of the int.
But whe... | Quoted directly from cppreference:
Empty base optimization is prohibited if one of the empty base classes
is also the type or the base of the type of the first non-static data
member, since the two base subobjects of the same type are required to
have different addresses within the object representation of the most
de... |
68,436,943 | 68,437,030 | How to define a templated method of a class template outside of class body | I would like to use a templated method within a class template. I mean an additional "templatification" of the method. The following code snippet should explain what I want to achieve:
#include <iostream>
using namespace std;
// a class with a template parameter
template <size_t SIZE>
class SomeClass {
public:
... | You need two templates: One for the class and one for the function.
Like in:
template<size_t SIZE>
template <typename T>
T SomeClass<SIZE>::someFunction(size_t position) {
return static_cast<T>(position * size); // just do something with type T
}
|
68,437,131 | 68,437,163 | C++ return different derived template class based on runtime argument | I have two template class Derived1 and Derived2 both derived from Base.
I wish foo can return Derived1 or Derived2 by template instantiation and their type is distinguished by argument use_int.
class Base {
public:
virtual ~Base() = default;
};
template <typename T>
class Derived1 : public Base {};
template <typen... | Derived1 and Derived2 are templates. If you want to use them as template arguments, you should declare Derived as template template parameter. E.g.
template <template <typename> typename Derived>
Base* foo(bool use_int) {
if (use_int)
return new Derived<int>();
else
return new Derived<float>();
}
|
68,437,598 | 68,441,520 | reusing std::unordered_map efficiently | I manage relatively small transient dictionaries in my program. My question: is it significantly more efficient to reuse them (with mymap.clear() after use), rather than to delete the old ones and create new ones?
Also, these dictionaries are currently implemented as std::unordered_map<std::string, int>. This works, bu... | For GCC at least, std::unordered_map<std::string, int>, at any point in time, has dynamic allocations as follows:
1 allocation for an array of buckets, which each hold iterators (likely implemented as pointers) into a singly linked list of nodes (generally between 1x and 2x your peak element count), or a sentinel iter... |
68,437,605 | 68,489,503 | How to use GMP with NS3? | When calling __gmpz_set_str() in a NS3, I got this error:
undefined reference to __gmpz_set_str collect2: error: ld returned 1 exit status
I am already including #include <gmpxx.h> and I have also installed libgmp3-dev and libgmp-dev.
Any idea?
this is the link to the waf: https://github.com/nsnam/ns-3-dev-git/blob/mas... | The compile flags need to be set at configure time, so the correct incantation is:
LDFLAGS=-lgmp ./waf configure
Now, you can simply run ./waf to build the entire codebase, and the -lgmp flag will be used. If you really want to use make(1), then
LDFLAGS=-lgmp make configure
should also work, but I recommend just usin... |
68,437,882 | 68,438,138 | Why does an object with static member instantiated in global namespace cause segfault? | I bumped into a segmentation fault issue, that I was able to reproduce with the below shared few code lines. Class A is instantiated before the main() in the global namespace, and class A also has a static member (myMap).
If A is instantiated inside the main, or definition of the static member is placed in main.cc, the... | The relative order of initialization of global data defined in different compilation units is unspecified.
Suppose the global data defined in main.cpp will be initialized before those from mymap.cc. In this case a will be constructed before A::myMap. However, the constructor A::A() of a wants to use myMap. This myM... |
68,437,886 | 68,438,061 | Where (in memory) does copy constructor copy the return value of function? | From what I've learned so far about C++, copy constructor is called in 3 situations
When object is passed by value
When a function returns an object.
When object is declared and initialized with another object of same type.
#include "Cube.h"
using uiuc::Cube;
Cube foo()
{
Cube c;
return c; //copy constructor... |
In the above code, copy constructor is invoked two times
If your type has a move constructor, it will be used instead of the copy constructor in this case.
In any case, here the move (or copy) constructor is called 0 or 1 times depending on compiler optimizations (could also be 2 times before C++17).
You start with 2... |
68,438,025 | 68,438,238 | lambda function doesn't matches argument list | I am training using lambda function and I create a small function that merge two lists using template class. I want to use lambda function in order to compare age and merge them into a new list that will be in ascending order.
Compiler tell that no instance of function template "merge_func" matches the argument list.
I... | Two issues.
The element type of the list is Student*, lambda should take Student* too.
You're passing lambda to merge_func which expects a function pointer. Template argument deduction doesn't consider implicit conversion (from lambda to function pointer) and fails deducing template parameter T on the 3rd function pa... |
68,438,073 | 68,438,363 | GUI app frozen while process and generate a file | I have a QT GUI application in c++ that aims to process and generates binary files.
The App works fine but it looks like it's frozen when it enters the while loop of processing and writing in the file.
I solve this by coping qApp->processEvents(); into the while loop. but the problem is that it takes much more time for... | First, create an object that encapsulates your work:
class Generator : public QObject {
Q_OBJECT
signals:
void progress(float);
void done();
slots:
void doWork() {
QVector<float> DataToFile;
for (unsigned long int k=0; k<DATASIZE ; k++){
/* Some process*/
DataToFile.push_back(Process_F... |
68,438,145 | 68,441,370 | execute a lambda function in different thread | Due to fixed requirements, I need to execute some code in a specific thread, and then return a result. The main-thread initiating that action should be blocked in the meantime.
void background_thread()
{
while(1)
{
request.lock();
g_lambda();
response.unlock();
request.unlock();
}
}
void mainthre... | Passing tasks to background thread could be accomplished by a producer-consumer queue. Simple C++11 implementation, that does not depend on 3rd party libraries would have std::condition_variable which is waited by the background thread and notified by main thead, std::queue of tasks, and std::mutex to guard these.
Gett... |
68,438,839 | 68,447,154 | Breadth-first search takes excessive time depending on veto insertion position | The problem being solved is LeetCode #752 "Open the Lock". A summary:
You have a combo lock with four one-digit wheels, starting at 0, 0, 0, 0. You want to determine the minimum number of movements required to change the lock to show a, b, c, d. In each movement, you can spin one wheel forward or backwards, e.g. the fi... | The slow version will allow duplicate states to be added to the queue. That they are duplicate is only detected when they are pulled from it, but then the "harm" has already been done. As there are many different paths to get to a same state, this will soon make the queue grow unnecessarily large, populated with lots o... |
68,439,081 | 68,439,434 | How to use a function defined using a macro | I have defined the macro as follows
#define COMPARE(OPERATOR, FUNCTION) \
template <typename T> \
void FUNCTION(T *compArrayA, T *compArrayB, bool *resArray, int size) { \
for (int idx = 0; idx <= size; ++idx ) {... | Short answer, don't do that. Since you've templates you can use standard library approach from functional header
std::less
std::greater
std::less_equal
std::greater_equal
without any macro definitions at all.
For example:
template<typename E, class Pred>
void vcompar... |
68,439,462 | 68,439,737 | unique_ptr as general purpose dispose object | Suppose I have a situation, where I have an SDK which provides certain interface, which implies some manual resources management or state changes. It is supposed to be used like this:
// SDK has state B by default
SDK->setStateA();
something();
requiring();
stateA();
SDK->setStateB();
Is it a good idea to incapsulate ... | Generally, it is best to design the interface of the code in such a way that it is easy to use and intuitive, or, put differently, that it's hard to use it wrongly. In particular, if the interface is able to prevent bugs by refusing compilation, it can save a lot of debugging time.
One possibility to achieve such an in... |
68,439,651 | 68,441,136 | Container for classes, with cv-qualifier and reference preserved? | I am relatively new to TMP in c++. I was wondering if there is a way to implement a container for classes(not its instances!) in c++(17, without boost or c++20, preferrably.)
Below is what I am looking for:
int integer = 0xDEADBEEF;
std::string hello ("hello");
boost::any c (integer);
const int c_deadbeef = integer;
in... | You can't distinguish integer and cr_deadbeef in a call site, so your desired syntax of decltype( makeClassContainer(integer, hello, c, c_deadbeef, cr_deadbeef) ) is a non-starter. You would have to apply decltype earlier.
Either directly
using my_type_1 = std::tuple<decltype(integer), decltype(hello), decltype(c), dec... |
68,440,215 | 68,440,582 | Can't open file to read data | I am using VS2019 and the following simple snippet of code doesn't work properly (it can't open a given file):
#include <iostream>
#include <fstream>
int main(int argc, char** argv)
{
std::ifstream inFile("Ids.txt");
try {
inFile.exceptions(inFile.failbit);
}
catch (const std::ios_base::failur... | When you run an executable from Visual Studio with CTRL+F5 or F5, then by default, the current working directory will be the location of the project file, not the executable file. This makes it easy to open files from where your source files are, which is practical during development.
You can also change the current wo... |
68,441,217 | 68,441,460 | c++ : std::visit not compilable under gcc | Here is my code which compiles fine for clang but failed with gcc
#include <iostream>
#include <string>
#include <regex>
#include <variant>
struct Id {
void SetValue(const std::string& item)
{
value = item;
}
std::string value;
};
struct Number {
void SetValue(const std::string& item)
... | As mentioned in the comments, this is a known bug in the current versions of GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90943
A simple workaround would be to force std::visit() to operate directly on the variant instead of the subclass by using a static_cast.
std::visit(LexerTokenExtractor{string_token}, static_... |
68,441,617 | 68,441,772 | "name followed by '::' must be a class or namespace name" error in release mode but not debug mode | C++, Visual Studio 2019
I keep getting this error in release mode but not debug mode for lines that use the "filesystem" and "chrono" libraries. I'm thinking that the issue probably relates to how the header files are linked in release mode.
Below are the relevant snippets of my code (ellipses indicate omitted code). T... | Fixed already! In project properties, I was changing the language standard to C++17 for Debug Mode but not Release Mode.
Screenshot:
.
|
68,441,684 | 68,785,681 | Compiling and Linking Cuda and Clang to support c++20 on Host Code | I am trying to compile, link and execute a simple Cuda example using Clang instead of Gcc. The general idea behind using Clang is to allow c++20 in Host Code and more compiler optimizations using the llvm/clang stack.
I looked at the following sources:
llvm docs
google paper about gpucc
This example is from the llvm do... |
The output indicates that it successfully compiles but fails to link:
axpy.cu:(.text+0xa0): multiple definition of `main';
This seems to have been sorted in the comments:
Maybe the only problem is that you pass axpy.cu twice in your compile command.
clang++-12 axpy.cu -o axpy --cuda-gpu-arch=sm_72 -L/usr/local/cud... |
68,441,713 | 68,442,243 | Is it possible to overload [] operator to do different thing in C++ | I want to overload "[]" witch is used to access array
But I also want to separate read/write to do different thing
For example :
class myclass{
private:
int val;
public:
myclass(){val=0;}
myclass(int _in){val=_in;}
....
//for A=myclass[n]
myclass& operator[](int index){
...
retur... | The chosen operator overload is affected solely by the type of the operands, and not how you use the returned value. There can only be one overload for one pair of operands.
However, you can use a return value that behaves one way when used as left hand operand of assignment, and another way when used as right hand ope... |
68,442,520 | 68,442,661 | Why does accessing members of class from outside gives accurate results while accessing it from member function does not work correctly? | The below code saves data in a file using the member function save() and reads data back using the static function load().
Loading data using load() function is successfull but using dump() function to print the result gives unexpected result, link for the image is provided for reference(https://i.stack.imgur.com/67qgH... | The load function returns a pointer to an object that no longer exists once load returns. it is an error to try to access that object after it no longer exists, but main does so.
Fix the error.
|
68,442,567 | 68,442,673 | Wrong output of MergeSort program in C++ | I'm trying to write a basic merge sort code which is giving the wrong output. My input array is {4,2,6,1,9,5,6,78,9,34,74,86,14,3,0} The output I'm getting is 0 1 2 3 4 5 6 9 9 14 74 32696 802952496 1 1 which is definitely wrong, But I can't find the wrong part of the code.
Sort Function take the array divides it in 2 ... | Here:
while(j<n2){
arr[it]=arr2[i];j++;it++;
}
Should be:
while(j<n2){
arr[it]=arr2[j];j++;it++;
}
What was wrong? You were accessing the index i instead of j.
Note: This kind of code:
int n1=mid-low+1,n2=high-mid;
int arr1[n1];
int arr2[n2];
for(int i=0;i<n1;i++)arr1[i]=arr[i+low];
for(int j=0;j<n2;j++)arr2[... |
68,442,615 | 68,447,821 | How to create a library without headers? | We have modules in C++20, can we completely remove #include in our code?
For example, we can write
import boost.asio;
...
Instead of
#include <boost/asio.hpp>
...
In the past we need these steps to install a library:
Compile all sources (.cpp) into objects (.o).
Package them into a library (.a or .so).
Install the ... | Modules are not meant to be a binary distribution mechanism; you should expect to supply module interface files (i.e., the same files compiled to object files in your library,
which are not header files) in a very header-like fashion and leave the CMI generation and caching to the client’s compiler and build tree (resp... |
68,442,696 | 68,451,055 | Parse Individual Curves from General_polygon_set_2 in CGAL | To start, I want to thank everyone who has helped me so far on previous problems I have had with working through the CGAL Library, it is greatly appreciated.
Background on myself: I am still very new with C++ and my coding experience is in MATLAB so there is a lot of concepts that I am learning very quickly and are the... | The doc here states that the value_type of a Hole_const_iterator is a General_polygon_2, which means that what you can iterate through all "curves" using "holes_begin()" and "holes-end", like you thought. To do that, use the following syntax:
for(auto h_it = mink.holes_begin(); h_it != mink.holes_end(); ++h_it)
{
//in ... |
68,442,698 | 68,443,626 | What are two variants of global `operator delete` in C++? | Sorry if I ask something trivial about C++, but I have not found an appropriate answer.
It looks like there are at least two versions of ::operator delete in C++, and in particular Clang and GCC use distinct versions, as can be demonstrated here:
#include <iostream>
#include <memory>
void operator delete(void *) noexc... | The standard library implementation of sized delete calls the unsized version.
Note that gcc -Wextra generates a warning if you override one and not the other.
The sized deletes:
Called instead of (1-2) if a user-defined replacement is provided, except that it's unspecified whether (1-2) or (5-6) is called when deleti... |
68,443,125 | 68,444,842 | Deletion of node from linked list | I am trying to code for deletion of a node with k as data of linked list. The below program is running fine, but it is not giving desired output if we have to delete the head node. For example, if the linked list is 98->6->1 and I have to delete 98, then the output which the program is showing is 0->6->1. Except for th... | The mistake in your code is that the head you are passing to deleteNode function is by value so the changes made to the head function is not displayed. The head in your function is not the same head in your main function it is just the copy of that head, so to apply the same change being applied to the head in deleteno... |
68,443,357 | 68,444,667 | not able to reverse operation. The error that says it cannot convert void to string but my result is saved as string. Have shown the code to refer | string result;
for(int i=st.size()-1;i>=0;i--){
result+=st.top();
cout<<st.top()<<endl;
st.pop();}
result+='\0';
return reverse(result.begin(), result.end());
st is a stack of character. I want to output stack elements in reverse order
| The return value of std::reverse() is void, so you can't return it (except from a function that itself returns void).
std:reverse() modifies the contents of the input range inline, so just return the std::string variable whose characters you are asking std::reverse() to modify, eg:
string result;
while (!st.empty()){
... |
68,444,104 | 68,447,286 | x86 memory ordering test shows reordering where Intel's manual says there shouldn't be? | According to intel's manual. Neither Loads Nor Stores Are Reordered with Like Operations
According to 8.2.3.2 Neither Loads Nor Stores Are Reordered with Like Operations
at document https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-3a-part-1-manual.html
e... | Take a closer look at what Section 8.2.3.2 of the intel manual. In your example your are effectively doing:
Processor 1
Processor 2
mov [ _x], 1
mov r2, _x
mov [ _y], 1
mov r1, _y
Instead of what the intel manual says:
Processor 1
Processor 2
mov [ _x], 1
mov r1, _y
mov [ _y], 1
mov r2, _x
I... |
68,444,429 | 68,448,721 | How can I distinguish between high- and low-performance cores/threads in C++? | When talking about multi-threading, it often seems like threads are treated as equal - just the same as the main thread, but running next to it.
On some new processors, however, such as the Apple "M" series and the upcoming Intel Alder Lake series not all threads are equally as performant as these chips feature separat... |
How to distinguish between high- and low-performance cores/threads in C++?
Please understand that "thread" is an abstraction of the hardware's capabilities and that something beyond your control (the OS, the kernel's scheduler) is responsible for creating and managing this abstraction. "Importance" and performance hi... |
68,444,552 | 68,448,835 | Getting whole array printed instead of subsets | I have used i&(1<<j)!=0 so that i get 1 or 0 in if condition specifying true or false but I am getting whole array printed instead of subsets. Though I get the correct result(subsets for given array) on using i&(1<<j).
void subsets(int arr[], int n)
{
for(int i=0;i<(1<<n);i++){
for(int j=0; j<n; j++)
... | Your code failed to compile when building with clang++ and -Werror flag, we will get this error:
operator_precendence.cpp:8:13: error: & has lower precedence than !=; != will be evaluated first [-Werror,-Wparentheses]
if (i & (1 << j) != 0) {
^~~~~~~~~~~~~~~
operator_precendence.cpp:8:13: note: place ... |
68,444,595 | 68,444,650 | C++ freeing heap-allocated variables in functions | Here's part of a function:
std::queue<std::string>* shunting_yard(std::vector<std::string> input){
std::queue<std::string>* output = new std::queue<std::string>();
...
return output;
I've dynamically allocated queue output is pointing to on the heap. However, when I try to free/delete the queue in int main... | You do not delete variables, or pointers. You delete things you allocate with new. The line:
std::queue<std::string>* output = new std::queue<std::string>();
does not allocate a variable called output with new. It allocates a queue, which has no name, and creates a local variable called output, and stores the address ... |
68,444,619 | 68,445,070 | Chrono, c++, comparing dates | I have Problem with comparing dates from chrono library.
For example, something should happen when the date_to_do_something is matched with the current date.
#include <iostream>
#include <chrono>
#include <typeinfo>
using namespace std;
int main(){
end = chrono::system_clock::now();
string date_to_do_something ="Tu... | First of all, pc and pl types are types char* and long*. If you want to print the full type name using typeid pipe your output to c++filt, something like ./prog | c++filt --types.
To compare these two dates, you should convert std::string to time_t. For that use tm structure. To convert string to time use strptime() fu... |
68,444,720 | 68,444,834 | Can I select a case label in a switch statement and then shows it on the screen in C++? | everyone! I think it could be a silly question, but I was wondering if it is possible to show a case label in a switch statement in C++. This is the statement:
switch(TYPE)
{
case 'A':
(cost <= 30000);
break;
case 'B':
(30000 < cost <= 60000);
break;
case 'C':
(cost > 60000);
... | It sounds like your logic might be a bit backwards. switch is used to check against the value of a variable that has already been set. Additionally, it can only check a single value per case; it cannot check a range.
If I interpret your question correctly, I think you want something like this:
if (cost <= 30000) {
... |
68,444,819 | 68,445,781 | Remove template type from templated class | I have this structure:
template <typename T>
using AllSettings = std::variant<
A<T>,
B<T>,
C<T>,
D<T>
>;
template typename<T>
void Foo() {
using SettingClassT = std::variant_alternative_t<0, AllSettings<T>>;
//....
}
is it possible to obtain base class without <T> from the SettingClassT?
Some... | Not sure about what do you exactly want but... seems to me that you're looking for a template struct as getTemplatePar
template <typename>
struct getTemplatePar;
template <template <typename> class C, typename T>
struct getTemplatePar<C<T>>
{
template <typename U>
using baseType = C<U>;
};
so you can write F... |
68,445,073 | 68,447,691 | How to skip/disregard files with names that use wide characters using std::filesystem? | I am iterating through a large set of nested directories searching for files of some extension, say ".foo" using code like the following:
namespace fs = std::filesystem;
int main(int argc, char* argv[])
{
std::ios_base::sync_with_stdio(false);
for (const auto& entry : fs::recursive_directory_iterator("<some di... | Unicode characters have values > 0x7f, so you could do something like this:
bool is_wide = false;
for (auto ch : entry.path().wstring())
{
if (ch > 0x7f)
{
is_wide = true;
break;
}
}
if (!is_wide)
std::cout << entry.path().string() << std::endl;
|
68,445,163 | 68,470,850 | TYPE_ALIGNMENT(LARGE_INTEGER) incorrect when building against Win10 SDK | I am running into issues with this assertion in the Win 10 SDK for Winnt.h, when upgrading from Win8.1 a C file which #includes winnt.h:
C:\Program Files (x86)\Windows
Kits\10\Include\10.0.18362.0\um\winnt.h(2487,1): error C2118: negative
subscript
#if defined(__cplusplus) && (_MSC_VER >= 1600)
static_assert(__aligno... | The section of Winnt.h posted in the question from Win 10 SDK is missing from the Win8.1 SDK, which implies the issue was always there but unreported.
Microsoft provide a way to disable this check, using the WINDOWS_IGNORE_PACKING_MISMATCH preprocessor definition.
For those interested, I verified in the library that it... |
68,445,448 | 68,445,614 | Error: Abort signal from abort(3) (SIGABRT) when using recursion | Problem Statement:
To construct a binary tree from a given inorder and preorder list.
I was able to write the logic but I get the error Abort signal from abort(3) (SIGABRT) and I ain't able to find what's causing this error.
Code:
#include <iostream>
#include <vector>
#include<algorithm>
#include <map>
#include <cmath>... | You increment pidx in construct_bin, but you don't do anything with that incremented value. As a result, you call construct_bin an infinite number of times and your code eventually runs out of memory or overflows the stack.
|
68,445,485 | 68,445,611 | How do I transform all elements of a varadic std::tuple using numerical indices? | Currently, I have an implementation like this in order to transform all values of a tuple using a function bar() that takes in each element of the tuple.
template<typename ... Args>
void foo(const std::tuple<Args...>& a)
{
std::tuple<Args...> transformedTuple = std::make_tuple(bar(std::get<Args>(a))...);
}
The pro... | You can use a helper function that takes a std::integer_sequence to do this. Add a helper function that takes an integer_sequence like
template<typename Tuple, std::size_t... I>
auto foo_helper(const Tuple& a, std::integer_sequence<std::size_t, I...>)
{
return std::make_tuple(bar(std::get<I>(a))...);
}
And then ... |
68,446,026 | 68,449,406 | gdb not loading pretty printers in thread? | I am currently trying to setup a VSCode project (the Godot sources for anyone interested), with compilation and debugging, however I can't get the pretty printers of GDB (version 8.1.1) to work.
In a regular application (a simple helloworld.cpp), if I compile, and debug, then get the pretty printer info, I get the foo... |
However, in my other project, when I launch the debugger and try to get info on the pretty printers, I get the following:
This is most likely happening because your other project did not link libstdc++.so.6 -- possibly because you used -static-libstdc++.
To ensure that gdb uses the pretty printer, I have created
Yo... |
68,446,478 | 68,447,057 | Thread Local Storage: How to combine values? | I have a parallel_for loop:
tbb::parallel_for(tbb::blocked_range<int>(0, numVerts, 1 /* Grain Size */),
[&](tbb::blocked_range<int> r) {
thread_local vector<int> V;
for (int i = r.begin(); i < r.end(); ++i) {
... (some work changing values in... | By definition, thread-local storage is local to each thread. Like any other local variable, the only way to access it across threads is to pass around pointers.
But you don't need to do that in this case (you don't need the thread_local, either). You know how many vectors you need, so you should just allocate an array ... |
68,446,567 | 68,447,662 | How can I convert the last column in svd.MatrixV() to 3 by 3 matrix? | I have obtained the 9th column in V matrix of singular value decomposition using:
svd.matrixV().array().col(8)
The column consists of 9 elements.
3.6 -0.0148 -1.922 -4.177 0.0135 -0.00389 -2.29 -0.98 0.21
Is there away in Eigen that can convert the 9 element column of svd.MatrixV() to 3 by 3 matrix ?
| You can do so using an Eigen::Map as follows:
Eigen::Map<Eigen::MatrixXf> col_map {svd.matrixV().array().col(8).data(), 3, 3};
This map can then be assigned to a new matrix
Eigen::MatrixXf col_mat {col_map};
|
68,446,673 | 68,447,243 | How to use boost asio steady timer expiry to get the execute timepoint | I want to get the time point when the boost asio steady timer fires.
The documentation says "expiry Get the timer's expiry time as an absolute time".
I do not understand what is the absolute time. I do not understand the result off expiry. Demo: (on wandbox)
#include <boost/asio.hpp>
#include <chrono>
#include <iostrea... | The problem is that you are comparing apples to oranges. system_clock and steady_clock do not share the same epoch. In other words, they represent time from different reference points.
The fact that you had to go through time_since_epoch() in order to compare them is a big indicator that you really shouldn't be compari... |
68,446,675 | 68,446,736 | Can Race Condition Happen In Semaphore? | Note: My question is still un-answered as the only answer has critical logic flaws and wrong assumptions.
Given the following code (From my digital text book):
Why there is no race condition?
For example in:
sem_wait(&barber_ready) and sem_post(&barber_ready) as we could end updating barber_ready at the same time once... | From the man page on sem_wait:
sem_wait() decrements (locks) the semaphore pointed to by sem.
If the semaphore's value is greater than zero, then the decrement
proceeds, and the function returns, immediately. If the
semaphore currently has the value zero, then the call blocks
until either it becomes possible to perfo... |
68,447,687 | 68,447,917 | Can't construct a wstring from a wchar_t | I have a struct called LOGFONT that I use from Windows headers
typedef struct tagLOGFONTW
{ LONG lfHeight;
LONG lfWidth;
LONG lfEscapement;
LONG lfOrientation;
LONG lfWeight;
BYTE lfItalic;
BYTE lfUnderline;
BYTE ... | I was able to fix this by adding the following to my CMakeFile,
target_compile_definitions(TargetName PRIVATE -DUNICODE -D_UNICODE)
|
68,447,983 | 68,448,371 | Optimizing a distance within angle check for game | I am trying to ensure this is function is as fast as possible.
CItem *find_closest_item_within_angle(
std::vector<CItem *> const &items,
CItem const *pThisItem,
float const angleDegrees)
{
float minDist = FLT_MAX;
CItem *pClosest = nullptr;
std::vector<CItem *>::iterator it = items.begin();
... | acos(dot) is a relatively heavy calculation which can be removed by comparing the cosines of the angles. cos(DEGREES_TO_RADIANS * angleDegrees) is also relatively heavy, but it would only be computed once, instead of for every item. Generally as rule of thumb, you shouldn't be doing trigonometry, try to stay within lin... |
68,448,271 | 68,448,408 | List initialization for array<array<int, M>, N> | When initializing a 2D array we can do
int data[2][2] = {{1, 2}, {3, 4}}; // OK
we can also use
int data[2][2] = {1, 2, 3, 4}; // OK
which makes sense since a 2D array still is a continues chunk of memory.
When using the array class instead of the base type, this works
array<array<int, 2>, 2> data = {1, 2, 3, 4}; // ... | std::array doesn't have any user-defined constructor (like std::vector), it just contains a underlying array, when performing aggregate initialization you need one more braces for it.
array<array<int, 2>, 2> data = {{{{1, 2}}, {{3, 4}}}};
// ^ ^ <- for array<array<int, 2>... |
68,448,837 | 68,524,598 | All of a sudden, my Qt application displays at 100% instead of the normal 200%, what did I changed that made it lose that feature? | In my settings, I clearly have my screen setup to 200% like so:
When I worked on my Qt application earlier, it would properly follow that setup.
Somehow, I changed a something and now it always appears at 100%. That makes it difficult to read the text.
What option(s) would Qt have that would turn that feature off?
I h... | Okay! I got the answer to that one in my situation.
Whenever nvidia sends a new version of their driver, my X11 session continues to work, but OpenGL is not accessible anymore. There must be something in Qt that decides to use OpenGL and since it (silently) fails opening a connection, it falls back to "no DPI scaling c... |
68,449,170 | 68,449,339 | make: *** No rule to make target `obj/main.o'. Stop | I'm working on an SDL project for which I'm using a makefile to build it. I'm Doing this on windows with a MinGW w64 compiler and make.
My project structure looks something like this
proj
------>bin #stores the executable
------>include #stroes the external library include files
------>lib #stores the ... | You have a trailing space on this line:
SDIR = ./src
Remove it, and the prerequisite will be correct, and the makefile will work.
|
68,449,351 | 68,455,326 | static_assert whether pointer adjustment is required for an upcast | I'd like to perform a compile-time check for whether an upcast from a derived type to a base type requires a pointer adjustment. I'm seeing nothing I could use from type_traits. Can this be done?
Here's an example of how this might be done at runtime. Note that clang even warns that the first printf would never print "... | This is called pointer interconvertibility. There is a trait std::is_pointer_interconvertible_base_of which unfortunately isn't implemented yet in gcc and clang. See also the paper and issue. Pointer interconvertible types have the same address and their pointers can be casted between with reinterpret_cast.
#include <t... |
68,449,630 | 68,462,138 | About c++ input behavior | #include <iostream>
using namespace std;
const int ArrSize = 400;
int main()
{
char arr1[ArrSize];
char arr2[ArrSize];
char arr3[ArrSize];
cout << "enter the first string ";
cin >> arr1;
cout << "enter the second string ";
cin.get(arr2, ArrSize);
cout << "enter the thrid string ";
cin>>arr... | Let's start by adjusting the program to check for errors.
#include <iostream>
using namespace std;
const int ArrSize = 400;
int main()
{
char arr1[ArrSize];
char arr2[ArrSize];
char arr3[ArrSize];
cout << "enter the first string ";
if (!(cin >> arr1))
{
cout << "Failed cin >> arr1\n";
}
... |
68,449,931 | 68,479,192 | Control path to pinned application to taskbar with Qt | How control path to pinned application to taskbar with Qt
| Since I myself have been searching with a lot of effort for a way to customize the program path to an application pinned to the taskbar, I wanted to post here my solution related to Qt.
Problem was, that I link the starter in a set of programs (starter/updater, main) when pinning the main program.
EventFilterPinnable.h... |
68,450,016 | 68,450,128 | Erase remove idiom on a std::string with non-printable characters throws exception | I am reading some text from another process through a pipe. The pipe returns the data to the variable chBuf but contains lots of non-printable chars. I tried to remove these non-printable characters using erase and remove but throws an exception. The program works without this erase remove line. What may I doing wrong?... | If the data in your file may contain nulls (amidst other characters that you're interested in), or it is not guaranteed to have a null at the very end, then you need to tell std::string how much data it should use to build the string. You do this with the std::string( const char *, size_t ) constructor:
std::string s... |
68,450,054 | 68,450,722 | Can't do async run member function in other class | I try to async to member function in other class but can't.
this is overview in my code
#include <iostream>
#include <thread>
#include <future>
#include <vector>
using namespace std;
class Work
{
public:
void doWork(int A);
};
void Work::doWork(int A)
{
cout<<"I got "<<A<<endl;
}
class Worker
{
priva... | I tried to fix your code and came up with a version that is working. You have a lot of unecessary cluttering in there. Also your code will leak the workset pointer. As pointed out in the comments the main mistake was the &workset which created a "ref to pointer" where all you need was the pointer itself. You should avo... |
68,450,061 | 68,450,101 | How to avoid error of narrowing conversion in c++11 | I have the below code which uses enum value to initialize the vector of the struct.
I was getting the error regarding narrow conversion. I have referred the Microsoft doc : link
by which I can solve the issue by below code.
#include <iostream>
#include <vector>
#include <string>
enum NUMBERS
{
NUMBERS_ZERO = 0... | You can define a type to use for the enumeration which will make the casts not needed:
enum NUMBERS : uint32_t
{
NUMBERS_ZERO = 0xA0000000,
NUMBERS_ONE = 0xA0000001,
NUMBERS_TWO = 0xA0000002,
NUMBERS_THREE = 0xA0000003,
};
Without the type definition the numbers can be assumed to be signed... |
68,450,810 | 68,451,621 | What operations with temporary object can prevent its lifetime prolongation? | As you know in C++, if a temporary object is bound to a local reference, then the lifetime of the temporary is extended till the end of the scope.
But what happens if one performs a cast with a temporary or some other operation, e.g.:
#include <iostream>
struct S
{
virtual ~S() { std::cout << "~S() "; }
};
struct... | I think Clang is correct.
The lifetime of the temporary in the 1st case should be extended.
a const_cast, static_cast, dynamic_cast, or reinterpret_cast conversion without a user-defined conversion that converts one of these expressions to the glvalue refers to the object designated by the operand, or to its complete... |
68,450,957 | 68,451,147 | Why do we need to define static variables of a class, but we don't define static variables when they are inside functions? | Code 1:
#include<iostream>
class Singleton
{
private:
static Singleton instance; //declaration of static variable
public:
static Singleton &GetInstance()
{
return instance;
}
void Hello()
{
std::cout << "Hello!";
}
};
Singleton Singleton::instance; //definition of static v... | The static member variable instance declared inside class Singleton in Code 1 is a class variable.
This means that regardless of the state of different instances of class Singleton, the state of static variable will remain the same for all objects/instances of that particular class. Hence, it needs to be defined outsid... |
68,451,908 | 68,452,084 | Accessing Nested Class Member Function in CPP | In case of nested class, how do I access the "Inner" or "Child" class's member function?.
For example, the code, where I created "obj1". Now how do I access the "childPrint()" with"obj1"?
example_code:
#include<iostream>
using namespace std;
/////////////////////////////////////////////////
class Parent
{
public:
... | obj1.Child::childPrint();
In this particular line, you need to understand that childPrint() is an instance member function of class Child. So, only an instance of class Child can call childPrint() function.
If childPrint() function is a static member function(class function) of class Child then it is possible to call i... |
68,452,049 | 68,452,081 | Copying from vector of derived class to vector of base class | I am looking for the simplest way to copy a vector of a derived class to a vector of a base class without doing it element by element. How can I fix the following to get this to work?
#include <vector>
#include <iostream>
struct A {
A( int a) : a(a) {}
int a;
};
struct B : public A {
B (int a, int b) : A ... | std::vector<A> can't be converted from std::vector<B> directly, they're two independent types substantially.
You can initialize va with the iterators of vb.
std::vector<A> va { vb.begin(), vb.end() };
Note that the elements of va would be slice-copied.
|
68,452,443 | 68,452,863 | Does std::reverse_iterator work with adapted ranges? | I remember having read that the motivation for [forward.iterators]/6 (requiring that, given two iterators a and b, a == b if and only if *a and *b are bound to the same object) was to support reverse_iterators. Am I remembering correctly?
cppreference.com notes that
For a reverse iterator r constructed from an iterato... | The note about stashing iterators is not about l-value vs r-value return from *, but instead about the multi-pass guarantee.
std::forward_iterator still has the semantic requirement "((void)[](auto x){ ++x; }(i), *i) is equivalent to *i", which is met by decltype(v.begin()), but is not (required to be) met by std::file... |
68,452,483 | 68,459,049 | Can the optimizer elide assignment from 64bit to 32bit integer types? | Given this:
uint64_t truncate(uint64_t num) {
uint32_t lessBits = static_cast<uint32_t>(num);
return static_cast<uint64_t>(lessBits);
}
Is the compiler allowed to optimize the static cast and keep the full 64 bit value or does it have to preserve the 32bit "truncation"?
Doing a quick godbold check, it would ap... | Because of the principle that optimizations must never affect defined program behavior, and the corollary that in order to allow an optimization, the Standard must characterize as Undefined Behavior all actions whose behavior it might affect, there are no defined cases where the Standard would allow implementations to ... |
68,452,625 | 68,452,721 | Class with a deleted copy constructor can be still copied? | I have a simple function:
void foo(atomic<int> a) { }
It occurs that I can call foo() in this way:
foo({ });
but I can't do it in a such way:
foo(atomic<int>{ }); due to an error message copy constructor is a deleted function. I have compiled with C++14.
What constructor is called in the first way: create constructor ... | In foo({ });, the parameter is copy list-initialized. As the result it's initialized by the default constructor of std::atomic.
In foo(atomic<int>{ });, the parameter is copy-initialized from the temporary std::atomic (i.e. atomic<int>{ }). Before C++17 even the copy/move operation might be elided the copy/move constru... |
68,452,829 | 68,452,959 | Can anybody explain me why this output shows Destructor message 6 times? | Output of the Program
#include <iostream>
using namespace std;
class Complex {
private:
int real;
int imag;
public:
Complex(int real, int imag);
Complex(Complex& c);
int getreal();
int getimag();
void setreal(int real);
void setimag(int imag);
Complex operator+(Complex c);
~Com... | Three destructors are executed for the three objects created in main(): c1, c2 and c3. Two other objects are created in operator+: c and temp.
Sixth object is created if the compiler does not use return value optimization. In this case temp is copied while returning it from operator+.
|
68,452,831 | 68,452,964 | What is the standard c++ library? | I've had this question on my C++ quiz.
To use c++ standard library we write ...
#include <iostream>
using namespace std;
import std;
None of the above
I've answered it #include <iostream>. Because indeed <iostream> is a standard C++ library. When I asked the professor about the correct answer he said the correct an... | the correct answer is 4, "To use c++ standard library" doesn't really make any sense, you can use individual classes and functions from the standard library not the whole standard library.
This includes one header from the standard library allowing use of std::cin etc.
see Why is "using namespace std;" considered bad ... |
68,453,311 | 68,453,388 | How to correctly implement a linked list class in C++ | I'm trying to implement a simple list in C++ but I'm stuck with writing the add function
When adding one element it works fine but then it just keeps adding the element indefinitely
This is weird because I'm making sure to only add to the tail of the linked list and the last element is always NULL.
The result is correc... | The variable
List next (value);
is automatic, so it exists from the line of its declaration till the end of the add() function. Once the function returns, the variable no longer exists and the pointer you assigned with
tail->next = &next;
becomes invalid.
You should allocate the 'next' item at a heap:
List* next = ne... |
68,453,748 | 68,454,714 | Define a huge hexadecimal number | I am working with a function cksumcrc32(init, (unsigned char *) &data, len);. The problem is that variable data is quite big, in hexadecimal is: 0x0020b3801005064000007d8000000000000000000000200000000000000000000000000, in terms of bytes, it is 36 bytes long. I am trying to define the variable in c++, but errors like "... | I think what you are looking for is an array of these bytes (or a vector) in the format:
std::vector<std::byte> arr;
arr.push_back(byte);
With this, you can individually add bytes of the number into this vector, allowing the integer to be as large as you want.
|
68,453,882 | 69,595,723 | Custom syntax highlighting using QScintilla with Qt/C++ | I am trying to implement custom syntax highlighting in Qt (C++) using QScintilla, however, the documentation is somehow poor. I googled and only found a tutorial for PyQt (qscintilla.com). I am using C++ not Python.
So where can I start? I have noticed that there is a class QSciLexCustom but it looks really confusing f... | You can subclass QsciLexerCustom and implement a styleText() function:
class MyCustomLexer: public QsciLexerCustom
{
public:
MyCustomLexer(QsciScintilla *parent);
void styleText(int start, int end);
QString description(int style) const;
const char *language() const;
QsciScintilla *parent_;
};
M... |
68,454,276 | 68,454,397 | Declare same template class as friend inside the template class? | Consider the following:
template<std::integral T>
class Integer {
T value;
template<std::integral T2>
friend class Integer;
public:
template<std::integral T2>
friend bool operator==(Integer<T> x, Integer<T2> y) {
return x.value == y.value;
}
};
the Integer class defines the friend operator== to comp... |
[class.friend]
10 Friendship is neither inherited nor transitive. [Example 8:
class A {
friend class B;
int a;
};
class B {
friend class C;
};
class C {
void f(A* p) {
p->a++; // error: C is not a friend of A despite being a friend of a friend
}
};
class D : public B {
void f(A* p) {
p... |
68,454,294 | 68,454,500 | time function in c++ by reference | I was working on a function that rewrites the values of a time struct accordingly (if minutes are 128 it will change to 2 hours and 8 minutes)
don't mind too much the actual function right now, my problem seems to be with the declaration/parameters/struct itself.
Erors:
Error (active) E0070 incomplete type is not ... | Struct name 'time' is causing the conflict. You can change name of the struct to something else and replace typedef struct to struct only otherwise it will be ignored by compiler itself.
This code is working for me.
#include <iostream>
#include <iomanip>
//#include<math.h>
//void canonify(ti&);
using namespace std;
//
... |
68,454,351 | 68,454,595 | How to print a matrix using goto statement | How to print a matrix using only goto statement?
I tried but my code is not working .
#include <stdio.h>
int main()
{
//int i=0,j=0;
int arr[3][3] = { (1, 2, 3), (4, 5, 6), (7, 8, 9) };
printf("The matrix is");
int i = 0;
printrow:
{
int j = 0;
printcolumn:
{
int j = 0;
... | Here you go.
#include <stdio.h>
int main()
{
//int i=0,j=0;
int arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
printf("The matrix is\n");
int i = 0;
printrow:
{
int j = 0;
printcolumn:
{
if (j < 3)
{
printf("%d ", arr[i][j]);
j++;
... |
68,454,362 | 68,470,220 | Having trouble when using 2d orthographic matrix with glm | after I've set up the (orthogonal) projection matrix for my simple 2d game, nothing renders on the screen. I am using cglm (glm but in c) and compared the results of cglm with the normal glm ortho projection implementation that renders well, and the results of the projection matrix match. Here is my render loop:
void R... | As @BDL and others have suggested, here is my final render loop that works like a charm right now:
(posting as a reference)
void RenderSprite(const struct Sprite *sprite) {
ASSERT(sprite, "[ERROR]: Can't render a sprite which is NULL\n");
struct Shader *shader = GetSpriteShader(sprite);
UseShader(shader);
... |
68,454,589 | 68,454,768 | What does the angle bracket syntax mean in a function call? | What does this syntax mean?
ForExample<Something>();
Can someone explain with a few examples how and what for it can be used?
| This code could be a call of the template function or instantiation of temporary class object.
For example, function is defined as:
template <typename T>
void ForExample(){
// Do something
}
This function can be called as:
ForExample<int>();
In your case type Something can be any type (int, double, string, float .... |
68,454,719 | 68,454,972 | C++ metaprogramming to split the function arguments and pass them one by one to another function | So I have a variable argument function with different argument types; I would like to pass every argument to another function which is a C function. As an example;
for a case with two arguments;
void function(int *a, double *b) needs to call
{
bindToFunc(0, a);
bindToFunc(1, b);
}
void function(int *a, double *b,... | With C++17 and fold expression, you might do:
template<typename... Ts>
void function(Ts... args)
{
[[maybe_unused]] int i = 0; // Not used for empty pack.
(bindToFunc(i++, args), ...);
}
|
68,454,861 | 68,455,317 | clang-format array initialiser over multiple lines? | I'd like to be able to write the following code:
float positions[] =
{
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f
};
however clang-format keeps formating the initializers to be over one single line.
I can't find the setting to allow them to be either over one line or multiple lines as above... | Your arrangement doesn't make any sense from a formatter point of view. You have an initializer list and asking the formatter to arrange it in two elements per line. But an initializer list has no semantics, nothing at all to even remotely suggest that its elements are related in pairs.
If your elements should be group... |
68,455,008 | 68,455,141 | Are symbols from the C standard library reserved in C++? | This is a follow-up to a different question.
The original question had other problems but I had to realize that the main one (according to CLang) was a redefinition of time as a different symbol while only nice C++ includes were used.
So here is a stripped-down version:
#include<iostream>
using std::cout;
using std::e... |
[extern.names]
3 Each name from the C standard library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.
Note that this paragraph reserves the name itself. So aliasing time in the global namespace violates thi... |
68,455,235 | 68,455,432 | What is an efficient way to get e.g. a specific member of a class by its id in C++? | I need help understanding how I setup my programme correctly. I have a class that stores "Customers". I read those customers from a file into the programme as class members. Now at a different part of my programme I want to get the corresponding data of the customer (e.g.: age, city) by the customers unique id.
class C... | A std::set will store customers in such a way (usually balanced binary search tree) that you can add and retrieve in logarithmic time.
This has an advantage over std::map in that you do not need to separate the key (customer id) from the value (the customer).
We have to do a little boilerplate to allow comparison of in... |
68,455,379 | 68,455,459 | How can i access variables in the main function from other function | I've looked at other topics, the answers usually solve the problem using parameters, but this is not the way I want. I'm new to C++, I was developing NodeJS before. Can we make a variable that we can access from the region we want like in NodeJS?
string read_from_ram(string& key) {
//how can I access and edit keysDB... | No. You'll have to pass a pointer/reference to the function with the way you currently have it written, or set it as a global variable (which is typically frowned upon unless required by the problem scope).
Another potential idea would be to make an object.
class MyClass {
private:
string key;
public: ... |
68,457,880 | 68,458,793 | cin skips when a character is input | I have a program in which I must input two doubles, and it must terminate when the character '|' is entered. However, when I type the character '|' cin is skipped and the program will just run without blocking. How can I terminate the program when a character is put in?
My code is:
#include "std_lib_facilities.h"
int ... | You can't read a | character into a double variable. operator>> will fail to extract the number and will set the failbit on the stream, which you can test for, eg:
#include "std_lib_facilities.h"
int main()
{
do
{
double number1, number2;
cout << "Enter two doubles\n";
if (!(cin >> nu... |
68,457,968 | 68,458,414 | Within a DLL function returning memory, where to allocate and where to deallocate? | I'm extremely new to DLL writing/usage, and have written a function within the DLL that accepts a string, and returns another string to the executable as output.
#define DECL_EXPORT extern "C" __declspec(dllexport)
DECL_EXPORT char * organizeArgs(const char * args) {
uint32 outputLen;
...
char * result ... | Another method is to change your function to the following:
DECL_EXPORT LONG organizeArgs(LPCSTR args, LPSTR outbuf, LONG length);
Then the API could be documented like this:
args - is the set of arguments
outbuf - is the output buffer or NULL
length - length of the output buffer, ignored if outbuf is NULL
Returns: ... |
68,458,805 | 68,458,912 | Can you use scanf() to define a variable set with #define? | If I initialize a variable using #define, can I then set its value using scanf()? i.e. does this work:
#define miscellaneous
printf("What value would you like to use for this example: ");
scanf("%g",&miscellaneous);
If I can't do it this way, is it even possible to set the value of a variable defined this way?
| #define miscellaneous means that every time you write miscellaneous, you would like the compiler to replace it with nothing. #define is automated copy-paste and in this case it pastes nothing.
So when you write scanf("%g", &miscellaneous); the macro (the #define) causes it to be changed to scanf("%g", &); which is not ... |
68,459,269 | 68,459,570 | Insertion of character in an initialized array | Let the array I have declared be:
char input[] = {'a','l','d'};
Now, I have to insert another character inside this array. Can I insert my character inside this array, or do I have to change the size of the input array and then insert?
Do char input[] = {'a','l','d'} and char input[3]={'a','l','d'} both have the same ... | If you have
char input[] = {'a','l','d'};
then the array is of size exactly 3, and there's no possibility to store additional characters in it.
You can overwrite:
input[1] = 'n';
but that replaces a character, not insert.
If you declare the array with some extra size, then you have some wiggle room.
char input[10] = ... |
68,460,156 | 68,460,217 | Is std::array<char, size> null terminated? | Is the following snippet of code safe? It invoked std::string's fourth constructor that takes in a pointer to a null terminated string. The thing is, I'm not sure if word below is null terminated. Is it?
std::array<char, 4> word{'a', 'b', 'c', 'd'};
int main()
{
std::string p = word.data();
return 0;
}
|
Is std::array<char, size> null terminated?
It can contain a null terminated string. It doesn't necessarily contain a null terminated string.
std::array<char, 4> word{'a', 'b', 'c', 'd'};
This array does not contain a null terminated string. You can tell because none of the elements are the null terminator characte... |
68,460,392 | 68,460,465 | If else statement not running C++ | I am trying to make a simple guess the number game and when the answer is bigger than the number the if else statement does not trigger.
For example if the number is 20 and I choose something above 30 say 41 it will just end the code.
#include <iostream>
#include <string>
#include <cmath>
#include <unistd.h>
#include ... | Consider this if statement when number is equal to 20 and answer is equal to 41.
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (an... |
68,461,088 | 68,461,391 | c++ more than one instance of overloaded function matches argument type | I've overloaded my function contains three times
// returns true if char c is contained in unordered map um
bool contains(std::unordered_map<char, op>& um, char c){
return um.find(c) != um.end();
}
// returns true if string s is contained in unordered map um
bool contains(std::unordered_map<char, op>& um, std::str... | Which overload you expect to match your call to the below line?
std::cout << contains(opmap, "+");
Overload 1 cannot match, because of your second argument, i.e. "+". Its type is const char[2] and cannot be matched to char.
Overload 2 and 3 cannot match, because the type of "+" has a const qualifier, but in those two ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.