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 |
|---|---|---|---|---|
67,214,300 | 67,214,452 | Initialize array from pointer and size of another array | In a function, I have access to the pointer and size of another array. Passing these along with the pointer, I want to add that data to a map. How can I do that without copying the underlying data twice?
void addToMap(double* ptr, size_t size, unsigned key) {
// Here I want to add the array corresponding to the point... | You cannot define an array variable like that because the function argument can vary at runtime, and is therefore not compile time constant which is a requirement for the size of an array variable.
You'll need to allocate the array dynamically. std::vector is the simplest way to do that.
An array can also not be direct... |
67,214,473 | 67,214,706 | How to initialiaze a multidimensional dynamically allocated array in a constructor C++? | I have created a class template that holds a union of the following type, which should be of variable length.
union BufferUnion {
int buf32;
short buf16[2];
};
class SomeClass {
int nBufs;
int buflen;
BufferUnion **bu;
SomeClass(int nBufs, int buflen);
~SomeClass();
}
and now I want... | First thing you should do when creating the two-dimensional array is to allocate the memory for the first dimension, then iterate on it creating the second dimension.
You've got the second part right, but what you're missing is:
bu = new BufferUnion*[nBufs] before the loop creating the second dimension.
As a sidenote:
... |
67,215,542 | 67,350,677 | SWIG JAVA typemaps configuration | Here is SWIG typemap, that converts C++ types to Python types.
#ifdef SWIGPYTHON
%typemap(in) (char *data, size_t datasize) {
Py_ssize_t len;
PyBytes_AsStringAndSize($input, &$1, &len);
$2 = (size_t)len;
}
%typemap(in, numinputs=0) (char **data, size_t *datasize)(char *temp, size_t tempsize) {
$... | SWIG already has a typemap for Java which does this for you. To use it all you need to do is use %apply to tell SWIG it is what you want to use for those parameters:
e.g.
%module test
%apply (char *STRING, size_t LENGTH) { (char *data, size_t datasize) }
void putFrame(char *data, size_t datasize);
which will generat... |
67,215,672 | 67,216,795 | Function pointers passed as template arguments | I was reading through some code and I found a case where a function pointer (the address, not the type) is passed to a template parameter.
// connects a free function
registry.on_construct<position>().connect<&my_free_function>();
// connects a member function
registry.on_construct<position>().connect<&my_class::memb... |
Is this doing what I think it's doing, ie., statically bound call of a function pointer?
Yes, this is doing exactly what you think it's doing. It binds the argument as part of the type itself so that it's not needed to be passed as a runtime argument
Does the template parameter need to be auto for this to work?
No ... |
67,216,726 | 67,216,818 | Need to get this program checking if Number is prime but without if statement, how to make it work for 1? main can not be changed | Need to get this program checking if Number is prime but without if statement, how to make it work for 1? main can not be changed
#include <iostream>
bool prime(int x){
for (int i = 2; i < x; ++i){
return (x % i != 0);
}
}
int main() {
std::cout << std::boolalpha << prime(1344) << std::endl;
}
| Your function returns in the first iteration of the loop and only checks if the number is even or odd. Its basically the same as:
bool prime(int x){
return (x % 2 != 0);
}
For the special case of x==1 you just need to add the condition that x can only be prime when it is not 1. And we can break out of the loop... |
67,216,773 | 67,216,847 | Bug when creating a class without using the new keyword | So I have a node class. I add a single node to a std::vector if mouse is pressed. This is the way I did it the first time.
struct Node
{
Node(int _x, int _y) : x(_x), y(_y)
{
};
int x = 0;
int y = 0;
Node* neighbours = nullptr;
};
std::vector<Node*> nodes;
//The following is in a while loop
i... | Your original code is pushing a pointer to a local variable that goes out of scope immediately after the push, destroying the node and leaving the vector with a dangling pointer, eg:
if (GetMouse(0).bPressed)
{
Node node = Node(mouseX - (nodeSize / 2), mouseY - (nodeSize / 2));
nodes.push_back(&node);
} // <-- ... |
67,216,829 | 67,216,970 | String class with concatenation с++ | I recently started learning c++ and I have a problem with implementing my own string class with string concatenation.
When the strings are added together, an error appears in debugging : <incomplete sequence \331>
I checked on many lines and noticed that the program works fine when the line is short , but stops working... | There are a lot of things wrong with your code.
Where is your operator=? You appear to have violated the Rule of Three. This is a massive memory bug.
for (int i = 1; i <= length; i++) if (i % 2 == 0) seems like a weird way to write for (int i = 2; i <= length; i+=2). This works fine, it's just weird.
operator+ does no... |
67,216,931 | 67,217,021 | A little double-linked list puzzle | Disclaimer
So initially when I posted this, it was a forward list by my error even though I meant to do it as a double-linked list - that's why there are some replies that don't match the problem.
Problem
I was doing some coding and I got to code below. At first glance, it looked like there is nothing wrong with the co... |
Eg. in line n2 = new Node(2, n3); n3 would be a bad pointer
There is a simple solution. Fix the order of initialisation so that you start with objects that have no dependencies, and initialise objects after their dependencies have been initialised. In this case, "1" depends on "2" and "2" depends on "3", so therefore... |
67,217,100 | 67,217,184 | Calling function via pointer in lambda expression | I am having vector, that stores classes of type Sensor, which each have a member function refresh(). This vector is member of my class LogManager.
class Sensor
{
public:
void refresh();
}
class LogManager
{
private:
std::vector<Sensor*> sensors;
void refresh_sensors()
{
... | Hmm.
for_each(sensors.begin(), sensors.end(), []( Sensor * sensor ) void -> { sensor->refresh(); } );
I didn't try compiling it, so there might be a syntax problem. Things I changed:
You're not using the [sensors] section, so I emptied that.
If you're using void *, you're almost certainly doing something very un-C++-... |
67,217,130 | 67,217,275 | Write a C++ code to count the number of a’s in a string | I've written the code below, but it's giving a number of errors:
15 13 C:\Users\admin\Desktop\Untitled1.cpp [Error] no match for 'operator==' (operand types are 'std::string {aka std::basic_string<char>}' and 'char')
15 28 C:\Users\admin\Desktop\Untitled1.cpp [Error] no match for 'operator==' (operand types a... | You're making this WAY too hard.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int count=0;
string str;
cout<<"Enter the characters for your string:";
getline(cin, str);
for (char c: str) {
if (c == 'a' || c == 'A')
count++;
}
cout<<"Number of ... |
67,217,754 | 67,219,110 | Number of vowels including "Y" | I have to write a function that prints out all vowels in a given string line including Y, unless Y is followed by another vowel.
For example:
"test phrase" returns 3
"yes no why not?" returns 4
I've tried using getline(), but I'm not sure if there's a way to use it without requiring some type of input from the user. I... | I deleted my last answer as I didn't understand your question correctly. But now here's the code that should work as intended. And yeah you should not use using namespace std, it is considered a bad practice.
Look here: Why is "using namespace std;" considered bad practice?
#include <algorithm>
#include <iostream>
#inc... |
67,218,349 | 67,218,674 | Could an R-value be equal to a nullptr | I have the following function in a C++ class:
CLASS_TYPE& operator=(const char* const &&rhs)
Could rhs ever be equal to a nullptr? In other words do I need to check in the operator definition if rhs equals to nullptr?
| The value nullptr is within the possible value a pointer can take. Trying to block that from happening at compile time is futile, since you can always set the value of a pointer to nullptr at runtime.
If you intended to receive a non-null string literal, simply use std::string_view or a reference to char array:
// Neve... |
67,218,404 | 67,218,542 | string subscript out of range error in word capitalization | Actually, the program works fine in Devc++ but gives me the error if i run it in VisualStudio, does anybody know why this happens?
The program should check if it has to cout a string from the stati array with every first letter of each word capitalized and then it has to convert the string back to lowercase, statoScelt... | Couple of things wrong with your code :
you need to place double quotes around the string characters you've defined .
For example:
std::string colour[4] = { "Blue", "Red",
"Orange", "Yellow" };
The size 16 makes sense for the last word , where size is 16, but for all the other words, you're still trying to access the... |
67,218,974 | 67,219,066 | invalid operands of types 'int' and 'const char [11]' to binary 'operator<<' | First of all, I'm just a beginner so I'm sorry if this would sound really stupid.
I'm currently doing a game in C++ where every move of a player corresponds to additional money and time deduction. Each player starts with 0 initial money and 30 minutes of time. I plan to have this on loop until both players have 0 time ... | Because of operator precedence rules (<< is evaluated before += and -=), you need to bracket your arithmetic expressions, like this:
if ((groupNumber1 == 1))
{
cout<<"You now have a total of "<<"$"<< (initialMoney += teensMoney) <<" and have "<< (initialTime -= teensTime) <<" minutes remaining."<<endl;
}
else if ((... |
67,219,028 | 67,219,098 | What is the expected behavior of C++ constant folding of integer expressions? | For example, let's say we have a function that replaces the two least significant decimal places of an int with 0:
int Remove2LSD(int x)
{
return x / 100 * 100;
}
If we pass 2052 we should expect a return of 2000, 2199 should return 2100.
It does not appear that constant folding occurs with the MSVC compiler if you ... | Most optimizations (including constant folding) are governed by the as-if rule. It states that any optimization is allowed if and only if it doesn't change the observable behavior of the program (it works "as if" it was unoptimized).
So no, you don't need to worry about constant folding here.
|
67,219,163 | 67,219,355 | Pointer on class contructor | I'm working on a personal project and I need to have a dynamic factory.
Currently I have the following "system" :
class Action { ...} // Which is abstract
class A : public Action { ... }
class B : public Action { ... }
class C : public Action { ... }
...
std::map<std::string, Action *> _actions;
_action.insert( { "A"... | You can implement the clone idiom to avoid having to dynamic_cast objects to determine which copy constructor to call, eg:
class Action {
public:
virtual ~Action() {};
virtual Action* clone() = 0;
...
};
class A : public Action {
public:
Action* clone() { return new A(*this); }
...
};
class B : pu... |
67,219,487 | 67,220,139 | Building a priority queue with a minHeap | This is my first time implementing a priority queue and I have a question.
For this implementation:
#pragma once
#include <vector>
#include <algorithm>
template <typename T>
struct PriorityQueue
{
std::vector<T> heapMin;
PriorityQueue();
PriorityQueue(std::vector<T>);
void minHeapfy(int);
void... | A heap is a partially sorted structure. A min heap requires only the parent to be smaller than the current node, but puts no restriction on the order of sibling nodes. This means there are many ways to organize the same data in a heap.
The following are both correct min heaps for values 1, 2, 3:
1 1
/ \... |
67,220,250 | 67,499,189 | MinGW - Header incomplete <netfw.h> | i am developing a networked application in C++ that should be able to add a rule to the windows firewall. I am following this example using the MingW g++ compiler.
The other examples are working without a problem, but this particular example won't work.
The exact problem i am facing, that NetFwRule is not defined in th... | Your GCC was too old.
You can get a newer version via MSYS' pacman, or download a standalone build, for example from http://winlibs.com/ which will work just as well if you don't need MSYS2.
|
67,220,643 | 67,277,647 | Transform ASCII Art to OpenCV Mat | I've recently started to work on a small project that consist of getting my camera input and transforming it into a virtual camera output as an Ascii art.
In order to do so, I've decided to use OpenCV to get my camera input and v4l2loopback for the virtual camera output.
In between, I've made a simple program that tran... | Here's a small proof of concept for converting a char matrix into an OpenCV Mat, using cv::putText. The idea is that you start with a matrix of chars (here, defined using std::vector) and you loop through each item. You extract the char, create a cell (an empty BGR Mat with a defined size), and you concatenate each cel... |
67,220,699 | 67,300,251 | Specify noutput_items for each output in work function | I want to modify a OOT block to have two outputs, as follow :
Current state :
int
block_impl::general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
... | You can use the produce function as follow :
int
block_impl::general_work (int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
const int OUT = 0;
cons... |
67,221,699 | 67,221,864 | C++ get return type for template argument | I have
template<typename DistanceFunc>
class C
{
using DistanceType = // the return type from DistanceFunc
public:
C(DistanceType distance, DistanceFunc f)
: m_distance(distance),
m_f(f)
{}
private:
DistanceType m_distance;
DistanceFunc m_f;
};
How do I derive the return type from Dista... |
How do I derive the return type from DistanceFunc for DistanceType?
Another solution could be use template specialization.
You can declare C as receiving a typename, without defining it
template <typename>
class C;
Then you can define a specialization of C receiving a (pointer to) function type as follows
template <... |
67,221,799 | 67,223,290 | Wrong function resolution in template when using inheritance | This code prints
non-template
template
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <type_traits>
using std::cout;
using std::endl;
struct A {
void g1();
};
struct B : A {
void g2();
};
void f(A& a)
{
cout << "non-template" << endl;
}
templat... | Non template beats template when there is otherwise a tie.
But for *this in B::b2, the template generates a (B&) signature, and the non-template a (A&), and B& is a better match. No tie.
For A::g1, it is (A&) vs (A&), a tie, so non-template wins.
Overload resolution can't do what you want. You can manually dispatch, ... |
67,222,253 | 67,222,302 | Why is my variable constant when it wasn't when I defined it? | Currently, I have a problem when trying to find a variable within a vector.
I defined a vector, tests, set to contain my own structure Test. It contains two variables, one and two. Both are instances of Test.
Test isn't much, it only contains an int and char.
I defined a macro that finds wether or not an instance of an... |
error: no match for 'operator==' (operand types are 'Test' and 'const Test')
You don't have an equality operator defined for Test. You need to define operator== so it can know how to check if two instances are equal.
|
67,222,333 | 67,222,395 | Constructor got deleted by compiler when I have a virtual method? | I came across a situation that can be summarized in the following code snippet. Basically, I would like my classes to inherit constructors. It works, but compilation fails as soon as I have a virtual method defined in C. Apparently the compiler deleted the constructor.
My questions are:
Why does the compiler do that?
... | Constructors are inherited only when you explicitly declare the inherited constructors. This is done as follows:
struct B : public A {
using A::A;
};
struct C : public B {
using B::B;
};
In your program, you are not using inherited constructors; you are using aggregate initialization. Adding a virtual functio... |
67,223,637 | 67,224,452 | multiprocess open a same file cause file operation failed | During process running , I use vim aa.txt and exec :wq ,then this process can't print any longer. Why ?
When I check process status by lsof -p pid,It show /home/ben/bypy/sederror/aa.txt~ (deleted) . By the way , testing in centos.
//test.cc
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std... | When you open a file on Linux, it's identified by device and inode, which isn't reused as long as anything has a reference to it. If you delete the file and create a new one with the same name, any processes that already had it open will still be referring to the old now-deleted one, not the new one. And when you edit ... |
67,223,792 | 67,223,836 | C++ Variables not updating in loop | For some reason the values in the loop do not update. Instead of taking the new values they are assigned in the loop they stay the same as when first assigned. Why is this?
using namespace std;
int main() {
int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;
... | I assume that town_A_Pop and town_B_Pop don't update.
If town_A_Growth is less than 100(and greater or same than 0) then (town_A_Growth / 100) will evaluate to 0 and (1 + (town_A_Growth / 100)) will evaluate to 1.
In that case, town_A_Pop = town_A_Pop * 1 so it will stay same.
Same goes to town_B_Pop.
To fix the proble... |
67,223,875 | 67,224,156 | Parsing date string to int using cpp | I was trying to solve a problem. The Problem is : There is given a date string like 21/9/2013. I have to convert this date into int. I have used stoi but it is just showed first two int 21.
|
I want to print 21 9 2013 to the console
So you don't really need three integers. You need three strings.
With these includes:
#include <string>
#include <sstream>
using namespace std;
You can parse a string like this:
string date = "21/9/2013";
into its components, like this:
stringstream stream(date);
string s;
w... |
67,224,125 | 67,224,416 | Why does a virtual destructor write to memory? | Recently, when working with custom allocator code and placement new+delete, I noticed something that surprised me: When a virtual destructor is called, it writes to the object's soon-to-be-freed memory.
Why is that?
(update) Aside: I'm more interested in the actual behavior here, not what the C++ standard has to say, w... | To destroy a Derived, conceptually Derived::~Derived is called (which does nothing in this case), then the vtable is adjusted so that the object is an Interface, then Interface::~Interface is called. What you are observing is the pointer to the Interface vtable (as seen here, constructing an Interface gives the same fi... |
67,224,539 | 67,225,069 | Result of subtracting indexes of an integer array | I am currently studying C++ and I am confused with this code:
int array[10];
int* p1 = &array[3];
int* p2 = &array[7];
cout<<"p2-p1=" << p2 - p1 <<endl;
I thought the result would be 16 because one element of an integer array is 4-byte sized but the compiler says p2-p1=4. Is subtracting between pointer... | It doesn't ignore the size of bytes, but the pointer knows the size of the pointed object. So 4 Bytes if it's an integer, 8 Bytes for double, ... . This works even for arrays of your own structs. I just added a picture for visualization of how this looks like.
|
67,224,821 | 67,225,028 | Return Integer while overloading operator plus 2 object in c++ | I want to return integer when + 2 objects.
But it caught errors
E2140 expression must have integral or unscoped enum type
Error C2110 '+': cannot add two pointers
class Sum {
int number;
public:
Sum(int number) : number(number) {};
int getNumber() const { return number; }
void setNumber(int val) { n... | Because the operator is defined inside the class it's left hand side must be of type Sum and the right hand side must be of type Sum* (because that's the type of parameter d1).
However, you try to add two pointers here:
int result = num1 + num2;
Correct would be to dereference the left hand side
// V
int res... |
67,225,377 | 67,244,927 | Using R and Rcpp, how to multiply two matrices that are sparse Matrix::csr/csc format? | The following code works as expected:
matrix.cpp
// [[Rcpp::depends(RcppEigen)]]
#include <RcppEigen.h>
// [[Rcpp::export]]
SEXP eigenMatTrans(Eigen::MatrixXd A){
Eigen::MatrixXd C = A.transpose();
return Rcpp::wrap(C);
}
// [[Rcpp::export]]
SEXP eigenMatMult(Eigen::MatrixXd A, Eigen::MatrixXd B){
Eigen... | There's a reason that dgRMatrix crossproduct functions are not yet implemented, in fact, they should not be implemented because otherwise they would enable bad practice.
There are a few performance considerations when working with sparse matrices:
Accessing marginal views against the major marginal orientation is high... |
67,225,388 | 67,225,977 | Implementing C realloc in a macro with new and delete | I'm using a library that lets me override some of it's macros for how it allocates to the heap
#define STBI_MALLOC(sz) malloc(sz)
#define STBI_REALLOC(p,newsz) realloc(p,newsz)
#define STBI_FREE(p) free(p)
I'd like to accept some of it's allocated heap into my program without wrapping it or ... | TL;DR - It can't be done, leave the code as is.
There is no realloc possibility in C++. realloc goes against the object-oriented nature of C++, as objects can't be moved around like that, so C++ outright dismissed the idea.
Nor can one be implemented in terms of new and delete, as you need to know the current array siz... |
67,226,581 | 67,227,814 | Warning when passing pointers to packed structure member | I want to pass a reference to a packed structure to a function. Unfortunately the compiler (gcc 9.3.0) doesn't like my idea and complains about unaligned pointers. I understand what it means but I do not see how to fix it.
struct map {
...
int32_t xy;
...
} __attribute__((__packed__));
void Test::write(int3... | As workaround, you might use intermediate value:
int32_t val32 = 123;
{
auto aligned_xy = map.xy; // Fix possible alignment "issue"
write(&aligned_xy , val32);
map.xy = aligned_xy;
}
Note: write should not keep the 'intermediate' pointer though.
|
67,226,980 | 67,227,414 | How to stop a Qthread after calling movetothread()? | When I reimplement the QTcpserver::incomingConnection(), a new QThread and and a new QTcpsocket is created.The accept-fd is passed to the QTcpsocket. Howerver, the warning occurs with the whole process exiting unexpectly:
QThread: Destroyed while thread is still running
as the Qthread calls quit() and the two objects i... | First of all Qt has nice asynchronous API so use of threads (in this context) is totally obsolete and waste of resources.
By using lambda in connect statement you have lost thread hopping functionality, which is done by default by connect. Result is that you are trying to destroy thread object from thread which this ob... |
67,227,136 | 67,231,534 | Deleting tcl list returned from Tcl_NewListObj | I created a tcl list using this function Tcl_NewListObj , if I don't have use for this tcl list, how do I do clean up? Should I call delete on listPtr in the code below?
Tcl_Obj* listPtr = Tcl_NewListObj(0,NULL);
// some code where we decide we don't want to use listPtr
delete listPtr; // delete listP... | Use Tcl_IncrRefCount() and Tcl_DecrRefCount() to manage the reference count for the object; it will be disposed of correctly when the reference count is decreased to a value less than 1. (It starts at zero; an immediate Tcl_DecrRefCount() would destroy the list. The actual deletion function is TclFreeObj(), but never c... |
67,227,334 | 67,227,563 | How save a C++ pointer in python to pass it again later? | I'm trying to create something and I don't know if it's possible or "clean" :
From python, call function A of my C++ code to compute something complicated
The C++ code returns just the pointer to the python
Do other things in python...
From python, call function B of my C++ code, it takes the pointer and other things ... | A pointer is just data that can be marshaled and sent to anything. It is however a very bad idea because when doing that, you have to assure that that pointer remains valid as long as the python part has the pointer. There is no possibility to check whether the pointer is still valid, so dereferencing a pointer that yo... |
67,227,843 | 67,228,097 | How to hide iterators in the API to consume an item in a std::map wrapper | In a c++98 project I have a class Items that wraps a std::map:
#include <string>
#include <map>
class Item { /* ... */ }; // Some class holding some data
class Items
{
public:
typedef std::map<std::string,Item> container_type;
typedef container_type::iterator iterator;
Items() {}
iterator find(cons... | With optional(not std, which is C++17, but could be done in C++98 (using boost for example)), then you might have in interface
optional<Item> get(const std::string&) const;
optional<Item> extract(const std::string&);
With usage similar to:
Items items;
// ...
if (optional<Item> item = items.extract("some-id"))
{
/... |
67,227,934 | 67,229,597 | Program to read from file line by line | I've been trying to write a code to read from a file line by line:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin("Story.txt");
// ins.open("Story.txt", ios::in);
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
else{
char a[10... | When std::istream::getline has read 100-1 characters (without finding a newline,\n), it will set the failbit on the stream. This prevents further reading on the stream (unless you reset that state). It does however not set eofbit so you are now in a bit of a pickle. The failbit prevents further reading, and eof() retur... |
67,228,676 | 67,228,819 | why does insert in std::unordered_set call the copy constructor? | I have an std::unordered_set of pointers. If I do
int main()
{
std::unordered_set<std::unique_ptr<int>> set;
set.insert(std::make_unique(3));
}
everything works and insert calls the move constructor (i think). However I have a different situation that is similar to the following code
std::unordered_set<std::unique... | void add(const std::unique_ptr<int>& obj)
It comes down to something fundamental: you cannot move a constant object, by definition. "Move" basically means ripping the guts out of the moved-from object, and shoving all the guts into the new, moved-to object (in the most efficient manner possible, with the precision of... |
67,228,736 | 67,233,790 | Doxygen documentation of boost::signals2 function signature | like in the title: does anyone know how to properly write Doxygen documentation of the signature of a boost::signals2
/**
* @brief aSignal
* void : aVoidReturn
* int : anInteger
* doulbe : aDouble
*/
boost::signals2::signal<void(int,double)> aSignal;
Thaanks
| Since OP says my solution from comment works I'm turning that to answer.
Basically problem is that arguments of signal do not have names, only types, so providing those names solves the issue:
struct Foo
{
/**
* @brief aSignal
* @param quantity number of items
* @param weight mass of items
*/
bo... |
67,229,383 | 67,229,451 | CUDA: Using device functors in kernels | I tried to make a device functor that essentially performs (unoptimized) matrix-vector multiplication like so
namespace cusolve
{
template <class value_type,
class matrix_type = value_type*,
class vector_type = value_type*>
struct linear_operator
{
const matrix_type matrix;
const size_t wi... | Forgot to use ceil when calculating grid dimensions.
const size_t gridWidth = ceil( ((double) width) / 16.0l );
|
67,229,799 | 67,229,919 | chdir(<directory>) doesn't change directory: No such file or directory | I want to create a simple c++ programm, that changes directory.
int main(int argc, char * argv[]){
//...
char input[256];
char *command;
//read command
fgets(input, 256, stdin);
// CODE ADDED WITH HELP
command = strchr(input, '\n');
if(command){
*command = '\0';
}
// CODE ADDED WITH HELP
if(strncmp(input, "... | fgets(input, 256, stdin);
This reads a single line of text, including the trailing newline character. The Enter key generates the "newline" character, which is part of the input.
chdir(command);
Unless additional measures are taken, the trailing newline character remains in command.
The Golden Rule Of Computer Progra... |
67,230,213 | 67,231,629 | Accepting N arguments converting into the same type | I'm currently trying to make a vector class in C++.
The class should have a constructor which accepts as many arguments as there are dimensions in the vector. The dimensionality is defined by a template when instantiating the vector.
All augments should be able to be converted into the same data type from which the vec... | If you do not want all arguments to be of same type you can remove that part. Apart from that you have a typo here:
(sizeof(Ts) == N)
should be
(sizeof...(Ts) == N)
After fixing that, forwarding the parameters and adding definition of the constructor, your code seems to do what you want:
#include <type_traits>
#inc... |
67,230,369 | 67,260,174 | Python ctypes how to deal with malloc/free? | I'm trying to convert a .cpp file to .py using the ctypes library.
Some basic operations are working, but I'm struggling when using typedef structs as well as malloc/free.
Here what I got:
module.h:
typedef struct
{
CHAR8 name[M_MODNAMELEN_A]; /**< Name of the module. */
} MODULE_NAME;
typedef struct
{
... |
How should I translate the malloc line from cpp to python?
Usually, a DLL that returns something like MODULE_LIST does the malloc for you,
and provides a function to free it later, but if you have to fill one out yourself
an array type is created by multiplying a type by a size, then calling it to create an instance:... |
67,230,605 | 67,230,919 | How can i change icons in QTreeView widget | How can i change these icons? I can't find prop that change it in treeView settings.
| There is QTreeView::drawBranches function in Qt. With this function you can draw the arbitrary icons at the left side of tree items, using the specified QPainter:
void QTreeView::drawBranches(QPainter *painter, const QRect &rect,
const QModelIndex &index) const
Another option is customize ... |
67,230,835 | 67,231,440 | passing a pointer to a struct, to a fuction | My C++ skills are amateurish at best, and I need to write some code to interface with a 3rd party sensor by way of a manufacturer provided .dll
As such, the function definitions are provided by the manufacture, but i'm really not sure of the correct way to implement them.
I have two structs, as per the API documentatio... | You look to be duplicating the definitions of these structs, not creating one.
#include <iostream>
#include <windows.h>
#include "CMOS_USB.h"
int main(){
unsigned short ProductID = 0x4400;
UNIT_SENSOR_INFORMATION SensorInformation;
HANDLE DeviceHandle = USB_OpenDevice(ProductID);
// not used?
HA... |
67,231,438 | 67,231,499 | Why in my simple C++ code output is -1717986920? | I just started C++ learning. I wanted to create a class.
The code is:
#include <iostream>
using namespace std;
class MyClass {
public:
int a;
int b;
MyClass(int nA, int nB) {
int a = nA;
int b = nB;
}
int add() {
int output = a + b;
return output;
}
};
void m... | In your constructor, you declare two local variables, a and b, and assign the given arguments' values to those – leaving the member variables of the same name untouched (and, thus, uninitialized). Remove the 'declaration' part of the assignments:
MyClass(int nA, int nB) {
a = nA;
b = nB;
}
Or, ... |
67,231,768 | 67,231,928 | Variadic template functions - where to put base case | I want to create a function that saves the arguments into a container.
This does work:
template <size_t idx, class TargetT, class HeadU>
void variadicFill(TargetT& target, HeadU head)
{
target[idx] = head;
}
template <size_t idx ,class TargetT, class HeadU, class... TailUs>
void variadicFill(TargetT& ... | The second one doesn't work because you're attempting to invoke an overload whose declaration isn't visible to that scope. You can use a forward declaration for the base case like this:
template <size_t idx, class TargetT, class HeadU>
void variadicFill(TargetT& target, HeadU head);
template <size_t idx ,class TargetT... |
67,231,920 | 67,232,120 | Convert int[n][n] to vector<vector<int>> | We can easily convert an array to a vector with the following:
int a[n];
vector<int> b = vector(a, a + n);
I want to work with matrix, what if I want to convert :
int a[n][n];
to
vector<vector<int>> b = ... // from a
with b.size() = n and b[0...n-1].size() = n ?
Alternatively I am okay with a solution converting... | I doubt that vector of vector is the best choice of the container for your use case, but if it's out of your control something like this should work:
int a[n][n];
std::vector<std::vector<int>> v;
v.reserve(n);
for (int *arr : a) {
v.emplace_back(arr, arr + n);
}
|
67,232,354 | 67,242,359 | Mixin constructors nested pack expansion | I am trying to implement a Mixin class, and facing some problems:
This is what I have at the moment:
#include <iostream>
#include <string>
using namespace std;
struct Base
{
Base()
{
cout << "default ctor" << endl;
}
Base(int i, string s)
:i_(i)
,s_(s)
{
co... | The GCC error invalid use of pack expansion expression is a bug #88580. Seems to be a regression in GCC 10.
As mentioned in the comments, changing :Mixin(std::forward<Args>(args)...)... to :Mixin{std::forward<Args>(args)...}... solves the issue.
Regarding why the default Base constructor is called: the virtual base cla... |
67,232,676 | 67,233,193 | OpenCV face detection - if statement | I am using OpenCV to detect face in c++. this code works well, but I want to Add new function that if the code can't find a face. so I'll use if-else statement. but I don't know how use that. What should go into the if statement conditions? Thanks for reading and Sorry for the poor English.
CascadeClassifier cascade;
v... | It is my understanding that faces is an array containing the faces found by the classifier. What if you just check the length of this array ? If faces.size()==0 then..
|
67,232,693 | 67,232,781 | Given a templated class, is there a way to get the "base"/untemplated type? | Pretty straightforward, but maybe not possible: Given some T<some_type>, is there a way to get T? A better example with code here:
template<class T>
struct parametrized_class{
};
template<class T>
using make_floaty = T<float>; // this doesn't compile since T is not the "base" type
int main() {
using int_class ... | You definitely can, although templates not being first-class citizens makes it a bit tricky:
template <class T>
struct make_floaty;
template <template <class> class Template, class T>
struct make_floaty<Template<T>> {
using type = Template<float>;
};
template <class T>
using make_floaty_t = typename make_floaty<T... |
67,232,822 | 67,233,222 | C++ Difference between class attributes and object attributes | Questions :
What is the difference between : time.m_seconds = m_seconds + b.m_seconds; and time.m_seconds = time.m_seconds + b.m_seconds; and time.m_seconds = this->m_seconds + b.m_seconds; ? They dont give the same output.
The problem :
Expected output : 20:35:36 /
Actual output : 20:34:36 /
Output with time.m_seconds... | So after the explanation of @Nathan Pierson this is the answer to my problem.
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
class Time {
private:
int m_hours;
int m_minutes;
int m_seconds;
public:
Time(int hours = 0, int minutes = 0, int seconds... |
67,232,851 | 67,234,035 | How to check for NULL variant values when vt == VT_NULL does not work? | I am maintaining an old system which uses Borland C++ 2007 and AnsiString values (there's nothing I can do about this, the system is phasing out), and I have this use case :
// declared in the header as class property
AnsiString str; // { Data:NULL }
// used in a class method
Variant v = str;
if (v.vt == VT_NULL |... |
However v.vt == 256, so the condition is false.
256 is varString, which is a custom Variant type specific to Delphi/C++Builder. There is no VARTYPE equivalent of varString in the Win32 VARIANT API, so you can't use a Variant that is holding an AnsiString with Win32 VARIANT functions. You would have to make it hold a... |
67,232,994 | 67,237,684 | QNetworkReply::NetworkError(ProtocolInvalidOperationError) what is it and how to fix it? | I'm attempting to make a POST request to a web page but I got a error in code below:
void WebViewModel::sendPOST(QString url)
{
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/x-www-form-urlencoded"));
QByteArray postData;
postData.append("... | This happens when server responds with 400 status code (Bad Request) or with 418 status code (I'm a teapot).
Either server is not configured properly, or it does not expect post requests to that endpoint, or it doesn't like requests with empty body.
You can use curl to validate that server responds with no error to pos... |
67,233,250 | 67,233,345 | Reading number of characters and words in a file | I tried to write a program to find out the number of characters and words in a file:
/*
Write C++ program to count:
Number of characters in a file
Number of words in a file
Number of lines in a file
*/
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int countOfCharacters = 0;
int countO... | When you reach the end of the file in the first read routine eofbit flag is set to true, in order to be able to read from the same stream without closing/reopening it, you need to reset it:
//...
ins.clear(); //<--
ins.seekg(0, ios::beg);
//...
That being said, you could do both counts in the same cycle, as suggested ... |
67,233,251 | 67,233,378 | Access to variables stored in the class object referenced by the variable | I have abstract class Organizm where I store reference to class Swiat. I don't know how to get access to variables of object which my Organizm reference to. The best explain is my code:
Organizmy.h
#pragma once
class Swiat;
class Organizm
{
public:
Swiat& swiat;
char symbol = '?';
int sila = 0;
int inic... | If you want to access the member swiat like here
cout<<this->swiat.x<<endl;
The the object must be known, but I see only a foward declaration here:
class Swiat;
You need to include the definition for Swiat as well. You must do something like
#include "Swiat.h"
or wherever your Swiat is defined.
The forward declarati... |
67,233,593 | 67,233,843 | std::chrono::high_resolution_clock based frame timer | I have been using the following clock definition for a frame timer for years now:
using frame_clock = std::conditional_t<
std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock,
std::chrono::steady_clock>;
In other words, I want a clock that is defined using the h... | For practical purposes, you only have 3 choices:
For taking real time, your only choice is std::system_clock (if you want to stay inside C++, OS levels routines do exist)
For measuring intervals, if you want to stay within C++, you have to use std::steady_clock. There is no implementation out there which would have a ... |
67,233,792 | 67,233,981 | Inserting its own size to std::map | I just encountered a weird bug in my code (C++14) caused by the unexpected (for me at least) behavior of std::map. Here's a simple example demonstrating the behavior:
#include <iostream>
#include <map>
int main()
{
std::map<int, int> m;
for(int i = 0; i < 3; ++i) {
m[m.size()] = m.size();
}
for... | There is a few thing that happens in the expression
m[m.size()] = m.size();
First, m[m.size()] and = m.size() need to be evaluated. In C++14, that evaluation order is indeterminately sequenced. m[m.size()] might happen first, or it might happen second. If it happens first, then you see the results you received. If... |
67,233,859 | 67,234,500 | CUDA GPU __global__ function does not complete | __global__ void functionA()
{
printf("functionA");
}
int main()
{
printf("main1");
functionA<<<1,1>>>();
printf("main2");
}
I'm trying to run a simple test with the above. But the program only outputs "main1". The program should output "functionA" and "main2" too.
| This seems to have two reasons:
First of all you need to add
cudaDeviceSynchronize();
after the CUDA routine in order to block the main until the device has completed all tasks.
Furthermore this might happen if you set the wrong GPU architecture/compute capability XX when compiling the code
$ nvcc -gencode=arch=comp... |
67,233,890 | 68,414,577 | WMI Query for SQL Server FilestreamSettings | Based on what I can find on the internet this doesn't seem to be something a lot of people do but I'm pretty stuck so I'm going to put it out here. I'm using WMI in C++ to try to manipulate SQL Server settings. I have the following code that doesn't return a result from my WMI query and I'm at a loss as to why:
hr = pL... | FYI, in case anyone stumbles across this: I didn't technically solve this, in that I never got my C++ code to work. I wrote some C# code using SQL Server Management Objects (basically a wrapper over WMI) and made it into a COM server that I could call from C++. Even this didn't work directly because my C# COM server ke... |
67,233,996 | 67,235,845 | How to use dynamic_cast efficiently? | There is an abstract class Entity, and other classes like Player and Enemy are inherit from it. When game detects a collision between the entities, the following method is called:
void handleCollision(Entity* ent1, Entity* ent2) {
if (dynamic_cast<Player*>(ent1) || dynamic_cast<Player*>(ent2) &&
... | Trying to expand Ben Voigt's comment about multiple virtual dispatch, something along the lines of:
void handleCollision(Entity* ent1, Entity* ent2)
{
ent1->collide_with(ent2);
}
Where:
class Entity
{
public:
virtual void collide_with(Entity*) = 0; // Dispatcher
virtual void handle_collision_with(Entity*) {}
... |
67,234,011 | 67,234,571 | Efficiently store multiple integral numbers in a single variable (and retrieve them) | Let's assume that we have up to 3 IDs (we don't know the number of IDs before, can be 0 to 3), each of them can consist of up to 4 digits, leading to numbers from 1 to 9999. Since these IDs are small enough, we want to store them in a single variable and not an array (for whatever reasons), such as a double. Here is an... | The IDs can go up to 9999, which requires 14 bits max. 3 integers of 14 bits each would require 42 bits max. You can easily store that in a 64-bit unsigned long or uint64_t with some manual bit-shifting, eg:
uint16_t get_id(uint64_t ids, uint8_t which)
{
return (ids >> (14 * (which & 3))) & 0x3FFF;
}
void set_id(u... |
67,234,106 | 67,234,236 | C++ variable list Initialization | So here are piece of 2 code
#1
int i=0, j=0;
for (i=0,j=0; i<=5; i++, j++)
{
cout<<i<<" "<<j<<endl;
}
#2
int i{0}, j{0};
for (i{0},j{0}; i<=5; i++, j++)
{
cout<<i<<" "<<j<<endl;
}
1st code allows me to replace the value inside for loop that was stored in i and j.
But in the code #... | List initialization, as the name suggests, is for the initialization of a variable. Initialization can only happen once, initially. You can assign to a variable, but list initialization is not for assignment (and yes, I know some types do allow assignment from braced-init-lists, but int isn't one of them).
So the corre... |
67,234,210 | 67,235,358 | How can I replace an array that's already assigned? | my program first asks how many names I want to insert then it stores those names in an array. Now in case 5 and void inserisci I am supposed to develop something that asks you which one of the names you entered you want to change and then what you want to change it to. Thing is, I have no idea how, I've been thinking a... | Firstly, your existing code had an error:
string* a = new string[n]; //arrays must have constant sizes, if you need a dynamic array, use the new operator
Arrays are allocated from the stack, so they need to have a size determined at compile time. If you need an array with a dynamic size, use the new operator, if you r... |
67,234,340 | 67,234,577 | How can I design around this restriction on concepts and incomplete types? | I have something like this:
template <typename T>
requires ::std::movable<T> || ::std::copyable<T> || ::std::is_void_v<T>
class ValueWrapper
{
// various functions to do stuff with value
};
class Value {
public:
Value(Value const &) = delete;
Value &operator =(Value const &) = delete;
Value(Value &&oth... | The type is complete within a member function definition, so we can use a deduced return type:
auto do_something() const {
return ValueWrapper<Value>();
}
|
67,234,365 | 67,235,063 | Sorting QList based on class property in Qt using Cpp | I have a QList qList, I want to sort this based on the property "playerRank" in Players class.
The Players class is as shown below.
class Players
{
public:
Players();
int playerId;
QString playerName;
int playerRank;
void setPlayerId(int id);
void setPlayerName(QString name);
void setPlayer... | @Ishra's answer is technically correct, but we can do better.
It's usually better to use the standard algorithms whenever possible
Make the parameters const so it works with containers to const objects too
No need for an inefficient "capture everything by copy" in the lambda
std::sort(qList.begin(), qList.end(), [](c... |
67,234,493 | 67,234,581 | C++ Multiplication Table | I need to create a multiplication table but with very specific directions. I have everything working, except one part. An example of the output has to look like this:
1 2 3 4 5 6 7
2 4 6 8 10 12 14
3 6 9 12 15 18 21
4 8 12 16 20 24 28
My output looks like this, but the code I wrote to do this has a space c... | You can just do it like this:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int x = 0;
int y = 0;
int a = 0;
// int y = 0; this is the error btw you can't re declare variable
int b = 0; //this is what you wanted i guess
cin >> x;
cin >> y;
for(b = 1; b <= y; ++b){
for(a ... |
67,235,807 | 67,358,106 | how to a run a windows desktop application from a console application | i currently have a game engine that i have developed during my university course.
i need to run the engine with the following function
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
... | circling back round and posting what ended up being the answer:
I ended up only needing 1 of the 4 parameters so I was able to rename the function and I was able to get the first parameter using GetModuleHandle(0)
these are the snippets from the same two files:
console application
windows application now being run fro... |
67,235,824 | 67,358,471 | How to build the whole openCV library into a static library? | I would like to build the whole openCV library into a file like opencv.a. I'm trying to use the .a binary file to link together with cpp code that I made that uses the openCV library, using emscripten to make a single wasm file.
Basically what I want to do is to compile the cpp app I made that uses the openCV library i... | Building OpenCV static libs
I think that is possible to build the whole OpenCV libs as a big static lib. But it is highly recommended to build the single and separated static libs for a fined granulated compilation. There are also parts of OpenCV project that compiling with Emscripten are very hard to build. And what a... |
67,236,104 | 67,236,179 | C++/SDL2 Mixer - One ternary works correctly, but a nearly-identical one doesn't? | I'm writing some simple test audio code to make sure SDL_mixer works for my application, but in the code to change the volume when given certain characters from std::cin everything works except for subtracting 10 from the volume. Adding 10 works, subtracting 1 works, but subtracting 10 only subtracts 1 and not 10.
In t... | The ternary operator works like this:
variable = (condition) ? expressionTrue : expressionFalse;
|
67,236,118 | 67,238,017 | How to add to existing numbers? C++ | I hope you all are having a wonderful day. Just to give a little context, I am trying to make a Mancala game in C++. The case is that I wanted to add to each number when a user gives an index. So for example, if the user types in 10 for the game of
04 04 04 04 04 04
00 00
04 04 04 04 04 04
... | Let's use a circular array to represent the board.
Each side has 6 slots, plus their "winnings" slot.
static const unsigned int MAX_SLOTS = 14u;
In my understanding of the game, a move is made by taking the contents of a slot and redistributing them (one per slot) in a clockwise or counter clockwise manner.
std::vecto... |
67,236,257 | 67,236,313 | array must be initialized with a brace-enclosed initializer c++ | Hello I have an Exercice where they give me this struct:
enum Sexe { INCONNUE=0, MASCULIN=1, FEMININ=2};
struct Personne {
int numero;
char nom[10];
Sexe sexe;
};
And I need to make a pointer and assign values to it. So I did this function:
void Init() {
Personne *p;
string sexe;
S... | In this declaration
Personne join_p{stoi(n),name,s};
the data member of the structure Personne is declared like
char nom[10];
that is it is an array,
But the array name used as an initializer is implicitly converted to a pointer to its first element.
So you are trying to initialize an array with a pointer.
You may no... |
67,236,275 | 67,236,395 | multiple inheritance diamond problem without default constructor | I end up with a multiple inheritance diamond problem with the situation that there is no default constructor in the base class.
struct A {
A(int x) {}
};
struct B : virtual public A {
using A::A;
};
struct C : virtual public A {
using A::A;
};
struct D : virtual public B, public C {
D(int x) : B(x), C(x) {}
... | You do have an access to A since you're inheriting from it.
You would have to call the constructor of A in order to construct the object D.
Your D constructor should look something like that :
D(int x) : A(x), B(x), C(x) {}
Because of the multiple inheritance, constructors of B and C would ignore the A(x) part and you... |
67,236,388 | 67,237,609 | I need to remove duplicate vertices(adjacency list) | File test.txt
6 (This is the number of vertices)
1 4 (Еhe first is the number of the vertex, and the second is the number of the vertex to which the edge is being constructed.
1 6
2 1
2 3
2 4
2 5
3 2
3 5
4 1
4 2
4 5
5 2
5 3
5 4
6 1
#include <iostream>
#include <fstream>
#include <vector>
#include <list>... | Based on what you have so far, seems like you don't really need a edge class. All the information could be stored in int instead.
And to solve what you wanted, you could first store all the edges in an std::vector<std::set<int> like:
while (input >> node1 >> node2)
{
adjList[node1 - 1].insert(node2);
}
By using a... |
67,236,561 | 67,236,766 | Variadic templates and function objects | Lets say that we have two function objects that take an int and return a boolean:
struct EvenNumber {
bool operator()(int const num) const {
return num % 2 == 0;
}
}
struct GreaterThenFive {
bool operator()(int const num) const {
return num > 5;
}
}
now let's say that we have a function that takes a ve... | You can't just call each filter on the argument, you also need to make a disjunction of the result of all the filters.
if ((std::forward<Filters>(filters)(num) && ...)) {
// ^^ ALL conditions must be satisfied
Also, the argument to forward needs to be the type Filters, not the va... |
67,237,027 | 67,237,205 | array class member with different size for each class instance | I would like to have a class that contains an array member, but the constructor lets me set the size of an array member.
Is this doable? I do not thing I need dynamic allocation, since once the class instances are created, there is no need for the array to change size, it is just that each class instance will have a di... | Despite several comments suggest that this would be impossible, it is actually not impossible.
The simplest way, of course, is to use an indirection and allocate the array during construction just the normal way (with a = new type[size] and calling delete[] a - not delete a - in the destructor).
But if for some reason ... |
67,237,197 | 67,237,276 | warning: ISO C++ forbids converting a string constant to 'char*' | I just started learning C++, and during compilation my code I get an error:
main.cpp:59:50: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
Encryption delta("dragons.txt", "output1.txt");
I don't know what this error means, or how to make it work, so if somebody could explain to... | To quote what is a literal type
Literal types are the types of constexpr variables and they can be constructed, manipulated, and returned from constexpr functions.
Essentially these are entities that can be used at compile time. Since they are constexpr, so for one thing, these are const, therefore, read-only. To fix... |
67,237,224 | 67,281,443 | Cannot link sndfile library to cmake project (MacOS) | Currently I'm trying to make some spectogram generation for my uni project. I'm trying to build a static library where all the magic will work and just call it from the main() function.
This is my cmake file:
set(CMAKE_CXX_STANDARD 17)
project(demo)
find_package(SndFile REQUIRED)
add_subdirectory(spectogram)
add_exe... | With help of Tsyvarev, I figured out the solution. I used the pkg-config module and a custom cmake file, I found on the web. I will include my final cmake in case someone else will need it:
cmake_minimum_required(VERSION 3.17)
set(CMAKE_CXX_STANDARD 17)
project(demo)
# - Try to find libsndfile
# Once done, this will ... |
67,237,321 | 67,237,392 | Troubles with BST recursion (finding height of a tree in C++) | int BST::getLength()
{
int leftHeight = 0;
int rightHeight = 0;
// Empty case
if (!prev && !dataInit)
return 0;
else
{
if (left)
{
leftHeight = left->getLength();
std::cout << "leftHeight: " << leftHeight;
std::cout << std::endl << ... | I am not completely sure about the structure of the rest of this code but I will hazard a guess here. It helps if we start thinking of base cases. For a binary tree, that would be the leaf nodes. For a leaf node, the height of its left or right children would be zero and the height of the entire tree including the leaf... |
67,237,550 | 67,237,961 | Why does iostream require the exception handler to be called while using vcvarsall.bat to compile 'Hello World'? | Attempting to compile the following code with vcvarsall.bat in command line throws a warning saying that the exception handler is needed in the code but not called before using /EHsc.
Code:
#include <iostream>
int main()
{
std::cout << "hello world" << std::endl;
return 0;
}
The batch file:
@echo off
cl... | Short answer:
Add /EHs or /EHsc to your compilation options as the documentation suggests. It's the most portable option regarding exceptions handling, if you will ever need to execute the same code on Unix machine.
Long answer:
There are two parts to this question. First is why the warning occurs in iostream and the ... |
67,237,567 | 67,237,633 | std::lexicographical_compare_three_way for ranges | Why is there std::lexicographical_compare_three_way, but no std::ranges::lexicographical_compare_three_way?
There is argument Comp in std::ranges::lexicographical_compare, but it is rather useless, because function returns bool, when one of the comparison category types is expected.
Here are some links to cppref
https... |
Why is there std::lexicographical_compare_three_way, but no std::ranges::lexicographical_compare_three_way?
The algorithms in std::ranges are constrained by concepts while the algorithms in std are not. So, for instance, std::ranges::lexicographical_compare (which uses a two-way comparison, defaulting to <) is specif... |
67,237,569 | 67,237,769 | std::filesystem::exists -- Do I need to check the std::error_code value if the function returns true? | std::filesystem::exists is used to check "if the given file status or path corresponds to an existing file or directory." In my code, I am using the definition with the following signature:
bool exists( const std::filesystem::path& p, std::error_code& ec ) noexcept;
My question is: if the function returns the boolean ... | The std::filesystem library evolved out directly from the corresponding Boost library. As several functions in the Boost libraries (such as Boost ASIO) it offers two interfaces that use a different type of error handling
bool exists(std::filesystem::path const& p);
bool exists(std::filesystem::path const& p, std::error... |
67,237,903 | 67,238,014 | Why I can't assign function returning rvalue reference when it's a int but I can when it's a class? | Why we can assign rvalue reference from a non-scalar but from a scalar it does not work, when returning from function, but works in local variable (wtf) ?
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <type_traits>
using std::cout;
using std::endl;
struct A
{
... | There's two things going on in your code. The first is the difference between being able to assign to temporaries (r-values) of class type.
struct S{};
S{} = S{}; // ok, S is class type
int{} = int{}; // error, int is an in-built type
This explains why f() = 10; doesn't work, but g() = A(); does. f returns a r-val... |
67,238,047 | 67,238,099 | Merge sort working but deleting elements c++ | Okay I have fiddled around with everything and can not find the problem. I am new to c++ and really need help with this. The merge sort works perfectly but for some odd reason will not give all the values. Working with recursive merge sort can be confusing so was hoping I could have this problem solved. Thank you!1
the... | The loop
for (int i = 0; i < (arrSize / 2); i++)
{
arrayOne.push_back(data[i]);
arrayTwo.push_back(data[i+arrSize/2]);
}
fails to work correctly when arrSize is an odd number. For example, if arrSize is 5, then arrSize / 2 evaluates to 2. Then, i takes values 0 and 1. So, arrayOne covers indices 0 and 1, and a... |
67,238,458 | 67,238,778 | How does the stringify operator expand TABS? | GCC seems like to always expand tabs in source code by spaces. It preserve space that are inside the expression. What does the standard says about it?
For example, what will c contains in this example (<TAB> represent a litteral \t character in source code file).
#define X(a) #a
const char* c = X(<TAB>a<TAB>c<TAB>);
/... | Consulting the C++ standard (draft)'s section [cpp.stringize] tells us:
Each occurrence of whitespace between the stringizing argument's preprocessing tokens becomes a single space character in the character string literal.
White space before the first preprocessing token and after the last preprocessing token compris... |
67,238,495 | 67,238,819 | value type of containers that contain other containers | In this question here a solution was suggested on how to check for the value type of a generic container, e.g. check if a std::vector contains integral. Now, sometimes I might be passing 2D vectors i.e. containers of containers that eventually has either a floating point or integral type.
How can we modify the followin... |
How do I extract the value type of the most nested container?
There is a type trait shown by user Evg in this answer.
Using that, this should work:
template< typename U, typename Tin, typename Tout>
concept MyConditions =
requires
{
typename U::value_type;
typename Tin::value_type;
typename Tout::value_ty... |
67,238,753 | 67,238,812 | Is it bad form to have "operator>" delegate to "operator<"? | I wrote this in a recent program:
friend bool operator<(const MyClass& a, const MyClass& b) {
// Lots of comparison code here
}
friend bool operator>(const MyClass& a, const MyClass& b) {
return b < a;
}
It works fine when I run the program, but is this bad form? Is there any reason I should not be doing this... | Defining the comparison operators in terms of less than is common in order to avoid writing the same code over and over (or copy/pasting) which is a source of bugs:
bool operator<(const Foo& a, const Foo& b) {
//Actual comparison of members
}
bool operator>=(const Foo& a, const Foo& b) {
return !(a < b);
}
bo... |
67,238,897 | 67,239,024 | What "conversion" of template template parameters is allowed in C++? | I'm trying to understand under what circumstances I can pass a type template as an argument for a template template parameter with a different signature. E.g., I would expect that the following might compile successfully.
template <typename...>
struct foo { };
template <template <typename> typename Template>
struct b... | I think Clang is wrong. Since C++17 (P0522R0, CWG 150), templates taking parameter pack like foo, should be allowed to be specified as template template argument for bar even it expects one template parameter.
template<class T> class A { /* ... */ };
template<class T, class U = T> class B { /* ... */ };
template <clas... |
67,239,221 | 67,239,259 | Palindrome boolean not checking false | For some reason my boolean is not checking false, can anyone help me figure out why? Also how would I go about making this program ignore spaces if it were a phrase (i.e. "never odd or even")
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string input;
int i = 0;
bo... | New answer
You are getting the size of the string before the user has entered the string.
Change
int size = input.size();
cin >> input;
to
cin >> input:
int size = input.size();
Previous answer
You are using a single = rather than two in the if statement.
Change
if (flag = true)
to
if (flag == true)
|
67,239,235 | 67,239,266 | How do I create a centered GLFW window? | I'm looking for the SDL equivalent of
gWindow = SDL_CreateWindow( "SDL window",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
WINDOW_WIDTH, WINDOW_HEIGHT, windowFlags );
for GLFW. I can center the glfw window after its creation with the below code, however, for a split second, the window is... | From the documentation:
By default, newly created windows use the placement recommended by the window system. To create the window at a specific position, make it initially invisible using the GLFW_VISIBLE window hint, set its position and then show it.
Example
Using your code above, you would add a call to glfwWindo... |
67,239,335 | 67,239,366 | how to print words inside a multi level char pointer array (c++)? | I have a
const char** extentions
of which is used with a call that returns an array into it.
extentions= glfwGetRequiredInstanceExtensions(&extentionscount);
im trying to print all the words in extentions.
my current code looks like this
for (int i = 0; i < 3; ++i)
{
for (int a = 0; a < 10; ... | You've almost got it.
a workaround for i is putting extentionscount in there which should match the number of words
That's no workaround, that's the solution ;)
Secondly: the strings in the array are null-terminated, so you don't need to iterate through them, just pass them to cout.
for (int i = 0; i < extensioncount... |
67,239,445 | 67,239,472 | GCC C++ linking error : Undefined reference to 'WinMain@16' | I'm have linking issue's on codelite when I try to build my project. I get the error 'undefined reference to 'WinMain@16'.
#include <stdio.h>
#include <SDL2/SDL.h>
int main()
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Quit();
return 0;
}
This is my main file, I am trying to use the SDL library fo... | Rename your main to be WinMain with the following parameters
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR lpCmdLine, INT nCmdShow)
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Quit();
return 0;
}
Most of those parameters will require #include <windows.h> If that header is not ava... |
67,239,447 | 67,239,618 | Rotating a 3D object at a (fast) constant rate in QT | This seems like a pretty simple problem, but I have tried a implementation of what I think would work and it works "kind of".
What I expect:
To be able to rotate an object about an axis at a constant rate that is rather fast. (Roughly around 120 *RPM or 2 *RPS.)
What I have tried:
My basic implementation was a QTimer t... | It seems that what you want is to make an animation of the rotation so in that case it is better to use a QVariantAnimation, that class will interpolate the values between the ranges that are established so it is no longer necessary to define a minimum change (the 0.1 degrees that you use).
Q3DFoo foo;
QVariantAnimati... |
67,239,717 | 67,240,061 | Not able to write #include statements properly in Geany IDE | Whenever I want to include a header in my source code, the IDE doesn't allow me to type the .h extension. If I type <stdio.h> it accepts only <stdio>, and I'm unable to type any further. I made no changes to the default settings built-in to the IDE. I am using the latest version 1.37.1. I have to manually #include head... | I consider this to be just on the right side of the on/offtopic definition, using the exception for "tools regularily used by programmers".
So I recommend to find out your configuration for "drop rest of word for auto completion" (within editor completion preferences). It could be active and I suspect you do not want i... |
67,240,105 | 67,240,240 | How to convert string array to integer array in C++? | I have a string of non-uniform space separated integers ,I want to do some arithmetic operations on the elements so I have decided to first convert the string to integer array. Below is my approach:
string s; //let s="1 2 30 54 899 2 7 3 1";
cin>>s;
int n=s.length();
vector<int>arr(n... |
What is wrong in this approach?
operator>> only extracts until the first encountered character in std::cin that satisfies std::isspace(), so s could not possibly be initialized to a string containing spaces in your program.
You assume that the length of the string n should be the length of the array. The number of c... |
67,240,118 | 71,780,297 | How to multiply multiple matrices with C++ | I'm doing a homework assignment which involves multiplying more than 2 matrices.
I thought about multiplying the first 2 matrices then take its result, continue multiplying it with the 3rd matrix, and repeat the same process until I multiply all the matrices together.
A * B * C = (A * B) * C = A * (B * C)
And here is... | Here is one solution.. Although I didn't applied dimension check of the matrices. So if you multiply a (3X4) & (2X4) matrix, it will not warn you. It can be done very easily with very simple steps. It worked for me with
A = 1 2 3 4
5 6 7 8 [4X4]
0 1 2 3
7 8 9 0
B = 2 ... |
67,240,232 | 67,240,351 | Generate a dependency diagram for c++ codes/projects | I have a massive C++ code to probe into from github and it would be helpful if I can generate a dependency diagram for the code base. Ideally I would like to know what function triggers other ones in the code and where are they located. Is there any program/software that does this?
Thanks
| This is called a call graph. One option is cflow together with pycflow2dot and dot. More options can be found at: https://stackoverflow.com/a/17844310/1959808
Example C file:
/*
* simple demo for pycflow2dot, use with:
* cflow2dot -i example.c -f png
* for help:
* cflow2dot -h
*/
#include <stdio.h>
void sa... |
67,240,399 | 67,240,605 | string size after converting const unsigned char[] to std::string | I tried to convert unsigned char array to an std::string of size 16.
But I don`t know why result string size is different.
I want to know the reason.
#include <iostream>
using namespace std;
const unsigned char t[16] = { 0x1E, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 ,0x08 ,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15 };... | case 1: input is not explicitly null-terminated, and likely those global arrays are placed in memory sequentially, so you get at least 48 bytes without zeros, finally it finds some zero 8 bytes ahead, so total is 56.
case 2: here you give it explicit length, and that's the correct way to do things in case of null termi... |
67,240,438 | 67,240,470 | Why does C++20 not allow to call a generic lambda with an explicit type? | auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>() { return T{}; };
int main()
{
f1(1); // ok
f2<int>(); // err: expected primary-expression before 'int'
}
Why does C++20 not allow to call a generic lambda with an explicit type?
| The correct syntax to invoke overloaded template operator () function supplying template parameters is
auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>() { return T{}; };
int main()
{
f1(1); // ok
f2.operator ()<int>(); // Ok
}
https://godbolt.org/z/YzY7njPGh
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.