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 |
|---|---|---|---|---|
61,625,998 | 61,626,131 | Can't use std::greater where std::less is used | This code compiles just fine:
#include <queue>
#include <functional>
std::priority_queue<int> q (std::less<int>{});
whereas this code gives weird compilation errors
#include <queue>
#include <functional>
std::priority_queue<int> q (std::greater<int>{});
| The 3rd template argument for std::priority_queue is std::less by default. So the constructor you are calling is expecting a std::less object. You have to change the 3rd template argument:
std::priority_queue<int, std::vector<T>, std::greater<int>> q (std::greater<int>{});
Passing in std::greater<int>{} is also unneed... |
61,626,046 | 61,626,221 | error in accessing surrounding variable in lambda function | ...
unordered_map<string ,int> map;
for (const auto& str : words) {
map[str]++;
}
auto cmp = [map](string s1, string s2){
if (map[s1] == map[s2])
return s1 < s2;
return map[s1] > map[s2];
};
...
This give me no viable overloade... | Variables captured in a lambda are const by default, unless you mark the lambda as mutable. unordered_map does not have an operator[] that can be called on a const unordered_map object, since it inserts (ie modifies) a new element if the requested key is not found.
Also, you are capturing map by value, you should captu... |
61,626,353 | 61,626,684 | Why does this code not cause a dead-lock? | I have below code where function bar lock the mutex and then called function foo, however function foo lock the same mutex. according to my understanding, dead-lock will take place because foo are trying to lock the same mutex and it has been locked in function bar. But below code executes without any halt. Who knows t... | The POSIX thread specification allows a POSIX thread implementation to use any of the standard three mutex types as the default one:
If the mutex type is PTHREAD_MUTEX_DEFAULT, the behavior of
pthread_mutex_lock() may correspond to one of the three other standard
mutex types
What is PTHREAD_MUTEX_DEFAULT? That's ... |
61,626,523 | 61,637,994 | apache netbeans 11.3 C++ plugin timeout, unable to install | Im moving to Apache Netbeans 11.3 and trying to install the C++ plugin on Windows 10, got the follow repos
http://updates.netbeans.org/netbeans/updates/8.2/uc/final/distribution/catalog.xml.gz
http://bits.netbeans.org/dev/nbms-and-javadoc/lastSuccessfulBuild/artifact/nbbuild/nbms/updates.xml.gz
but everytime it hits t... | Check the Java version
For me, I have Java version 14
So this version has no program
unpack200.exe
Problem was solved by copying the unpack200.exe file from Java version 1.8 to the bin folder in java 14
|
61,626,613 | 61,626,651 | A quick question from a newbie about deleting non-Upper-alpha: why isn't my code working? | Hi I am trying to delete all the non-capitalized alphabet from a string input, but I am not quite sure where the error is in my coding. Please comment if you know why!
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string CreateAcronym(string userPhrase) {
int i;
int stringSize;
char char... |
You cached old string length and continued to use while the string will become shorter by erasing characters.
You skip characters after characters to erase because i++ isn't canceled after erasure.
stringSize = userPhrase.size();
for (i=0 ; i < stringSize ; i++ ) {
charAti = userPhrase.at(i);
if ( !isupper(cha... |
61,626,712 | 61,627,838 | Sqlite3: Select data from timestamp to x minutes | I have a set of data within a database that has a range of entries from a DATETIME timestamp.
I am attempting to write a function that selects everything from a start time, to an end time which is defined by `'x minutes'.
So for example, from my test database data set, I want to select everything from 2020-05-04 04:49:... | The function strftime() is used to format dates.
You should use datetime() like this:
select * from tableTest
where timestamp1 between
datetime('2020-05-04 04:49:02')
and
datetime('2020-05-04 04:49:02', '+2 minutes');
|
61,626,853 | 61,626,931 | Interaction of C++ lambdas and templates | I'm trying to wrap my mind around the interaction of C++ lambda expressions and templates.
This code works as I expect:
#include <iostream>
int bar (int x, int (* f) (int))
{
return f (x);
}
double bar (double x, double (* f) (double))
{
return f (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> i... | May be not what you exactly need but it works with C++11 (as Lambda functions are just syntactic sugar for anonymous functors):
#include <iostream>
template <typename T, typename L>
T bar (T x, const L& l)
{
return l (x);
}
int main ()
{
std::cout << bar (16, [] (int x) -> int { return x * x; }) << std::endl;... |
61,627,167 | 63,550,847 | Runtime Error : Integer Overflow for Complement Number Problem | I have 3 ways of complementing a given binary number. The 1st & 3rd methods do not get any Integer Overflow Error. Can you please explain why the 2nd method gets this run time error?
Here's the code :
int findComplement1(int num) {
if(num==0)
return 1;
int n=num;
int bit=1;
... | TLDR: This is a two's complement arithmetical issue of underflow.
Your error rightly shows that "-2147483648 - 1 cannot be represented in type 'int'". A little background on the integer type might be helpful.
The integer type is a four-byte (32 bit) representation of mathematical integers. Thus it should be able to rep... |
61,627,227 | 61,627,390 | Usage of multimap with next_permutation c++ | i am just trying to implement Knapsack Problem in a Naive way to stress test my original solution.
MY CODE
double StressTest(multimap<int, int> ValWt, int KnapscakWeight)
{
vector<double> TotalValue;
double Temp_KnapsackWeight = 0.0;
double Value = 0.0;
multimap<int, int>::iterator itr1;// = ValWt.begi... | You cannot use std::map or std::multimap (or unordered versions) as std::next_permutation requires:
-BidirIt must meet the requirements of ValueSwappable and LegacyBidirectionalIterator.
but std::multimap values are not swappable as key in the map is not mutable:
value_type std::pair<const Key, T>
(emphasis is mine)... |
61,627,865 | 61,628,589 | SortedArray program not compiling | I am currently having trouble compiling my c++ SortedArray program.I genuinely do not know where my program is wrong and would like to figure out the issue. It would be great if someone could help me out.I am wondering if maybe I am calling my functions improperly due to the pointer but have tried using arrow and dot o... | You have a large number of small problems. To begin in order to overload << you must #include <iostream>
In SortedArray.h, you are missing the << in:
friend std::ostream& operator<< (std::ostream& out, const SortedArray& sA);
In SortedArray.c, you have a non-functioning if at:
if(size==capacity); // remove the ... |
61,628,187 | 61,628,407 | trying to make hash table, program compiles but keeps crashing | I am trying to make hash table, with a class hash that stores string name and int age into tables which are linked list(non standard).
The table array of item pointers stores the head of each linked list.
Adding an item involves updating the last item of the linked list with input name and age.
There aren't any compila... | Your constructor does not allocated the items: It takes a copy of each item in the table
and replaces the value of the copy by a newly allocated item.
Try:
hash::hash()
{
for(auto &x : table){
x=new item;
x->name="none";
x->age=-1;
x->next=nullptr;
}
}
|
61,628,511 | 61,637,161 | find the local time zone’s difference from GMT in minutes | I have timezone in format GMT+09:00 and GMT+10:00. I am using Linux (Open Suse) and C++17.
I am trying to find out the local time zone’s difference from GMT in minutes.
Here is my sample program.
static constexpr time_t const NULL_TIME = -1;
// returns difference in mintues
long tz_offset(time_t when = NULL_TIME) {
... | These strings are known as POSIX timezones and are defined here. This definition says this about the UTC offset:
If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west (which may be indicated by an optional preceding '+' ).
Meanwhile std::put_time is defined in terms of t... |
61,629,171 | 61,629,269 | I want to count the upper-case characters in a string. Why is my code is giving wrong output? | I am working on a programming exercise, "Count of camel case characters" using C++. The goal of the exercise is to count the number of upper-case letters in a given string (what the exercise calls "camel case").
So given the following two inputs:
ckjkUUYII
HKJT
I would expect to get the following counts respectively:... | After entering integer value as t, in input buffer newline character is left. So first call of getline gives you empty string as a result. You have to do:
int t;
cin >> t;
cin.ignore();
while (t--) {
...
}
to consume newline character, then both calls of getline will return entered strings properly.
|
61,629,328 | 61,629,657 | why does this c++ code run on Dev c++ but not on a website? | This code takes input of an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. We have to return the missing numbers.
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
It works totally fine in Dev C++, but when i submit it a website called leetcode, it is giving me the fol... | It only appears to work fine in Dev C++. As the error message of the other compiler says, you have Undefined Behaviors in your code. Jesper has pointer one.
Another one would be the line:
if(nums[i]!=nums[i+1])
During the last iteration i is equal to len-1, so nums[i+1] tries to read num[len] which does not exist.
Yo... |
61,629,879 | 62,687,977 | Why does Intellisense with Emscripten does not find the include path of SDL2/SDL.h? | I'm developing on Win10 a C++ programm for Webassembly.
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <emscripten.h>
int main() {
printf("Hello World!");
}
Emscripten itself creates correctly the .wasm file. But Intellisense in Visual Studio Code shows always the source of #include <SDL2/SDL.h> can't be fou... | Assuming you're using the Emscripten Ports version of SDL2 (via -s USE_SDL=2), you need to add the Emscripten Ports installed include directory to your "includePath".
Typically it is located at .emscripten_cache/wasm-obj/include in your user profile (e.g. C:\Users\PowerNow\.emscripten_cache\wasm-obj\include).
This dire... |
61,630,145 | 61,640,843 | Keep Lua state in a C++ environment to limit context switches | I'm having fun coding simple OpenGL demos and I recently decided to use Lua with my C++ engine in order to change the rendering dynamically without having to recompile on and on my project. Thus I can tweak more easily the rendering algorithm. But I know that my current rendering update functions are probably far from ... | OK, loading the chunk of the update() function into a global variable and having a global parameter table in the Lua script is the way to go. I achieved this using the following guidelines, and I will post the detailed steps below. Basically, loading the script entirely first ensures that all global variables are store... |
61,630,766 | 63,022,664 | How do I resolve sigabrt error on codechef ide | Sigabrt runtime error occurs of a fatal error, because of an assert statement not returning true? Or use of excessive memory, I'm not able to figure out what I'm doing wrong here, help me out?
( problem 1343 C on codeforces) link
so here's the code.
#include <iostream>
#include <stdlib.h>
#include<vector>
using namespa... | I have debugged your code and also the modified code has been accepted for the above question.
Mistakes you made:
1. In the below loop, value at i'th index of vector<int> b is being added to long int s. Instead, b[k] should be added to long int s because the variable being used in the loop is k not i.
for (int k = 0; k... |
61,630,821 | 61,630,888 | C++ Template Error: missing template arguments before ‘=’ token | I am trying to create a function that sets the root node of a LinkedList. However, when I run the following piece of code:
#include <iostream>
using namespace std;
template <typename K>
struct Node {
Node<K>* next;
const K value;
};
template <typename K>
Node<K>* root = NULL;
template <typename K>
void SetRoot(c... | root is a variable template, you need to specify template argument when using it. e.g.
root<K> = &new_node;
// ^^^ specifying K which is the template parameter of SetRoot
BTW: new_node is a local object which will be destroyed when get out of SetRoot. After that root<K> becomes dangled.
|
61,630,837 | 61,631,016 | Why is the simple calculation result differs in python and c++? | I am using a simple dataset to calculate the linear regression between x and y values. I wrote the code both in python and c++. However the output differs a lot due to rounding(I believe) during the operations. The minimum runnable products:
cpp code:
void linear_regression1(){
vector<int> independent;
independ... | You have an integer overflow issue in the code: 60'300 * 60'300 = 3'636'090'000 while usually an int are 4-bytes long and can hold only values in range [-2^31, 2^31-1] = [-2'147'483'648, 2'147'483'647].
Python's integer does not overflow.
|
61,631,784 | 61,631,905 | How to Use Same Class Between Plugins and App in Qt? | I created a plugin in Qt. Plugin Class and App Class use a same class named ShareData.
This is ShareData Class:
//sharedata.h
class ShareData
{
public:
ShareData();
};
//sharedata.cpp
ShareData::ShareData()
{
}
But When I create an instance in plugin class as follows:
//plugin.pro
INCLUDEPATH += $PWD/../echowi... | Plugin should be independent of main application, so you cannot use classes defined in it. Your build error is probably beacuse of shareddata.cpp is not compiled during plugin build.
If you really want use such design I would suggest creation of library for SharedData.
INCLUDEPATH only says that you can use headers of ... |
61,631,956 | 61,631,994 | Concatenation of std::string and int leads to a shift. Why? | Today I was surprised when trying to concatenate an std::string with an int. Consider the following MWE:
#include <iostream>
#include <string>
void print(const std::string& text)
{
std::cout << "The string is: " << text << ".\n";
}
int main()
{
print("iteration_" + 1);
return 0;
}
Instead of printing
Th... |
Does the string for some reason get converted into char[]
Actually it is the other way around. "iteration_" is a char[11] which decays to a const char* when you add 1. Incrementing the pointer by one makes it point to the next character in the string. This is then used to construct a temporary std::string that contai... |
61,632,099 | 61,632,300 | C++ map showing values as 0 for all keys | I am inserting number from a vector in map with key as the number and value as it's (index + 1).
But when I print the contents of the map, value being shown is 0 though I pass interger i.
// taking input of n integers in vector s;
vector<int> s;
for(int i=0;i<n;i++){
int tmp;cin>>tmp;
s.push_back(tmp);
}
//crea... | Your code block following the comment:
// check if number already in map
is logically faulty, because operator[] will actually insert an element, using value initialisation(a), if it does not currently exist.
If you were to instead use:
if (m.find(s[i-1]) != m.end())
that would get rid of this problem.
(a) I believe... |
61,632,168 | 61,634,100 | Vectorization: when is worth manually unrolling loops? | I would like to have a general understanding of when I can expect a compiler to vectorize a loop and when it is worth for me to unroll the loop to help it decides to use vectorization.
I understand the details are very important (what compiler, what compilation options, what architecture, how do I write the code in th... | Short answer, as others said : there is no general guidelines if you do not specify compiler nor target architecture.
As a remark, it is generally better to let the compiler optimize the code these days because it "knows" better the architecture possibilities. There is some cases where unrolling the loops will not be f... |
61,632,340 | 61,632,406 | dynamic_cast fails when cast a base class to derived class | I have two classes, base class and a derived class.
The base class has a virtual method.
Here is my test example:
class Base
{
public:
virtual void Hello() { cout << "-> Hello Base" << endl; }
};
class Derived: public Base
{
public:
void Hello() { cout << "-> Hello Derived" << endl; }
};
int main()
{
Bas... |
dynamic_cast fails when cast a base class to derived class
This is what is supposed to happen. When you dynamic cast a pointer to an object whose dynamic type is not the casted type, then you get a null pointer as the result.
In your example, you indirect through the null pointer and attempt to call a member function... |
61,632,720 | 61,635,115 | QT How to check if key is pressed? | I would like to be able to check if the key is pressed at any time. I imagine such a solution:
void MyQQuickPaintedItem::keyPressEvent(QKeyEvent * event)
{
isKeyPressed[ event->key() ] = 1;
}
void MyQQuickPaintedItem::keyReleaseEvent(QKeyEvent *event)
{
isKeyPressed[ event->key() ] = 0;
}
To check if the righ... | Instead of an array you can use the map, if you are not interested in the order then you can use unordered_maps which is faster. There are rather few keys so I think the program will run fast anyway.
|
61,632,771 | 61,632,950 | CMake target_include_directories does not find #include of private header | I am trying to build a libary with the following directory structure:
lib1
|-include
| |-lib1
| |-public.h
|-src
| |-private.h
| |-private.cpp
| |-public.cpp
|-lib
| |-liblib1.a
|-CMakeLists.txt
were the public header includes the private header to use its functionality.
My CMakeLists.txt looks as follows:
project(m... | If you include a header, then you must tell where that header is. If you say that the header is private, then you aren't telling where the header is to the dependencies. When the dependencies include the private header through the public one, they don't know where it is.
Solution: Make all headers included by a public ... |
61,632,992 | 61,633,034 | Dereferencing an iterator of a list of pointers | I have a problem trying to dereference an iterator of a std::list<std::unique_ptr<MyClass>>.
Here's my situation: in headerFile.h I have
class MyClass{
public:
bool variable = false;
private:
};
and then in headerFile2.h
#include "headerFile.h"
#include <memory>
#include <list>
class OtherClass{
public:
private:
... | operator-> has higher precedence than operator*, so *it -> variable = true; is interpreted as *(it -> variable) = true;, while it -> variable is invalid.
You can add parentheses as
(*it) -> variable = true;
**it.variable = true; has the similar issue; you could (**it).variable = true;.
|
61,633,190 | 61,634,332 | c++ program doesn't execute with `#include<cmath>` | I'm writing a program for my class that solves a few problems one after another. This part:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main() {
ifstream data;
data.open("data.txt");
//LOAD VALUES
int d[200][320];
for(int i=0;i<200;i++){
for(int j=0;... | Including cmath has nothing to do with your issue.
You have undefined behavior called buffer overflow when analyzing data.
Here is live demo with index checking (exception is thrown).
Basically you have messed up order of indexes.
Here is fixed version of your code (with index checking).
BTW your code is very messy, le... |
61,633,234 | 61,636,440 | Using jvm.h from JNI | At the moment I am using the libraries within JAVA_HOME/include in my JNI application. This consists of
classfile_constants.h
jawt.h
jdwpTransport.h
jni.h
jvmti.h
jvmticmlr.h
windows/jawt_md.h
windows/jni_md.h
windows/bridge/AccessBridgeCallbacks.h
windows/bridge/AccessBridgeCalls.c
windows/bridge/AccessBridgeCalls.h
... | Functions declared in jvm.h are for internal JDK use only. They are not supposed to be called from user code. They are not a part of any public API, and they can change in any (even minor) JDK update.
It is possible to call these functions, either by linking your binary against libjvm, or by using dynamic lookup, i.e. ... |
61,633,571 | 61,637,787 | How to resize a cv::Mat in order to use it for a Qlabel (My program throws SIGSEV) | I have a problem when resizing a cv::Mat and trying to use it for a pixmap in a Qlabel.
If I resize the mat and dont use it for the Qlabel, the program works fine, and if I do not resize the mat and use it for the pixmap with that size, it also works fine. The problem comes when I try to do both at the same time, for ... | I solved it by moving the map (where i got my image from) from the class variables to the run() function, so I do not have to resize the map.
|
61,633,686 | 61,633,737 | Indexing operator of an object owned by unique_ptr | I am working on a c++ project. I need to put into a std::vector different classes. I found (Objects of different classes in a single vector?) that it is possible to do this by creating classes with a common type and then putting pointers to the vector. In this case I could cast the pointers to the type I need. This is ... | You need to extract pointer first
A[0] //type: std::unique_ptr<TMyClass>&
Then extract object from that pointer (pointee)
*A[0] //type: TMyClass&
And then you can use your overloaded operators on this object
(*A[0])[0]
|
61,633,781 | 61,633,806 | c++ How to pass an rvalue Reference to another function | I'm using the embedded templated library with etl::queue
https://www.etlcpp.com/queue.html
the etl::queue is quitvalent to std::queue
In order to avoid copying I'd like to actually move the element into the queue.
Now my setup looks like this
bool CETLConcurrentQueue<ElementType_T, u32QueueSize>::Add(ElementType_T &&... | You have to use std::move to convert element to rvalue. As a named variable element itself is an lvalue, even its type is an rvalue reference.
queue.push(std::move(element));
Note that types and value categories are two independent things.
(emphasis mine)
Each C++ expression (an operator with its operands, a literal,... |
61,633,863 | 61,634,061 | A vector in one class being used by another class is failing to store items | I have a Graph class which has populates its Population vector of type Person (another class) with information from a file. The person class has a Conns vector which stores all the people the person has come into contact with. The Graph class also populates the Conns vector in each Person in the Population vector. The ... | Person contacter = findPerson(info[0]); //Get the person object of the "contacter"
Person contactee = findPerson(info[1]); //Get the person object of the "contactee"
//Add the connection to the person
contacter.addConn(contactee)
contacter is a local copy of the Person in population, not the same object. So it adds a... |
61,634,070 | 61,634,146 | Error declaring function with arguments in cython | Figuring out a way of using python functions in c++, I came across python, I am writing a simple fibonacci function which adds n numbers from a particular index in to the given list l. I am a newbie to cython so the error might be trivial :). Please point out what is wrong:
from libcpp.list cimport list
from test impor... | try to change in into another word in the line:
cdef public long long gen_fibonacci(list[int] &l,int in,int n):`
|
61,634,337 | 61,634,338 | When is a requires clause expression required to be parenthesised? (pun by accident) | This gives an error:
template <class T, T A, T B>
requires A > B // <-- error
class X{};
error: parentheses are required around this expression in a requires
clause
requires A < B
~~^~~
( )
Almost all operators give this error (requires A > B, requires A == B, requires A & B... | Yes, && and || are treated special here because constraints are aware of conjunctions and disjunctions.
§ 13.5.1 Constraints [temp.constr.constr]
A constraint is a sequence of logical operations and operands that specifies requirements on template arguments. The operands of a
logical operation are constraints. Ther... |
61,634,342 | 61,634,584 | Overriding C++ pure virtual functions | I have the following classes:
Mode class
h-file:
#pragma once
class Mode
{
public:
virtual int recv() = 0;
};
Mode class
cpp-file:
-> empty
LocalMode class
h-file:
#pragma once
#include "Mode.h"
class LocalMode: public Mode
{
private:
public:
LocalMode();
int recv();
};
LocalMode class
cpp-fi... |
Is the keyword "override" always necessary? If not, what are the best practices?
It is never "necessary". Overriding works with or without this keyword. It is only here to help you prevent issues like typos etc.
struct A
{
virtual int foo();
};
struct B: public A
{
int fooo(); //whoops, not overriding, no co... |
61,634,458 | 61,634,636 | What is the disadvantage if I use objects on the stack instead of on the heap in factory pattern? | CPP codes are as follows:
Operation* OperationFactory:: CreateOperation(char opr) {
OperationAdd resultAdd;
OperationSub resultSub;
OperationMul resultMul;
OperationDiv resultDiv;
switch (opr) {
case '+':
return &resultAdd;
case '-':
return &resultSub;
case '*':
return &resultMul;
case '/':
return &resu... | The pointers your return are useless once the function returns. Similar problem in simpler code:
int* dont_do_this(){
int x = 0;
return &x;
}
x no longer exists once the function returned and you have a dangling pointer. Dereferencing it causes undefined behavior.
It can be fixed by making x static:
int* mayb... |
61,634,593 | 61,635,001 | Simultaneous Union and Intersection between two maps in C++ | While doing a college project I came upon the following problem:
I have two maps (Kmer1 and Kmer2) which are composed by a string(key) and a int(value).
I have to calculate the distance which follows this formula
[1-(I/U)]*100
Where...
...U = the sum of all int values inside Kmer1 U Kmer2
...I = the sum of a... | Add these two loops just after your main while loop.
while (it1 != Kmer1.cend()){
U += it1->second;
it1++;
}
while (it2 != Kmer2.cend()){
U += it2->second;
it2++;
}
|
61,634,723 | 61,932,429 | Dereferencing shared pointer and call by reference | I use some fork of QMapControl and found a bug. GeometryPointImage has getter for image const QPixmap& image() const:
const QPixmap& GeometryPointImage::image() const
{
// Is the image pixmap currently null?
if (m_image == nullptr) { //std::shared_ptr<QPixmap> m_image;
// Have we already constructed the... | Well, I don't expect someone to give another answer to this question by now, so let there be my solution, it may help someone who will face such a problem later:
std::shared_ptr<QPixmap> GeometryPointImage::image() const
{
// Is the image pixmap currently null?
if (m_image == nullptr)
{
// Have we a... |
61,635,042 | 61,639,733 | How can I format a collection as a string efficiently in C++? | I have a program that has a string (which will need to be formatted) and takes a collection of elements from an external source.
The string must be formatted using the elements of the collection, which are std::string.
I can't formatting the string manually, such as:
// Just examples
sprintf(test, "%s this is my %s. Th... | You can do this using {fmt}'s recently added dynamic_format_arg_store (https://github.com/fmtlib/fmt/releases/tag/6.2.0):
#include <fmt/format.h>
int main() {
fmt::dynamic_format_arg_store<fmt::format_context> args;
args.push_back("Hello");
args.push_back("string");
args.push_back("5");
fmt::vprint("{} this ... |
61,635,067 | 61,635,281 | Adding 2 cstring arrays into 1 cstring array | I recently learnt the cstring arrays and wanted to try out a basic operation of adding two strings together, in a normal string using as header you can add string1+string2=string3. But I tried doing this for cstrings and I get an error when I follow this format which is probably not right.
Here is the code, the code i... | First remove this line from code
std::string(fname +" "+ lname);
Second you forgot to add '\0' after you end the string take a look at this code:
int main() {
char fname[100], lname[100], full_name[100];
int i, j;
i = 0; j = 0; // i is index of fname and j is index for lname
cout << "Enter your first ... |
61,635,319 | 61,635,899 | atan2() using two vectors | Below is an example of how we can find the angle in all four quadrant wise using the function atan2.
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int main ()
{
double x, y, result;
x = -10.0;
y = -10.0;
result = atan2 (y,x);
printf ("The arc tangent for (x=%f, y=%f) is %f rad\n",... | To find angle between vectors in 2D, namely angle needed to rotate the first vector to make it collinear with the second one:
angle = atan2(cross(a, b), dot(a, b))
where cross and dot refer to cross product and dot product of vectors. In components:
angle = atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y)
|
61,635,658 | 61,635,911 | Ternary conditional operator inside std::cout | Here's my code:
std::cout << "The contaner is " << (!container)?"not":; "empty";
Which obviously doesn't work but I hope the idea is clear now. I want to print "The container is empty", and to add "not" before "empty" if bool container is false.
I'd like to know if it's possible or if I have to write something along ... | You're almost there. The ternary operator will need the else result, you can use an empty string "", then, due to precedence issues you will need to encapsulate the expression with parenthesis:
std::cout << "The contaner is " << (!container ? "not" : "") << "empty";
|
61,636,014 | 61,680,013 | why define operator<< and >> in a namespace break boost program_options? | from here, if I put the overloaded operator in the namespace it should just work. But I found it actually not working, compiler always complain that it cannot find the << or >>.
In following example, if I turn on the USE_NAMESPACE, compiling fails. But the >> and << actually work outside the program_options. If I turn ... | As mentioned, you need ADL (Argument Dependent Lookup) to succeed.
If you can control POI (Point Of Instantiation) you can also actively use the names from the dedicated namespace instead. In this case, you need to use these names in the TU that defines simple_options before the point that instantiates the parsing code... |
61,636,039 | 61,636,176 | How to check CMake variable in C++ | I have two different CMake builds: one with emscripten and one with regular g++. Based on the build type I want to execute certain c++ code blocks. I'm not sure how to do that.
CMAKE file:
cmake_minimum_required(VERSION 3.15)
project(project)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -W... | CMake variables cannot be accessed in C++. However, CMake can set compiler options, and specifically, macro definitions. Such macros can be accessed by the pre processor. Use the target_compile_definitions command.
|
61,636,120 | 61,636,170 | How to have base abstract class object as class member but accept derived class memebers in constructor? | Setup
I've encountered the following situation in my C++ code (this is an example to illustrate the problem, and has not much to do with the actual code). I have a virtual class Family and two classes that I derive from it:
class Family {
public:
virtual double operator()(double const & x) const = 0;
... | You need to use references or pointers for polymorphism. One possible solution would be:
class Car {
public:
Car(Family* member) : right_seat_(member) {}
private:
Family* right_seat_;
};
int main(){
Mother* lucy = new Mother();
Car Van = Car(lucy);
...//do stuff with car
}
Don't f... |
61,636,277 | 61,636,310 | Weird C++ error, unqualified ID, redeclaration | I want to create a project, I have 3 files, a test.cpp, something.h and a something.cpp. here they are:
test.cpp:
#include <bits/stdc++.h>
#define f cin
#define g cout
#include "something.h"
using namespace std;
int main(void)
{
int x;
register(x);
return 0;
}
something.h:
#ifndef __SOMETHING__H_
#define ... | register is a reserved word in C++. Therefore, you have to give another (unreserved) name.
more information: Register keyword in C++ - Stack Overflow
|
61,636,560 | 61,636,648 | How to connect an AnsiString to a path [C++] | I have this
strcpy (&rZipArchive[strlen(rZipArchive)],"\\"+"char(FileNameLog)", ".zip");
I'm trying to make a path out of it, ZipArchive is a path to a folder but i need to attach to that path "\FileNameLog.zip", FileNameLog contains the date of today 'dd_MM_yy'. The final result i'm searching for is rZipArchive\FileN... | You can format data and store the result as a string via sprintf().
sprintf (&rZipArchive[strlen(rZipArchive)], "\\%s.zip", FileNameLog);
If you know the buffer size(rZipArchiveSize for example), using snprintf(), which accepts output size limit, is safer.
size_t len = strlen(rZipArchive);
if (len < rZipArchiveSize) {... |
61,636,836 | 61,636,938 | 0x20 treated as 0x00 with stringstream | The following program writes 0x20 to stringstream, then reads the value and it's 0. Why is that and how to write a value so it is read as 0x20?
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << (char) 0x20;
char c;
ss >> c;
if ( c == 0x20 ) {
std::cout << "32";
} else if (... | By default, std::stringstream's >> operator skips over writespace. And in ASCII (a typical but by no means universal encoding). 0x20 is the space character you get when you press that long button on your keyboard.
As there is nothing else on the stream, NUL is output to c.
Introducing the manipulator std::noskipws is t... |
61,636,844 | 61,637,264 | How to take input for an array of vectors? | I'm trying to solve a question in which I'm required to create an array of vectors, scan their elements, and fetch an element given two numbers a and b describing its position in the array of vectors. The problem is that I'm not sure how to scan the elements correctly. Just one vector is taking up all of the elements. ... | First a remark: vector<int> v[n]; isn't standard C++, because only arrays with a fixed size on compile time are supported, so avoid it in production code. It does work with most compilers, so I'm just remarking.
For filling in your vectors, you forgot to read the size of the vector to fill.
To avoid 'out of bound' acce... |
61,636,911 | 61,637,240 | Is it possible to compile fmt in vs2010 | I know Visual studio 2010 is outdated and should not be used. I am just curious if it is possible to compile libfmt.a in vs2010?
| As per suggestion from @0x5453, we need to use 4.x versions to build against visual studios.
Thanks
|
61,637,011 | 61,637,170 | How to remove from vector of pairs the value item from pair that is a class in c++? | i am trying to remove all Orders that have old pizza than 3 days :
i have this vector of pairs :
std::vector<std::pair<Client,Order>> x;
x.push_back(std::make_pair(Client(2,"Anca"),Order(3,1)));
x.push_back(std::make_pair(Client(16,"Maria"),Order(1,3)));
x.push_back(std::make_pair(Client(29,"Alex"),Order(1... | Using extra while loop is wrong. The moment you erase first element, end() iterator is invalidated. Fortunately, std::remove (and std::remove_if) can handle any number of elements in a single call.
The second issue is that std::remove can only be used for removing exactly same elements (compared with operator ==). Howe... |
61,637,867 | 61,637,976 | How to do random shuffling of an array | I want to generate numbers between range of 1 to n to create test cases for my program. So i created an array of size n and then stored it in array then usedrandom_shuffle But it's actually not random it always gives same series of number. it changes series like after 3 or 4 shuffling.
So is there any better way to do... | According to cppreference, std::random_shuffle commonly uses std::rand() as randomizer, which would require setting seed with srand() first.
However, std::shuffle accepts the generators from <random> library (which are superior to rand() unless you are using MinGW older than 9.3)
Example of usage from cppreference (li... |
61,637,980 | 61,638,110 | Narrowing Conversion from int to char inside { } | An issue with signedness of char | See the behaviour of char in case of a vector<char> and a standalone char:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> someInts = {2, 3, 1 + 5};
// I can perform operations ^^^^^ inside the braces in this case
// vector<char> someChars = {'a', 'b', 'r' + 'z'};
... | 1+5 is an int so there is no problem using it to initialize a vector<int> entry.
'r' + 's' is an int (236) which is out of range of char on your system. So there is a problem trying to use it to initialize a vector<char> entry. This is exactly the sort of case that the rule about list initialization disallowing narrowi... |
61,638,187 | 61,639,058 | Base class virutal method is being called, instead of child's override implementation | I am writting an ODE integrator with BOOST::ODEINT. It requires that the class with the logic has the operator() overloaded with this signature "void operator()(const std::vector &x, std::vector &dxdt, double t)".
I pretended to write an abstract class which encapsulates the common model logic and the integrator logic,... | Quoting from the relevant documentation:
In odeint all system functions and observers are passed by value. For example, if you call a do_step method of a particular stepper or the integration functions, your system and your stepper will be passed by value.
The problem is that dynamic polymorphism does work only when... |
61,638,512 | 61,638,791 | Initialts algorithm c++11 | I'm trying to write a code which prints out an initials of a string.
But I have a problem in one case, where those names are with more than one
white-space characters.And I came up with an idea to delete those white-spaces characters that aren't necessary and leave only one white space,but I'm not yet confident in ... | It is possible to keep in memory the information if last character was a space or not..
#include <iostream>
#include <string>
#include <cctype>
std::string initials(const std::string &w) {
char space = ' ';
std::string a;
int mode = 0;
for (int i = 0; i < w.size(); ++i) {
if (w[i] == space) {
... |
61,638,747 | 61,642,625 | Default scheduling in OpenMP (gcc compiler) | I am using OpenMP in a C++ progam. According to the gcc documentation, the default scheduling is dynamic with a chunk size of 1 -> https://gcc.gnu.org/onlinedocs/gcc-9.3.0/libgomp.pdf (p22).
I decided to test this so I wrote a simple C++ test program:
#include <chrono>
#include <cmath>
#include <iostream>
#include <omp... | OMP_SCHEDULE and omp_set_schedule() affect runtime loop scheduling, that is for constructs with schedule(runtime) clause. With most OpenMP runtimes, the default scheduling when no schedule clause is present is static with chunk size equal to #iterations / #threads (the handling of the case where #threads does not divid... |
61,639,086 | 61,649,151 | Unhandled exception thrown: read access violation error when accessing dos header of DLL | I am trying to access the dos header of a DLL PE file. I am getting the address of the IMAGE_DOS_HEADER from the PEB of my process. I am getting the address by accessing the PEB, then accessing the LDR and then scanning the InMemoryOrderModuleList until I find the DLL I want to access (on this case the kernel32.DLL), a... |
And your currentitem_InMemoryOrderModuleList is just a pointer to
LIST_ENTRY. And this LIST_ENTRY is a InMemoryOrderLinks field in
LDR_DATA_TABLE_ENTRY. You can adjust pointer to point to enclosing
structure before using.
Refer to "PEB (Process Environment Block) invalid DllBase address", "CONTAINING_RECORD" (W... |
61,639,182 | 61,663,388 | Find the nearest postive definte matrix with Eigen | I am wanting to find the nearest positive definite matrix to some X matrix.
I have seen this answer here: https://scicomp.stackexchange.com/questions/30631/how-to-find-the-nearest-a-near-positive-definite-from-a-given-matrix
But I am having trouble translating that to an answer in Eigen. I have tried the following:
Ma... | The problems that you're not using the right eigenvalue solver.
Since the matrix Y is symmetric by construction, you need to use SelfAdjointEigenSolver.
This symmetry guarantees that your real matrix is diagonalizable and has real eigenvalues and eigenvectors, so you don't have to deal with complex numbers.
The general... |
61,639,285 | 61,640,139 | Erase inside a std::string by std::string_view | I need to find and then erase a portion of a string (a substring). string_view seems such a good idea, but I cannot make it work with string::erase:
// guaranteed to return a view into `str`
auto gimme_gimme_gimme(const std::string& str) -> std::string_view;
auto after_midnight(std::string& str)
{
auto man = gimme... | The string view could indeed be empty, or it could be a view to the outside of the container. Your suggested erase overload, as well as the implementation of the function in your answer relies on a pre-condition that the string view is to the same string object.
Of course, the iterator overloads are very much analogous... |
61,639,510 | 61,642,960 | error: multiple definition of... when defining an extern variable in a third library | I have three libraries:
The first (Lib.h) declares a variable that will be defined elsewhere:
extern int a;
The second one (Lib2.h) includes the third one:
#include "Lib3.h"
The .cpp file of this library (Lib2.cpp) contains nothing besides this:
#include "Lib2.h"
and the third (Lib3.h) finally contains the definitio... | When int a; exists in Lib3.h, then every translation unit that includes Lib3.h (directly or indirectly) will get its own copy of a, hence the error. a needs to be declared in Lib3.h as extern, just like it is in Lib.h, and then the actual int a; variable needs to be defined in a .cpp file elsewhere (Lib2.cpp will suff... |
61,639,551 | 61,639,784 | Where are the statement of or the foundations for the "as if" rule in the C++ Standard? | After a little google search (for instance, site:eel.is "as if rule") I couldn't find a proper place where the so called "as if" rule is clearly stated in the C++ standard. All I could find is that in those places within the standard where it is invoked, the intro.execution reference is given.
But intro.execution doen'... | The definition for "as if" rule is given in the footnote to 4.1.1/1. See http://eel.is/c++draft/intro.abstract#footnote-4:
This provision is sometimes called the “as-if” rule, because an
implementation is free to disregard any requirement of this document
as long as the result is as if the requirement had been obe... |
61,639,577 | 61,639,944 | I have to reverse a string but my code is not producing any output -- C++ | Given a string S as input. I have to reverse the given string.
Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows, first line of each test case contains a string S.
Output: Corresponding to each test case, print the string S in reverse order.
why my code ... | std::string is not resized automatically, that's why res[j]=... doesn't work.
To fix this you can:
replace res[j]=... with res.push_back(...)
specify string size beforehand, e.g. replace string res; with string res(s.size(), '\0');
Also note that in production it would be better to do:
string res = s;
std::reverse(s.... |
61,639,718 | 61,639,791 | Why is std::set_intersection not working? | I have the following code:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
// your code goes here
int t;
cin>>t;
while(t--)
{
string a;
string b;
cin>>a;
cin>>b;
vector<char> v1(a.begin(),a.end());
vector<char> v2(b.begin(),b.end());
sort(v1.begin(),v1.end... | It doesn't work because c is empty. This means that c.begin() be equal to c.end(), and dereferencing an end iterator leads to undefined behavior.
You need to insert the elements in the vector, for example by using std::back_inserter:
auto ls = set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(c));
... |
61,639,803 | 61,640,209 | std::priority_queue contain struct with functor that contains a state | There exists two excellent answers to questions about std::priority_queue containing struct/class:
What if I need those compare structs to hold a state, such as an object of ofstream?
Thanks in advance.
| You can define compare functor with constructor requiring state:
struct Compare
{
State state;
Compare(State state)
: state(state)
{
}
bool operator()(const Item& a, const Item& b)
{
... // use state
}
};
and pass its instanc... |
61,639,929 | 61,656,046 | Resizing QLabel using QSizeGrip | Actually I want to create a QLabel which can be resized by the user, So I found the QSizeGrip class which is used to resized parents window, but actually I want to use this QSizeGrip on my label so that using that grip user can resize my label but the problem I am facing is that this grip when i use with my label resiz... | Use
setWindowFlags(Qt::SubWindow);
That statement after creating QSizeGrip object, This flag will sit this grip to resize the QLabel insted of the widget window.
|
61,639,962 | 61,640,222 | Convert std::tuple to std::variant recursively | Need an idea on what technique to use to declare std::variant type containing all the types included into a given std::tuple and its sub-tuples (if an element is also a tuple) recursively.
For example,
std::tuple<int, std::tuple<int, double, std::tuple<float, double, std::string>>>
transforms into
std::variant<int, d... | With Boost.Mp11, this isn't so bad.
The first step is to recursively flatten the input list. We have mp_flatten, but that only does a single flattening - we need to invoke it recursively. There may be a better way to do this, but the best I've come up with so far is to use mp_iterate with a function that flattens only ... |
61,640,014 | 61,656,530 | How to forward output of a directshow app(C++) to a C# app? | I am making a C# app to capture graphic from an avermedia pcie capture card.
But it seems that there are no out of box tools to do so.
So I made a C++ directshow app to do the capture, which is a console app and opens a capture window when running.
How can I redirect the output to a C# app? for example, to a CaptureEle... | So you want to have XAML CaptureElement connected to AverMedia PCIe capture card. This sounds like a well-understood challenge overall, however every other piece of technology you mentioned is eventually a bad choice: DirectShow, multiple apps with piping, redirection and fitting of cutsom code to XAML CaptureElement c... |
61,640,027 | 61,640,172 | Struct char array member initialization in C++ | I'm trying to understand struct initialization in C++, in special char array member:
struct S {
int x;
char str[16];
};
// (1) This would be the desired way: simple and compact, but doesn't work
S s1={.x=12, .str = "Hello2"};
// (2) Instead, this appears the correct way to do, but it is ugly and cumbersome fo... | just replace
S s1={.x=12, .str = "Hello2"};
by the 'C' initialization form
S s1={12, "Hello2"};
or as said in remarks use a std::string which is a most elegant, concise and practical way than an array of char for a string, and you will able to use the 'C++' initialization form you wanted
|
61,640,112 | 61,655,425 | Function to calculate angle to a point in unusual 2D space | I'm looking for a robust function to calculate the difference(delta) between an object and a point.
For example, it there was an object at point A with an orientation of 1.2 Rad, what would be the required angle for the object to turn in order to face Point B.
Furthermore, I'm working in a odd coordinate system where n... | Here's the answer.
float Robot::getDeltaHeading(float _x1, float _y1, float _x2, float _y2, float _currentHeading) {
_currentHeading -= 90;
double Ux = 0.0, Uy = 0.0, Vx = 0.0, Vy = 0.0, d = 0.0;
d = sqrtf(powf(abs(_x1 - _x2), 2) + powf(abs(_y1 - _x2), 2));
Ux = (_x2 - _x1) / d;
Uy = (_y2 - _y1... |
61,640,518 | 61,640,645 | C++ primer 5 ed. mutual conversions | I have some difficulty to understand mutual conversions, it is explained in C++ Primer 5 ed.:
"In the following example, we’ve defined two ways to obtain an A from a B: either by using B’s conversion operator or by using the A constructor that takes a B:// usually a bad idea to have mutual conversions between two clas... |
But when I defined the required members and f I don't get any error!
The shown program is ill-formed for the reasons described in the book. If a compiler fails to issue a diagnostic message, then the compiler does not conform to the standard.
I am using GCC.
You can ask GCC to try to conform to the C++ standard us... |
61,641,003 | 61,642,593 | Dangers of using reference-to-pointer as function argument | Can someone tell me if this is safe, because I think it isn't:
class A
{
public:
A(int*& i) : m_i(i)
{}
int*& m_i;
};
class B
{
public:
B(int* const& i) : m_i(i)
{}
int* const & m_i;
};
int main()
{
int i = 1;
int *j = &i;
A a1(j); // this works (1)
A a2(&i); // compiler... | A's constructor takes a non-const reference to an int* pointer. A a1(j); works, because j is an int* variable, so the reference is satisfied. And j outlives a1, so the A::m_i member is safe to use for the lifetime of a1.
A a2(&i); fails to compile, because although &i is an int*, operator& returns a temporary value, ... |
61,641,146 | 61,641,313 | C++ multiple nested If-else statements work but combined doesn't | I'm a newbie to c++. I attempted a questions related to bitsets(https://www.codechef.com/problems/CHEFQUE),
when I use the following nested statements the code passes all the tests
for(int i=1;i<Q+1;i++){
temp = S/2;
if(S&1){ //odd
if(!sets[temp]){
sets[temp] = true;
... | As you can see from this table the operator ! has a higher precedence that & (Bitwise and, not address of), so your code should looks like this:
for(int i=1;i<Q+1;i++){
temp = S/2;
if(S&1 && !sets[temp]){ //odd and empty
sets[temp] = true;
sum+=temp;
}
else if(!(S&1) && sets[temp]){ ... |
61,641,174 | 61,641,670 | Unable to link the grpc libraries in Windows | I have installed grpc:x64 using vcpkg in windows and I am trying to compile the basic greeter server program. But it is giving me linking errors. Even though the find_package command is able to find the grpc package, I suspect that the library paths are not set properly. I am not able to figure out the exact reason for... | Figured out the missing library. gRPC::grpc++_reflection needs to be added in the dependency list.
|
61,641,381 | 61,641,651 | C++ - Reading from a file bug | My program is working as I want it to work (It is on Bosnian language so the cout of the program is not that important). The program is about reading some text from file and then couting what I want to
The only problem I have with this program is that for some reason it is showing the two 0 0 at the end of the text fil... | You are seeing the extra 0 0 at end most likely due to an extra empty line at end of proizvodi.txt.txt file. This happens because the new line is also accepted as input but since there are no entries, the entries in struct proizvod retain default 0 values for cijena and kolicina which gets printed out as 0 0.
Update yo... |
61,641,404 | 61,641,478 | How to Print 7 Days of week by taking user input? | The Issue is when first time I run my Program and enter 5 than program will return Friday and after this press y to restart the operation without closing the console and enter 9 the program will return the default error message and will also return Friday which is a bad error in my code and I cannot Identify what makes... | The Day function is supposed to return a string. However, you are not returning a string in the default case of the switch statement, which invokes undefined behaviour (in your case, the function returned "Friday", but anything can happen).
You need to return something for the program to be well-defined:
string Day (D... |
61,641,689 | 61,661,814 | thrust::device_vector of struct throw Bus Error | When attempting to create a thrust::device_vector of a struct I get a Bus error (core dumped). The strange part is that the code below runs fine on my laptop (Quadro P2000). However, when I port this code on to a Jetson TX2 (tested in two different ones), the error shows up. I'm attaching a simple code that can reprodu... | Will answer my own question here. Thanks to @talonmies advice, the issue came from using managed memory. The TX2 has a different managed memory model that cause my code to fail. Using cudaMalloc instead of cudaMallocManaged fixed it.
|
61,641,986 | 61,642,188 | Correct definition of explicit default constructor with enum and template arguments | I have a base class Method with subclasses.
auto harmonic_force = [](const double& q, const double& k){return -k*q;};
enum SplittingAB{ SS,L42 };
class Method
{
public:
~Method() = default;
virtual void evolute( std::vector<std::pair<double,double>> &qp, int T) const = 0;
};
template <typename Function>
cla... | Issue 1
The compiler rightly reports an error since you are trying to intialize a Function& with a Function const&. If allowed, it won't preserve the const-ness of the original object.
Unless performance is a proven issue for your use case, change
Function& force;
to
Function force;
Issue 2
Add code to initialize... |
61,642,214 | 61,725,421 | Visual Studio deletes a shared .pch file, and questions about custom build steps | I try to use a shared .pch file, which is compiled in one project and used in others.
However the .pch file is deleted if a .pdb filename of the PCH project differs from .pdb filenames of the other projects.
This page doesn't answer the question: https://devblogs.microsoft.com/cppblog/shared-pch-usage-sample-in-visual-... | For some reason (I did this or not) the generated by compiler .pdb file was not $(PlatformToolsetVersion).pdb, but $(ProjectName).pdb . So the copied into other project folders shared .pdb file was pch.pdb in my case, while other projects were expecting different names. And that was triggering a DELETE task in Microsof... |
61,642,231 | 61,642,384 | Assigning a 2d array pointer parameter to a local array pointer variable | I am a little bit confused about how to assign a 2d array pointer parameter to a local 2d array pointer variable. Check the code below.
#define N 5
#define M 6
void print(int (*arr)[M][N]) {
int *localArr[M][N];
localArr = arr; //error C3863: array type 'int *[6][5]' is not assignable
//localArr[0][... | the local declaration has to be like this way,
int (*localArr)[M][N]; //pointer to an MxN array
//int * localArr[m][N];//An MxN array of pointer to int
|
61,642,574 | 61,686,976 | Difference of C++17 and C++20 in template friend function with unary and binary operators | I have the following MWE in C++20 with clang++ -std=c++2a, in which I defined in-class unary - operator and friend-ed binary - operator:
template<typename T>
class vec;
template<typename T>
vec<T> operator-(const vec<T>&, const vec<T>&);
template<typename T>
class vec {
public:
vec() {}
vec operator-() const ... | This is due to the way name look-up proceeds inside class context. Look up for names inside friend declarator are looked-up as in any member declarators. The pertinent lookup rules that apply here are:
[basic.lookup.unqual]/1:
In all the cases listed in [basic.lookup.unqual], the scopes are searched for a declaratio... |
61,642,728 | 61,652,691 | How to effectively copy data from 2D host array (with padding) to 1D device array and remove the original padding in CUDA? | I have a 2D column major array on the host with padding, for example:
|1 4 7|
|2 5 8|
A_h = |3 6 9|
|x x x|
|x x x|
and I want to copy the data to device memory as 1D array:
{1, 2, 3, 4, 5, 6, 7, 8, 9} //preferred
or
{1, 2, 3, 4, 5, 6, 7, 8, 9, x, x, x, x, x, x}
... | If the use case is only copying a subset of a larger source into a smaller destination which isn't strided (so contiguous), then a conditional copy with a predicate is probably the simplest approach (I guess gather would also work). Something like this:
#include <vector>
#include <iostream>
#include <thrust/device_vect... |
61,642,816 | 61,643,085 | How can I specialize a standard concept for my own class? | I have a template function that should work for all integral types:
#include <concepts>
template<typename T>
bool odd(T n) requires std::integral<T>
{
return n & T(1);
}
Now I want to use this function with some user defined integral type, e.g. boost::multiprecision::cpp_int
#include <boost/multiprecision/cpp_int.hp... |
how can I specialize a standard concept for my own type?
You don't. Concepts can't be specialized. Type traits can be under certain circumstances, but std::integral isn't one that you can, so that's not the right route either.
What can I do to fix this
You need to come up with the right concept for the set of algor... |
61,643,526 | 61,643,624 | While loop bug with cout and cin in c++? or is it | So basically I was making a chat app and then I came across to a bug i couldnt fix. for purpose of not leaking my source code here is an example of it:
#include<iostream>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
cin >> lol;
}
return 0;
}
s... | That's no bug, that's the way it works.
The operator>>() for std::string separates by whitespace, so you effectively get one word at a time.
If you'd like to read an entire line, use std::getline().
|
61,643,700 | 61,643,762 | C++ friend operator overloading cin>> | I am replacing a Read in function with a friend operator. I am having trouble referencing the friend operator in a void function. I am receiving and error "No member named 'Read' in Date" in the void GetDates function. Does anyone know how to fix this? Thank you!
Question 2:
I am now using cout<< operator but I am rece... | Read is the name of the stream that you are extracting from. An example of a stream that you can read from is cin. You need to replace this line:
l[i].Read(); //ERROR HERE
with
cin >> l[i];
Inside operator>> the cin object is now called Read.
The issue with your operator<< is that it needs to be declared as a friend... |
61,643,879 | 61,644,206 | Trying to insert a node at a given position, however I'm getting stuck in an infnite loop | I'm trying to add a node at a given position in a linked list, however I'm stuck in an infinite loop for some reasons. When I run the following code, the cout statement in the loop keeps outputting forever. Is this issue happening because I'm doing the loop wrong, or it is because I messed something up with how I used ... | Well, do it like this:
while(inc < position)
{
// print data
cout << endl<< "NEXT: " << temp -> data;
// increment temp to point to next
temp = temp -> next;
inc +=1;
}
Your code is:
temp -> next = temp;
temp = temp -> next;
these line makes it going over same same data again and again. K... |
61,644,583 | 61,661,972 | CMake MacOS frameworks not being linked properly? | Using CLion IDE and CMake to compile my project with c++ and a couple objective-c++ classes.
My problem arose because I need to include CoreFoundation in my project for my class in a .mm file to inherit from NSObject
After much digging, I think I found the modern CMake way of linking MacOS frameworks (CoreBluetooth, Co... | Okay after going on several wild goose hunts and layers and layers of digging, I finally found a solution. I printed out the location of CoreFoundation to make sure it was being found correctly and the directory is good:
find_library(FoundationLib CoreFoundation)
message("LIB: ${FoundationLib}")
-> /Library/Developer/... |
61,644,627 | 61,645,111 | memory viewer, padding values | I'm trying to dump some memory values through an injected module in a target process.
uintptr_t moduleBase = (uintptr_t)GetModuleHandle(NULL);
if (fout) {
for (int i = 0; i < 8; i++)
{
std::cout << std::uppercase << std::hex << moduleBase + i << ": ";
unsigned int c = ((int*)(moduleBase))[i]... | You'll have to iterate over the bytes that make up the value returned by SwapEndians(c) and print them one by one. A function template can be used for that.
template <typename T>
void writeBytes(std::ostream& out, T t)
{
out << std::uppercase << std::hex << std::setfill('0');
uint8_t* bp = reinterpret_cast<uint8_... |
61,644,691 | 61,693,177 | How to change the standard items selection QlistView | i have QListView I assigned him my modeland delegate in which I redefined the method paint(..):
void PlainDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QRect rect = option.rect;
QLinearGradient gradient(0,0,rect.width(),rect.height());
if (option.s... | You can do it via CSS.
Look at this (in file css or QWidget::setStyle(QStyle *style)):
QListView::item:selected
{
border: 1.2px;
border-color: #273e51;
border-style: outset;
...etc
}
QListView::item:selected:!active
{
}
QListView::item:selected:active
{
}
QListView::item:hover
{
}
look at th... |
61,644,823 | 61,645,945 | InitializeCriticalSection works in one project, but fails in another | Using Visual Studio 2019 Professional on Windows 10 x64. I have several C++ DLL projects, some of which are multi-threaded. I'm using CRITICAL_SECTION objects for thread safety.
In DLL1:
CRITICAL_SECTION critDLL1;
InitializeCriticalSection(&critDLL1);
In DLL2:
CRITICAL_SECTION critDLL2;
InitializeCriticalSection(&crit... | If your program crashes under WPO (an optimization that assumes that whatever you are compiling is the entire program), it means that either the assumption is incorrect or that the optimizer ends up exploiting some undefined behavior that previously didn't (without the optimization applied), even if the assumption is c... |
61,644,875 | 61,644,960 | Problem with, ESP8266WebServer::on(const char [6], <unresolved overloaded function type>)' | I'm learning how to use 'class' in C++, and when I'm trying to call a function from my class I'm getting this error:
Error
C:\Users\Mateus\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WebServer\src/ESP8266WebServer.h:90:8: note: void ESP8266WebServer::on(const String&, HTTPMethod, ESP8... | Looks like you need a lambda function, similar to your previous example
server.on("/Lg1", [](){ l1.toggleLight(); });
|
61,644,911 | 61,645,042 | Why do you need to recompile C/C++ for each OS? | This is more of a theoretical question than anything. I'm a Comp sci major with a huge interest in low level programming. I love finding out how things work under the hood. My specialization is compiler design.
Anyway, as I'm working on my first compiler, things are occurring to me that are kind of confusing.
When you ... |
Don't we target the CPU architecture/instruction set when compiling a C/C++ program?
No, you don't.
I mean yes, you are compiling for a CPU instruction set. But that's not all compilation is.
Consider the simplest "Hello, world!" program. All it does is call printf, right? But there's no "printf" instruction set opco... |
61,644,973 | 61,645,132 | Set value of temporary std::future | I have a function which returns a std::pair<std::future<bool>,std::future_status>. In some cases I want future.get() to always return true and I was wondering if there was a legit way of doing it. Currently I am doing something horrendous:
std::future<bool> tmp = std::async(std::launch::async,[]()->bool{return true;});... | I'm not sure what effect you're trying to achieve, but you can use a std::promise to directly set the value of a std::future:
#include<future>
std::promise<bool> tmpPromise; //default construct promise
std::future<bool> tmp = tmpPromise.get_future(); //get future associated with promise
tmpPromise.set_value(true); /... |
61,645,259 | 61,645,451 | Conversion from ARGB to RGBA | I'm trying to write my own Color struct for a task I have.
My goal is that my buffer will always contain a RGBA value, even if it is initialized with ARGB values.
I have 2 constructors:
Takes R,G,B,A values of type uint8_t separately - Works like a charm.
Takes a uint32_t that holds an ARGB value - The problem begins ... | Looks to me that the class is holding an ABGR value, so obviously a conversion from ARGB to RGBA isn't helpful. This seems right (untested though).
inline uint32_t fromArgb(uint32_t argb)
{
return
// Source is in format: 0xAARRGGBB
((argb & 0x00FF0000) >> 16) | //______RR
... |
61,645,278 | 61,645,484 | Why can't I make a external type appear like an inner type in c++? | I want to maintain an existing API that heavily uses an inner enum but I need to separate the enum out into its own type:
This is the current API:
class Outer {
public:
enum Inner {
FIELD1
};
};
In other words, users currently expect to set Inners by using Outer::Inner.
I would like to preserve the n... | This is not allowed because of the rule [basic.scope.class]/3:
A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.
When you do typedef Inner Inner;, you're violating this rule. The firs... |
61,645,444 | 61,646,420 | Implementing an iterator class for a my linked list. What is the using keyword? | I believe this is relatively new that an iterator class is required to have the following tags at the top of the class:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = int;
using pointer = T*;
using reference = T&;
Why are these necessary and what are they doing... | The using keyword is new in C++11.
In this instance, it's being used as a replacement for typedef.
Instead of writing:
typedef T value_type;
You can write this to get the same result:
using value_type = T;
See What is the logic behind the "using" keyword in C++? for more info.
|
61,645,527 | 61,645,596 | How can I do a dot product between a matrix and a vector in c++ | There are a function called inner_product, but I failed miserably in use that. I'll need to use this function several times for different matrices and vectors. Bellow my current code:
std::vector<vector<int>> matrix_a = {{0, 0},
{0, 1},
{1, 0},
... | You are trying to use pointers to begin and end of a vector of vectors, inner_product requires pointers to beginning and end of a vector.
Also, vectors have their own iterators, you can use them instead of std::begin and std::end.
Live demo
#include <iostream>
#include <numeric>
#include <vector>
//passing vectors by ... |
61,645,582 | 61,646,070 | Any issues calling Boost C++ ASIO function close() concurrently with an async_write() on the same socket? | According to the MSDN doc for closesocket:
"A Winsock client must never issue closesocket on s concurrently with another Winsock function call."
For example, what happens if an IO completion thread detects an error and closes the socket:
client_socket_.lowest_layer().close(ec);
while concurrently another thread is abo... | If you use a strand¹ there's no real problem, though I'll submit that it's probably cleaner (much cleaner) to invoke shutdown() before/instead of close() in many scenarios.
Asio does requires you to synchronize access to the socket/stream objects (everything other than the documented thread-safe objects as io_context a... |
61,645,642 | 61,645,923 | C++ unit testing for multiple cpu architectures | we develop an app in C++ for ARM and x86 architectures. Of course we integration test our app for both architectures but for now we unit test our app only on x86. Is this a possible error source and is it normal to run unit tests for all supported architectures?
| In theory, as long as your code only uses C++ and you have no undefined behavior, the code should behave the same on all compliant platforms. That's what the standard is supposed to do.
In practice little code is completely contained (you might use libraries or drivers that can behave differently on different platforms... |
61,645,787 | 61,650,744 | OpenPose: E0312 / no suitable user-defined conversion from "fLS::clstring" to "const op::String" and other errors | my NB crashed a few weeks ago and what was working well on my Linux Ubuntu, now does not. I need to install and make OpenPose working on my second notebook (the one from my job). Unfortunately, here I have only Windows 10 and it is not possible to install other OS. I was not able to make working correctly CMake, so I'v... | I assume you are using the latest OpenPose. From OpenPose 1.6.0 several changes are done in the code such as op::String as a container of std::string.
Given very limited information in the question, I propose the following
workarounds-
You may checkout OpenPose 1.5.1 by executing git checkout tags/v1.5.1
If you wan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.