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 |
|---|---|---|---|---|
62,713,846 | 62,714,013 | Can multiple 'const reference' variables share the same memory? | I'm wondering if there's a memory cost to having multiple "constant reference" variables in the same scope pointing to the same object:
const Animal& animal = getAnimal();
const Dog& dog = static_cast<const Dog&>(animal);
Conceptually, animal and dog are two variables, each of pointer size, and thus would take up 2 re... |
Does the C++ standard allow it?
Sure, why not. There is no way you could tell the difference. The so-called "as-if rule" allows compilers to do any optimization as long the observable behavior is the same as if it didn't do any optimizations (side note: there are exceptions, where optimizations are allowed to change ... |
62,713,884 | 62,714,469 | How to convert Hex string to text data in C++ | I have a variable which is giving data in hex strings as follows: 68 73 2d 3c 40 40 9d 46 3c....
I want to convert this data to text format.
I have a some code. this code is giving false and unreadable data.
int hex_value(char hex_digit)
{
switch (hex_digit) {
case '0': case '1': case '2': case '3': case '4':
... | in this case the stl class stringstream may be useful:
std::string hex_to_string(const std::string& input)
{
std::string output;
std::istringstream iss(input);
iss.setf(std::istringstream::hex, std::istringstream::basefield);
while (!iss.eof()) {
unsigned int n;
iss >> n;
if... |
62,714,138 | 62,714,389 | I have a GUI for my program that saves a config file, how can I double click on this config file to load the GUI directly with the config data? | So I have this program written in C++, and I created a GUI application (using Qt5) for it that runs on Windows.
On the GUI, you can enter some data (for e.g. Name, Age, Date,...). With this data some processing can be done.
The GUI is able to serialize and save the data I entered (Name, Age, Date..) into a binary or te... | There is probably more than one way to implement this feature. Here is what I would do:
Make a unique file type for the config file (a dot extension like .myappconf or something like that should do it)
Create a file association for your application with that file type. This is typically done in the installer or in the... |
62,714,379 | 62,749,326 | How to draw over an existing dotted line with a wider one? | I want to draw over an existing dotted line (left black) with a boulder line (right green) to simulate selection effect,
but the strokes of a bolder line are not aligned with the original one
even though they are painted using the same start/end points p1 and p2:
Here's the code:
const QPointF p1{};
const QPointF p2{}... | According to Qt docs:
The dash pattern is specified in units of the pens width
Which means we'd have to calculate ratio between width of both lines like this:
QPen pen;
const double penWidth(pen.widthF());
const auto penDashPattern(pen.dashPattern());
QPen boldPen(pen);
const double boldPenWidth(penWidth + 2);
auto ... |
62,714,546 | 62,716,088 | Using QTextStream stops std::cout working | Using Qt (v5.15.0) in Visual Studio 2019 with the Qt VS Tools extension installed. Simple console application. Below is a simple demonstration of the problem:
#include <iostream>
#include <QDebug>
void main()
{
std::cout << "cout: Line 1\n";
qDebug() << "qDebug: Line 2";
std::cout << "cout: Line 3\n";
... | On my computer (visual studio community edition 2019 and QT 5.9.9) this compiles and prints every line including line 7.
If you want to make sure the buffer is flushed at line 7 you can use :
std::cout << "cout: Line 7\n" << std::endl;
but you'd have to use it every line you want to be certain to be flushed.
Alternati... |
62,714,848 | 62,715,233 | Is there a way to pass by value all the sub-classes of an pure abstract class to a function in C++? | Say I had 2 classes A and B, where A is a pure abstract class with a pure virtual function and B inherits from A and implements the pure virtual function. If I then have a function g() that I want to pass any instance of a subclass of A by value to (so I could mutate it without changing the original instance), how woul... | I think the best practice here is to leverage clone() method:
#include <iostream>
#include <memory>
class Base
{
public:
virtual void set_str(std::string) = 0;
virtual void print() = 0;
virtual std::unique_ptr<Base> clone() = 0;
};
class Derived: public Base
{
private:
std::string _str;
public:
st... |
62,714,864 | 62,715,477 | Does struct with reference member have unique object representation? | This answer raised the following question.
Suppose we have a simple
struct S {
int& i;
}
Internally (in GCC and Clang, at least) S contains just a pointer to an int, and
static_assert(sizeof(int*) == 8);
static_assert(sizeof(S) == 8);
Does S have a unique object representation? GCC and Clang disagree *:
static... | Firstly, references are not objects. Objects are specified in [intro.object] and references in [dcl.ref].
Subobjects are objects ([intro.object]). Therefore reference members are not subobjects and therefore a class containing only reference members (and no bases) has no subobjects (even though it has data members).
[... |
62,715,202 | 62,715,264 | invalid conversion from 'int' to 'int*' CPP | #include <iostream>
#include <cstring>
#include<bits/stdc++.h>
using namespace std;
int static t[1000][1001];
int solve(int arr[],int i, int j)
{
if(i>=j)
return 0;
if(t[i][j]!=-1)
return t[i][j];
int mini=INT_MAX;
for(int k=i;k<=j-1;k++)
{
int temp=solve(arr,i,k)+solve(i,k... | The expression solve(i,k+1,j) is wrong - the solve function expects a pointer to int as its first argument which is expected to point to an array, but you just pass an integer i.
|
62,715,357 | 62,715,431 | Overloaded less then operator returns the opposite boolean value | I overloaded the less then operator in my Booking class.
#include <iostream>
using namespace std;
class Booking{
private:
long bookingID;
public:
Booking(long bookingID) : bookingID(bookingID){}
long getBookingID(){
return bookingID;
}
bool operator<(Booking &b){
return this->bookingID<b.getBookingID();
}
}... | You are comparing pointers, not objects.
What you mean is:
Booking b2( 11);
Booking b1( 2);
cout << (b1<b2) << endl; // returns 1, as expected
cout << (b2<b1) << endl; // returns 0, as expected
|
62,715,363 | 62,715,946 | Error opening a file residing under "/sys/" in C/C++ | I cannot read from a file resides under /sys(to be precise /sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:01/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/capacity).I've tried both using the C method(fopen and fread) and the C++ method(std::ifstream).Here's what I've done so far :
//headerfile.h
protected:
char m... | m_path probably contains a newline character (\n) at the end, as fgets does not remove it. Overwrite the first newline character at the end with a 0-byte.
That method to find the file name is pretty ugly and depends on external tools; I'd recommend searching for the file directly in the C++ code (possibly using the std... |
62,715,636 | 62,716,450 | Regex with multiple character separator | I have this string
options{Red | Blue | Green}
And I want to capture the options inside the curly braces one by one. So far I was able to capture the inner part, but I don't understand how to set the pattern SPACELINESPACE | as a separator and capture Red Blue and Green.
For capturing the string inside the curly brace... | Could you use something like:
\w+(?=[^{]*?})
EDIT 1: OP mentioned in the comment below:
"what if I have something like this, options{Red | Blue | green },users={ Paul | Ringo | John | George}? I want to capture just the options."
I'm unsure what flavor is used, but the below pattern will negate the substrings that ... |
62,715,815 | 62,735,522 | How to use copy elision when function is called in if block | In the following snippet, no move and no copy of A happens thanks to copy elision
struct A;
A function1();
A function2();
int main(int argc, char**) {
if (argc > 3) {
A a = function1();
} else {
A a = function2();
}
return 0;
}
This is nice, however a is not accessible outside the if-block. When decla... | Immediately-Invoked Lambda Expression (IILE) can save the day in this and more complicated cases:
A a = [&] {
if (…) {
return function1();
} else {
return function2();
}
}();
|
62,716,242 | 62,716,532 | implement iterator over file | I want to create a class with a loaded file and implement an iterator for given class to iterate over it with range iterator
Here is my class
class Csv
{
public:
explicit Csv(std::string filepath);
~Csv();
void load_new_file(std::string filepath) {}
private:
std::ifstream file;
};
Here is a behav... | Minimal example that uses std::getline:
class End_iterator {};
class Iterator {
public:
Iterator(std::ifstream& file) : file_{file} {
next();
}
const std::string& operator*() const {
return str_;
}
Iterator& operator++() {
next();
return *this;
}
bool oper... |
62,716,542 | 62,717,345 | What does the expression "b=(b-x)&x" mean? | Given that x is a set, the following code goes through the subsets of a set x:
int b = 0;
do {
// process subset b
} while (b=(b-x)&x);
I came across this reading about bit manipulation and how it's used to represent sets.
What does the expression b=(b-x)&x mean? How does it work?
I'm familiar with == but not with = ... | Easy parts first:
Does the loop terminate when the value of (b-x)&x becomes zero? I'm familiar with == but not with = being here in the do while loop. How does that work?
Yes.
A do/while loop like this:
do{
cout << b<<"\n";
}while(b = (b-x)&x);
does the following steps:
Execute cout << b<<"\n";.
Execute b = (b-... |
62,716,743 | 62,717,634 | std::ofstream as class member deletes the copy constructor? | the following code only compiles when I remove the definition of the destructor of class Test or when I remove the std::ofstream member. Otherwise I get an error telling me that the copy constructor of Test has been deleted.
Can someone explain why that is? Thank you!
#include<fstream>
#include<vector>
class Test {
pu... |
If it is only about the deletion of Test's copy constructor because of std::ofstream not being copyable, why does this compile?
The reason that the "empty" destructor stops you is that declaring a destructor suppresses the implicit generation of a move constructor, so std::vector<Test>::emplace_back has to copy Test ... |
62,716,782 | 62,723,452 | Android rebuilds static library when the binary is compiled | I have a binary in Android that links to a static library A. Static library libA depends on multiple shared libraries.
The binary does not do anything except it imports a class from the static library and executes a simple function.
However, the binary fails to build except I link against the same shared libraries to w... | According to the error message, the compiler cannot find a header file in its header search path. Header includes are resolved during the preprocessor stage, therefore this is not a linking problem. The preprocessor runs at the beginning of compilation, the linking is done at the end.
From your description, I understan... |
62,716,810 | 62,716,877 | The c++ using statement within a function, followed by a function name (for ADL?) | What is the copy-and-swap idiom?
in this question, in the top answer, within the section where the swap public friend overload is implemented, the implementation makes use of this:
friend void swap(dumb_array& first, dumb_array& second){
//the line of code below
using std::swap;
//then it calls the std::swa... | The using statement makes this line work:
swap(first, second);
Notice that we can omit std:: in front of swap.
The important thing there is that std::swap(...) is a qualified lookup, but swap(...) is an unqualified lookup. The main difference is that qualified lookup is calling a function in a specific namespace or sc... |
62,716,983 | 62,717,749 | How to Replace character in c++ without using library | I have prototype - int replace_char(string &, char);
I can't use library from string and ctype.h, I should write my own function.
So the task is to find in the text caharacter, which should I should replace with "*" .
example: In This is my text .
replace all t to * . Result will be - *his is my *ex*.
#include <iostr... | There were several errors in the code:
The function signature mismatches, the prototype is defined as std::string& but in the function definition, std::string only was used.
The program never converted the capital letter T or anything which is capital in order to convert them before comparing each letter with a singl... |
62,717,067 | 62,717,228 | Why is volatile int convertible to int but volatile T is not convertible to T? | Consider the following code:
#include <iostream>
#include <type_traits>
struct type {};
int main(int argc, char* argv[]) {
std::cout << std::is_convertible_v<volatile int, int> << " ";
std::cout << std::is_convertible_v<volatile int, volatile int> << " ";
std::cout << std::is_convertible_v<volatile type, ... | The implicitly-declared default constructor for type has this signature
type::type(type const&);
The reference cannot bind to a volatile object, since that would discard qualifiers.
[class.copy.ctor]
7 The implicitly-declared copy constructor for a class X will
have the form
X::X(const X&)
if each potentially constr... |
62,717,134 | 62,717,462 | Memory Leak in Custom List Type Using Template Class | I am trying to create a custom list type in C++ using the C++ template feature, and I have gotten it to compile and run correctly for lists of different types of value, even lists of lists of values, however when I run the program with Valgrind I get a memory leak.
I have been staring at this one for ages but have not ... | As WhozCraig and Yksisarvinen pointed out in the comments, using new[] and delete[] as opposed to using the malloc() function allows the memory to be allocated and freed correctly, and the resulting code is shown below just in case it helps anybody:
template<typename listType>
class List {
public:
listType *data;
... |
62,717,187 | 62,717,282 | call function with cout inside a cout statement | Firstly please have a look at some simple codes that my questions derived from.
#include <iostream>
#include <string>
using namespace std;
string get_something()
{
cout << "output something";
return " and return something";
}
void print_something()
{
cout << "print something";
}
int main()
{
... | This seems to be a very common misunderstanding among beginners. Printing something via cout is not the same as returning a value from a function. Thats completely orthogonal things.
You can write:
std::string returned_value = get_something();
std::cout << returned_value;
But you cannot write:
??? returned_value = pri... |
62,717,559 | 62,717,711 | Assignment operator for std::variant | I'm trying to assign a float to a defined value in my std::map using std::variant. I initialized my map this way:
std::map<std::string,std::variant<float,int,bool,std::string> kwargs;
kwargs["type"] = "linear";
kwargs["flag"] = true;
kwargs["height"] = 5;
kwargs["length"] = 4.5;
I'm trying to archive this operati... | To access the variant, you need to use the free function std::get:
float f = std::get<float>(kwargs["length"]);
Also, you might run into a problem with this line:
kwargs["length"] = 4.5;
Since 4.5 is a literal of type double, and not float. To solve this, just use the F suffix:
kwargs["length"] = 4.5F;
|
62,717,701 | 62,723,410 | C++ app MySQL odbc database connection error: terminate called after throwing an instance of 'otl_tmpl_exception<> | I am currently debugging a containerized C++ application, it seems like it's throwing exception and complaining about the database connection, error:
terminate called after throwing an instance of 'otl_tmpl_exception<odbc::otl_exc, odbc::otl_conn, odbc::otl_cur>'
Aborted
The code in main() is below:
int main(int ac, c... | I'm not very familiar with the Oracle, ODBC and DB2-CLI Template Library but I had a go using it with a MySql database on my Ubuntu Linux.
This is how I was able to run a simple query. I think the code below is fairly self-explanatory.
As you'll see, it's quite different from your code. The driver is mysql. You have to... |
62,717,901 | 62,718,041 | In C++ algorithm header, why use "!(val < *first)"? | Here is a piece of C++ code written in the c++ algorithm header file.
bool binary_search(vector<int>::iterator first, vector<int>::iterator last, int val)
{
first = lower_bound(first, last, val);
return (first != last) && !(val < *first);
}
I can understand how this binary_search function work, but I cannot un... | The algorithm has simply been specified to only require the type to be comparable with <, and no other comparison operator such as ==.
This allows the algorithm to be used with types that do not implement == (as rare as that may be). That would not be the case if the algorithm used ==.
Note that the algorithm already u... |
62,718,016 | 62,718,064 | What makes placement new call the constructor of an object? | From here:
The Standard C++ Library provides a placement form of
operator new declared in the standard header as:
void *operator new(std::size_t, void *p) throw ();
Most C++ implementations define it as an inline function:
inline
void *operator new(std::size_t, void *p) throw ()
{
return p;
}
It does nothing b... |
But what makes it call the constructor?
The semantics of operator new
For details, read the C++11 standard n3337 about new expressions, or a newer variant of that standard.
When you define some operator new, using it later would call the constructor. By definition of C++.
I recommend reading a good C++ programming bo... |
62,718,214 | 62,721,676 | constexpr template meta-info variable in c++11 | I'm trying to represent some meta information in a structured way (i.e. using a class). It's header-only and I need to support c++11 so can't use inline variables. I've come up with a couple of potential solutions but each has its drawbacks. Any suggestions would be much appreciated though just pointing on how to make ... | Prior to C++17, which introduced inline variables—and made constexpr static member variables implicitly inline—you have to define such variables outside the class if they are odr-used:
const FieldInfo<Sth> SthInfo::fieldA;
Note that this is a non-templated variable and thus must be defined in exactly one source file. ... |
62,718,306 | 62,718,601 | Can someone help me in writing this same program using CALL BY ADDRESS? | This is a program i wrote to convert lower case string to upper case using CALL BY REFERENCE.
//program to convert a lower case sentence to upper case
#include<iostream>
#include<string>
using namespace std;
void changetoup(string &str)
{
for(int i=0;i<str.length();i++)
{
str[i]-=32; //line1
}
}
i... | To replace the str[i] call to fit a pointer str, recall that the string itself is now described *str.
So you can:
Dereference there and then: (*str)[i]
Or make a reference:
std::string& ref = *str;
ref[i] -= 32;
Use at() instead (though this is slightly more costly, and can throw an exception, due to added bounds c... |
62,718,996 | 62,719,072 | Cout printing with array pointers - weird behavior | I was playing around with pointers and got results I did not expect:
#include <iostream>
#include <vector>
int main() {
int arr[4] = { 1, 2, 3, 4 };
int* pArr = arr;
std::cout << "First number: " << *pArr << " at address: " << pArr;
pArr++;
std::cout << "\nSecond number: " << *pArr << " at address:... | This code:
std::cout << "\n" << *pArr2++ << "\n";
std::cout << "\n" << *pArr2++ << "\n";
has a well defined order of modifications to pArr and will print
1
2
But this code:
std::cout << "\n" << *pArr2++ << "\n" << *pArr2++ << "\n";
invokes undefined behavior before c++17, because there are multiple modifications to ... |
62,720,060 | 62,720,627 | How to safe cast int reference to long reference? | Given
T& bindParam(const long& val) {
/* some code*/
}
T& bindParam(const long&& val) = delete;
T& bindParam(const int& val) // same as above for int
{
static_assert(sizeof(int) == sizeof(long)); // true
static_assert(alignof(int) == alignof(long)); // true
return bindParam(reinterpret_cast<const long&>(... |
obviously, strict aliasing violation, but should work if compiler is not intended to break code
If you don't care about strict aliasing violations, then you should ignore warnings that appear when you violate strict aliasing. Which is what this warning is doing.
Accessing a long through a pointer/reference to an int ... |
62,720,510 | 62,720,804 | Output not appearing in Visual Studio code after compile and run | Why output is not appearing.I am new to Visual Studio and I don't know why this is happening.
I am providing a screenshot.enter image description here
and this is the code which i am getting instead of my output.
[Running] cd "/home/dell/src/" && g++ hello.cpp -o hello && "/home/dell/src/"hello
/usr/bin/ld: /usr/lib/gc... | I have had same problem with no reason . I tried compile and run manually using g++ .
For easier compile you can create Make-File for your code .
|
62,720,552 | 62,721,185 | Using Resolution theorem proving with Z3 | I am new to Z3 but have some prior experience using Prolog.
I have managed to solve the following "puzzle", i.e. to prove that the girl is a witch using Prolog, but am at a loss how to implement it in Z3 (in C++ or Python):
https://www.netfunny.com/rhf/jokes/90q4/burnher.html
Do I need to declare Function() for asserti... | It should be pointed out that SMT solvers (i.e., Z3) aren't usually good at reasoning with quantifiers in general, but this particular case is easy enough that it can handle without a sweat. (It's easy because all you have are uninterpreted sorts and booleans; there are no integers, reals, datatypes etc., to complicate... |
62,720,807 | 62,720,876 | Why to add "extern" keyword if the global variable is external by default? | main.cpp
#include <iostream>
extern int g_x; // this extern is a forward declaration of a variable named g_x that is defined somewhere else
int main()
{
std::cout << g_x; // prints 2
return 0;
}
add.cpp
int g_x { 2 };
If I delete extern in main.cpp, then the code does not work. One the other hand, I don't ... | extern is different from external linkage. extern just means that you do a declaration, and that the variable is defined somewhere else.
If you remove extern, int g_x will be defined in main.cpp violating ODR (since you have it defined twice).
|
62,720,880 | 62,721,038 | OUTPUT ERROR,The problem is to find the sum 5000 digit number cpp | This is the code(cpp)
#include <iostream>
#include <string>
#include <numeric>//to import the accumulate function
#include <vector>
#include <algorithm>
using namespace std;
int main(){
vector<long long> vi;
string s; //this contains the long number its better not to type here
... | I don't understand why you are using std::vector. You could calculate the sum without using the vector:
int k=0,sum=0;
for(int i=0;i<s.length();i++)
{
k = s[i]-'0';
sum += k;
}
Note: if you are a little paranoid of the sum value fitting into an integer, you can use an unsigned integer since digits can't be n... |
62,721,097 | 62,729,524 | C++ Regex infinite loop | I'm writing a c++ program that regex's to find the cells mentioned in a give excel range string
e.g.
$C$5
$CC$4
$C$5:$F$89
because of the need to either match only once (i.e only one cell is being mentioned in the string) or twice (i.e. for when two cells are mentioned in the string; its a range) I have designed my pro... | Inside your while loop, you do not change the inString, nor are you using an iterator that would move the regex index, so you constantly get one and the same match, and there is no break condition inside the loop.
Use
while (std::regex_search(inString, match, regx)) {
std::cout << match[0] << "\n";
vecC... |
62,721,248 | 62,753,043 | how does istream std::cin modifies custom istream buffer? | I am reading C++ Practical Programming by Example by Andrew Koenig (Author) and in the chapter 4.1.3 Reading homework grades, there is this snippet:
istream& read_hw(istream& in, vector<double>& hw){
//if(in){ /* HOW can be istream be used as bool in condition? -> commented out, this is not needed */
... |
return value : Why does the function have istream type as return value? Why is not the function void?
The function type certainly could be void, you are correct. However, returning an istream& allows chaining, like the following:
std::string name;
read_hw(cin, gradevec) >> name;
This would place the first non-dou... |
62,721,540 | 62,721,611 | Repeat Code in C Based on Compile time Arguments | Suppose I have a some C code, say, printf("A"); how can I repeat it N number of times based on some compile time argument where N is passed in that compiler argument. e.g gcc -D print=N
Similarly, is there a way where we can pass the range of the loop based on the compile time argument/flag?
| Simply put it into a loop:
for (int i = 0; i < print; ++i)
printf("A");
The print symbol will be substituted by the value specified on the compiler command line (e.g. -Dprint=5), so the loop runs the desired amount of times. You can do the same thing with the start value 0 by adding another -D definition to use a di... |
62,721,697 | 62,762,433 | Integer-Overflow for values upto pow(10,19) | This is the code i am working on where i get the overflow problem.
The Constraints specified in my problem are (0 ≤ v, c, n, m ≤ pow(10,18))
My code fails for this test case:63434583954291753 66777666160449180 94688604155374928 61081164840594246
P.S. There is no problem with implementation of my code. Just Want to avoi... | You entered n = 94,688,604,155,374,928.
Then in the line
int **output=new int*[(n+1)%mod]
which means you are asking the system to allocate memory of n number of integer pointers. That is about 90,000 * 8 TB of memory assuming your operating system is 64-bit. I doubt your computer has that much RAM.
Use smaller number... |
62,721,869 | 62,721,903 | returning an array address from function in c++ issue | i'm new to programming , this code gives me syntax error in line => int *result = apply_all(array1,5,array2,3) this is the error: expected primary-expression before '}' token|
i'm trying to write function called apply_all expects 2 arrays of integers and their sizes and dynamically allocates a new array of integers who... | On this line:
*(result[i*5+j]) = *(array1[i])**(array2[j]);
since result[i*5+j] gives you an int, you are trying to dereference an int, which is not possible.
You just need to do:
result[i*5+j] = array1[i] * array2[j];
Also, in print, your range-for loop won't work with a pointer. You need to do:
for(int i = 0; i < s... |
62,721,992 | 62,722,625 | Represents empty type in C++ class template | consider the following example of a compile-time "vector".
#include <iostream>
template <int n, int...ns>
struct static_vector {
static constexpr int value = n;
static_vector<ns...> rest;
};
template <int n>
struct static_vector<n> {
static constexpr int value = n;
void* rest;
};
template <int n, cla... | But why recursion ?
You tagged C++17 so you can use template folding, so... what about as follows ?
#include <iostream>
template <int ... Is>
struct static_vector
{
template <std::size_t N>
int get () const
{
static_assert( N < sizeof...(Is), "index out of bound" );
std::size_t i{};
int r... |
62,722,042 | 62,722,127 | Vector of Ofstream objects cannot be created | ofstream out_data1, out_data2;
vector<ofstream> {out_data1, out_data2};
Error image :
Why is this happening? How can I solve it?
| If you take a careful look at this link, you will understand that you are trying to copy an ofstream object, and the copy constructor of ofstream is deleted. That is what the error is telling you. You could have simply searched for the error on Google though ;)
|
62,722,111 | 62,722,370 | Main UI Thread is blocked once oboe recording is started | I have coded a basic application that starts recording with oboe library.
In MainActivity there are 2 buttons that call 2 JNI functions that are :
recordAudio()
stopRecording()
In native-lib.cpp, these 2 JNI functions are defined as follows :
extern "C" JNIEXPORT jboolean JNICALL
Java_com_example_oboeaudiorecorder_Ma... | I now call the recordAudio function from a thread as follows :
buttonRecordAudio.setOnClickListener{
val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
if (permission != PackageManager.PERMISSION_GRANTED) {
Log.i("", "Permission to record denied")
Activit... |
62,722,412 | 62,722,706 | Initialize outer scope variable in class function | I am new to C++ I come from a C# background. I am creating an Arduino project using c++ using vs code thanks to https://docs.platformio.org/ .
The following code works and turns on my led strip:
main.cpp
#include <Arduino.h>
#include <LedStrip.h>
// pin where led strip is connected
#define LED_STIP_PIN 4
// number... | The writers of that class made a grade-school C++ mistake and didn't correctly observe the Rule of Three. This means an Adafruit_NeoPixel object can be copied when it is not safe to do so.
void setup(uint16_t led_count, uint16_t pin)
{
// Declare our NeoPixel strip object:
Adafruit_NeoPixel a(led_count, pin, NE... |
62,722,657 | 62,722,705 | In C++, does it make sense to use a function with std::optional<T> parameter, to denote optional parameters? | I know that one can implement functions with optional parameters like so:
int someFunction(int A, int B = -1) {
if (B != -1) {
... // If B given then do something
} else {
... // If B not given then do something else
}
}
However, I'd lake to take advantage of std::optional as recommended by a c... | To use it in the way you intend here, I believe you'd need to specify a default value of std::nullopt:
int some Function(int A, std::optional<int> B = std::nullopt) {
if (B.has_value()) {
... // If B given then do something
} else {
... // If B not given then do something else
}
}
|
62,722,666 | 62,775,849 | Concatenate unique value separated by comma in two string in C++ | CString s;
int res = 0;
char *existing;
char *current;
existing = strtok(urls, ",");
current = strtok(storedurls, ",");
while (existing != NULL)
{
while (current != NULL)
{
... | DWORD res = 0;
CString existingUrls = urls;
CString curUrls;
CString curItemInExitingUrl;
CString curItemInCurUrl;
CString urlsToAdd;
while (!existingUrls.IsEmpty()) {
CWinLogFile::GetTok(existingUrls, _T(","), curItemIn... |
62,722,937 | 62,723,186 | Implementing an `is_similar` type trait based on the definition of the C++ standard | I am trying to implement a is_similar type trait based on the definition given by the standard (details here):
Two types T1 and T2 are similar if they have cv-decompositions
with the same n such that corresponding Pi components are either
the same or one is "array of Ni" and the other is "array of unknown
bound of", a... | cv-decomposition "peels" a type down into alternating layers of const/volatile qualifiers and pointer/array indirections. Types are similar if the pointer/array indirections are the same (allowing "array of unknown bound" to match "array of n") and if the types underneath are the same (ignoring the cv-qualifiers).
So,
... |
62,722,950 | 62,746,500 | error C2679: binary '<<': no operator found which takes a right-hand operand of type 'std::string_view' (or there is no acceptable conversion) | #include <iostream>
#include <string>
void Log(std::string_view message)
{
std::cout << message << std::endl;
}
int main()
{
const char* text = "Test";
Log(text);
std::cin.get();
}
I am getting that error and #include <string> is included at the start. Any ideas?
| Like others already mentioned - std::string_view is defined in the standard header "string_view", which must be included - otherwise string_view is not defined.
Because you include some headers like "string" and "iostream" which have some connection to std::string_view it is clear that they do at least some forward_dec... |
62,723,007 | 62,723,177 | Can I use C++ Code in iOS or mac application? | I have a code written in Ruby and I want to convert it to a library that both of my Android and iOS apps can consume. I am planning on rewriting it in C++ so that all platforms can use this library (including embedded sensors and small devices and phones)
I know Android can consume C++ based code via NDK but can iOS de... | Yes, C++ (and even most recent versions, like c++17) is fully supported on all popular platforms (Android, iOS/watchOS/tvOS, macOS and UWP/Windows 10). The only major thing you will have to face is so-called "glue layer" code, which has to be written separately for each platform to let your code interface with OS-nativ... |
62,723,079 | 62,733,266 | Is type casting needed when using NOT (~) operator on a literal integer against a 64bit variable | Will the following work, if not what are the rules of auto type-casting that prevent it from working?
uint64_t u64val=3293;
#define ALIGNsize 4
u64val=(u64val+ALIGNsize-1)&~(ALIGNsize-1);
Or is this required:
uint64_t u64val=3293;
#define ALIGNsize 4
u64val=(u64val+ALIGNsize-1)&~((uint64_t)ALIGNsize-1);
If the later,... | I did a test and as far as alignment using NOT (~) I think I came up with something generic that works. Both for C and C++ (tested in C++). Here the sample app. Is this good or am I missing something (want to ensure before accepting as answer):
// TestAlign.cpp : This file contains the 'main' function. Program exec... |
62,723,172 | 62,723,505 | Why would I compile 2 C/++ source files instead of using a header file? | I've recently started learning about makefiles, and the video I'm watching includes a compilation if two source files and a header file. A class was defined in the header file, which was included in both source files. A method for the class was defined in one source file and was called in the second (main.cpp). Why wou... | The human mind can't hold very much information at a time, so we chop things up into smaller, logical and coherent pieces.
OK. So one main.cpp that includes the dozens or hundreds or thousands files in the program, all implemented in header files of a reasonable size, each covering one concept or aggregating more heade... |
62,723,421 | 62,727,925 | Getting notified when an I2C-Value changes in C++ | I recently started experimenting with I2C-Hardware on my raspberry pi. Following this tutorial Using the I2C interface I already know how to read and set values. However, the program I want to realize needs the current value on a specific address all the time. So, I made a thread and query the value constantly in a nev... | I was able to get what I wanted.
I use the following repeater for the I2C-Bus: link and it turns out there is a soldering bridge (LB2) you can set that sets a signal on GPIO17 whenever a value on the I2C-Bus changes since it has last been changed. I can now listen on this events accordingly.
|
62,723,839 | 62,723,864 | Modulus Behavior -1 % 3 (C++) | if (currIndex < 0) {
cout << currIndex << " % " << array.size() << endl;
currIndex = currIndex % array.size();
cout << currIndex << endl;
}
Output:
-1 % 3
0
-1 % 3 = -1 in C++ so why is 0 being returned?
Full Snippet:
https://ideone.com/leWqhi
| size() returns unsigned integer type, so this computation is done by casting -1 to unsigned and performing unsigned modulo.
Cast size() to signed integer type to get correct result.
|
62,723,854 | 62,723,938 | Why is this done with linked lists in C ++? (handling them like stack) | I have the following code:
#include<iostream>
#include<stdlib.h>
using namespace std;
struct Nodo{
int valor;
Nodo *siguiente;
};
// Lista enlazada "simple", manipulandola con el metodo LIFO (pila).
void agregar_nodo(Nodo *&cima, int n); // ¿Puntero por referencia?
int main(){
Nodo *cima = NULL;
ag... | Answers to questions:
If you didn't use new then where would your Nodo objects live? They would have to be locals on the stack, or globals. If they're locals, then they'll disappear as soon as the function that declares them exits. If they're globals, you'll only have a certain number of them to use, however many you ... |
62,723,870 | 62,723,908 | Most efficient way of initializing a map of vectors in C++ | What's the most efficient way to initialize a map of vectors of fixed size set to the same value except for the first one?
So for example assume it's a map of strings to a vector of booleans:
std::map<std::string, std::vector<bool>> map;
I can think of two ways:
for (const std::string& key : {"key1", "key2", "key3"}) ... | Make a temp vector<bool>:
std::vector<bool> vb(10, false);
vb[0] = true;
for (const std::string& key : {"key1", "key2", "key3"})
map[key] = b;
Note that your original code used k where you should have been using key
|
62,724,132 | 62,724,175 | c++ "error: invalid use of void expression" | I'm trying to implement a trie and I get the following error:
error: invalid use of void expression
5 | collect(node->next[c], pre.push_back(c), q);
| ^~~~~~~
This is my function:
void string_map<T>::collect(Node* node, string pre, std::queue<string> q) const {
if (node == nullptr) {return;}
if (... | http://www.cplusplus.com/reference/string/string/push_back/
string::push_back returns a Void type (ie, doesn't return) and you are using the return value of this call as an argument here:
collect(node->next[c], pre.push_back(c), q);
I am not sure exactly what you are trying to do, but this is the cause for the error.... |
62,724,196 | 62,727,531 | Polymorphic member variable(s) - class design | Wondering whether anyone can help identify a more elegant design approach - or potentially identifying shortcomings of the following design.
Currently, I have an abstract Response class that derives from a serializable JSON Object.
//objects.h
struct Object
{
[[nodiscard]] std::string serialize() const;
virtua... | (I’m adapting one of my recent Reddit comments that answered basically the same question.)
in general
Don’t model serialization with inheritance! It’s a cross-cutting concern you want to attach to arbitrary types. Inheritance is the wrong tool for that. Some problems with the approach:
You force everything serializabl... |
62,724,349 | 62,724,368 | C++: Unable to change the value of a std::pair using the "=" operator | I'm attempting to update the value of an std::pair, but that results in a compiler error. How can this be resolved?
#include <unordered_map>
#include <utility>
#include <string>
#include <iostream>
int main(int argc, char *argv[])
{
std::unordered_map<int, std::pair<std::string, std::string>> test1;
test1.inse... | You are using const_iterator instead of iterator for test2:
std::unordered_map<int, std::pair<std::string, std::string>>::const_iterator test2 ...
Use:
std::unordered_map<int, std::pair<std::string, std::string>>::iterator test2 ...
Or simplify it using auto:
auto test2 = test1.find(1);
|
62,724,611 | 62,724,624 | Initialize a char array or string with a pointer in C++ | I have a pointer, where the next X elements are ASCII characters with a '\0' at the end. I need to save the ASCII characters either in a char array or string type.
Is it possible to dynamically initialize a string or char array in C++ with a pointer?
The code below does not compile with the following error:
char symbol... | You can use std::copy to copy the contents like this:
char symbol[11];
std::copy(packet + 8, packet + 19, symbol);
or use a std::string constructor:
std::string symbol(packet + 8, packet + 19);
|
62,725,023 | 62,778,555 | Why Does this SFML Code Act like an App, But Does Not Create a Window? | Stack Overflow. I come to you in a time of great need.
I am starting to learn C++, after learning Python, and I want to learn C++ in an entreating way; that is, by making games with SFML. I am following a book which you can find here. I use MacOs Catalina, and Clion with Cmake. The problem is that, when using a basic e... | I think it's because you are missing the event loop. Events have to be polled for window to work properly.
sf::Event event;
// Then in your main loop...
while (window.pollEvent(event))
{
// Handle events.
}
|
62,725,196 | 62,725,271 | What unexpected process happened in this test()?why Always overwrite ch[0 1 2...]? | I want to input some char[100], then store them in char *ch[100], but failed.
ch[0,1,...last] would be normal in test().
But ch[0...last]==ch[last] when exit from test().
What happened?
#include<iostream>
#include<cstring>
using namespace std;
char *ch[100];
int N=0;
int test(char *strValue)
{
ch[N++]=strValue;//... | The statement
ch[N++]=strValue;
copies the pointer not the string.
That means all elements of ch will point to the very same string, which will only have the contents of the last input.
The natural C++ solution is to use a std::vector of std::string objects, and push_back new strings as needed:
#include <iostream>
#in... |
62,725,288 | 62,725,335 | Why std::iterator is not able to access the function | When I try to access a function through iterator the compile tells that class ha no member with such name.
class Director
{
private:
std::string stdstrName;
public:
Director(std::string name): stdstrName(name){ }
void setName(std::string name) { stdstrName = name; }
std::string getName() { return stdstr... | You are using std::find(), but it's used with values, not with callables, hence you need to use std::find_if.
And you are using your iterator to access to a member function of an object pointed to by a pointer which is pointed to by an iterator, hence you have two dereferences, not one.
The following is a correction
au... |
62,725,377 | 62,725,417 | Why does the C++ std::unordered_map returning an iterator from emplace / find? | I understand why an unordered_map has an iterator (begin() and end()) but I don't see what value returning an iterator from find / emplace is.
I can't imagine a use case where you would want to start your iterator at a given key as opposed to begin / end (because a good hash function should make the position of a key i... | What if you want to remove the item? What if you want to extract or merge it? What if you want to use it as a hint to emplace?
|
62,725,763 | 62,739,372 | How can I calculate a precise time difference (C++)? | I have two UTC times, stored as "day:hour:minute:second:millisecond", and also as five integer variables for day, hour, minute, etc. I'd like to find the difference between the two times, with millisecond precision. How can this be done in C++?
| To calculate time difference with millisecond precision:
Convert both timestamps to std::chrono::system_clock::time_point.
struct std::tm thetime { .tm_sec = sec, .tm_min = min, .tm_hour = hour,
.tm_mday = mday, .tm_mon = mon, .tm_year = year };
auto mytime = (std::chrono::system_clock::... |
62,725,841 | 62,725,870 | c++ private variable of a passed object | #include <stdio.h>
class HelloClass
{
float t;
public:
HelloClass(float x) : t(x) {};
float Add(HelloClass a);
};
float HelloClass::Add(HelloClass b)
{
return t + b.t; // How is b.t accessible here?
}
int main()
{
HelloClass a(2), b(3);
printf("hello %f\n", a.Add(b));
return 0;
}
Hello, ... | This is expected behavior, private members could be accesed by member functions, even they're from other instances.
(emphasis mine)
A private member of a class is only accessible to the members and
friends of that class, regardless of whether the members are on the
same or different instances:
class S {
private:
... |
62,725,916 | 62,760,930 | Z3: what's a more convenient and efficient method for defining class hierarchies? | As an extension to a previous Z3-related question Using Resolution theorem proving with Z3 and built on top of @alias 's answer at https://stackoverflow.com/a/62721185/13861050
I've added a few more functions and relations:
FEMALE = Function('FEMALE', Thing, BoolSort())
ANIMAL ... | SMTLib is essentially a first-order logic. (More precisely, it's a first-order many-sorted logic.)
This pretty much disallows any construct that takes functions as arguments. So, you cannot write properties that say "this function is symmetric" or second order statements of the form LIVING_THING(ANIMAL) where ANIMAL is... |
62,726,174 | 62,726,297 | Friend of the class is inaccesible | i am trying to write a very simple code as a practice. The problem is when i make friend a member function of one class to another, it says inaccesible but when i declare the whole class as friend of another class it works fine.
#include <iostream>
using namespace std;
class gpa2;
class gpa1 {
private:
int no1;
... | xp.no4 is not accessible, as setnum1 is a member function of gpa1, not gpa2
Implementing the function setnum1(int, gpa2&) is not necessary when defining it, and causing problems here: At the time of defining class gpa1 setnum1 can't be implemented, as class gpa2 is not yet defined. BUT implementing it after defining gp... |
62,726,195 | 62,726,271 | Why does new make system calls if whole app is virtually maped? | what i understand is that writing a user space app will result in OS creating virtual space for this app which will be approx = whole amount of ram on the system, this way the app will think it's the owner of the computer and some of this space will only be mapped to physical hardware.
Accordingly, I know that new call... |
what i understand is that writing a user space app will result in OS creating virtual space for this app which will be approx = whole amount of ram on the system
No. Typical mainstream operating systems will create virtual memory to hold the program itself and the memory it requests as it requests more. There is no... |
62,726,546 | 62,726,877 | Is this a proper use of C++20 concepts? | I have a simple Vec3<T> class, and I would like to update it using C++20 concepts (Clang 10.0.0 with -std=c++20). The new version looks something like this:
template <typename T> concept Arithmetic = std::is_arithmetic_v<T>;
template <typename T> concept FloatingPoint = std::is_floating_point_v<T>;
template <Arithmeti... | We already have a concept for a floating point type, it is std::floating_point. The absence of std::arithmetic seems to be an oversight and has already been noted, see N4844, page 50:
US 193. C++20 lacks a concept for arithmetic types. This omission is surprising, as this is a fairly common use case. For example, supp... |
62,726,701 | 62,726,724 | How can I take input from user and store it in a vector? | Unable to take input from user and store it in a vector. How to do that?
Just started learning to code.
#include<iostream>
#include<vector>
int main() {
int total_even = 0;
int product_odd = 1;
std::vector<int>numbers;
std::cout << "Enter 6 digits: ";
std::cin >> numbers;
for (int i = 0; i < numbers.size(); i++) {
... | This is how you take inputs in a vector:
std::vector<int> numbers;
for(int i = 0; i < /*6 in your case*/; i++) {
int temp;
if(scanf("%d",&temp)) {
numbers.push_back(temp);
}
else {
std::cerr << "something wrong with vector" << "\n";
}
}
Another way would be using a for-each loop. B... |
62,727,310 | 62,728,092 | Why does delete fail after memset | The following code will cause core dump when deletion. But if comment out "memset", it is good to run.
So, it looks like memset does something wrong. What is the problem of the following code?
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n= 5;
int **p = new int* [n];
fo... | What you had created is array of pointers to non-contiguous areas of memory
int **p = new int* [n];
for (int i=0; i<n; i++) {
p[i] = new int [n];
}
Here p[0] points at first area, p[1] at second, p[n] at last. They aren't same object, so from point of view for language lawyer such memset call is Undefined Behavior... |
62,727,464 | 62,727,521 | How to understand new operator overloading? | For "+" operator overloading, it is pretty easy to understand. c = c1.operator+(c2) is function notation, c = c1 + c2 is operator notation.
However, I just couldn't understand new operator overloading. In the following code:
Please tell me what happened when processing student * p = new student("Yash", 24); Why void * ... | The arguments in
student * p = new student("Yash", 24);
are arguments to the student constructor, they are not passed to operator new whose only responsibility is to allocate enough memory for the student object.
In order to allocate enough memory for a student object operator new has to be told how much memory it nee... |
62,727,882 | 62,728,203 | Compiling is stuck on the previous compilation c++ | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
cout << "Hello";
}
When I try to compile this program it still compiles the last program that was:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(... | You are seeing the result of your previous program, because the compilation of your new program fails.
The reason why compilation of your program fails is because your program depends on code from the C++ standard library. Your program is not linked against the C++ standard library because you use gcc, which is the com... |
62,728,239 | 62,795,316 | CMake WxWidgets project successfully built on linux but not on windows | I've managed to build a WxWidgets based on CMake on Ubuntu 19.10, but failed on Windows 10, saying that it cannot find WxWidgets, though I've built it successfully (static, release and with unicode support).
WxWidgets path is C:\wxWidgets-3.1.3 and the build directory is C:\wxWidgets-3.1.3\msw-release.
The makefile is
... | To properly detect wxWidgets you need wx-config.
A Windows version of wx-config exists and can be downloaded from: https://github.com/kowey/wx-config-win
To make wx-config know where your wxWidgets is, you need set the following environment variables:
WXWIN (in your case to C:/wxWidgets-3.1.3)
WXCFG (in your case to s... |
62,728,368 | 62,728,458 | Automatic conversion of int to unsigned int | #include <iostream>
using namespace std;
int main() {
unsigned int u = 5;
int x = -1;
if(x>u) {
cout<<"Should not happen"<<endl;
} else {
cout<<"Ok"<<endl;
}
}
This code outputs Should not happen. I came across this when comparing the size of a string (size_t is an unsigned int or ... | You can enable -Wsign-compare -Werror in Clang: Try it online!
It'll produce a compile-time error (because of -Werror that treats warnings as errors):
.code.tio.cpp:7:9: error: comparison of integers of different signs: 'int' and 'unsigned int' [-Werror,-Wsign-compare]
if(x>u) {
~^~
1 error generated.
For s... |
62,728,624 | 62,728,712 | eventfd, adds values written to socket | Following is the issue,
I have one listener thread, that listens and accepts new connections.
Once accepted, I use eventfd to pass on socket descriptor to four other worker threads.
listener is the one that creates one eventfd, and all worker threads read the same.
Now issue is, when multiple clients connect to server,... | You're using the wrong tool for the job. eventfd() is a something happened notification tool, not a something happened; here's the relevant data tool.
When you write a new 64 bit integer value to the eventfd, it's added to the current number associated with the event. Reading from the descriptor gives you the current n... |
62,728,674 | 62,728,759 | Get the absolute path from std::filesystem::path c++ | I have this piece of code
auto path = std::filesystem::path("/root/home/../opt/.");
I had tried std::filesystem::absolute() but then realized it is for something else than the reasult I want
My question is how can i convert that relative path to the absolute path so that the reasult will be "/root/opt/".
I am using ... | Use std::filesystem::canonical to turn the path into an absolute path with all .. removed (reference):
auto path = std::filesystem::canonical("/root/home/../opt/.");
Gives you:
"/root/opt"
|
62,728,802 | 62,729,708 | Default argument parameter in template specialization | template<typename T> void printf_t(const T&, char='\n');
template<> void printf_t(const int&, char);
void (*pi)(const int&, char) = printf_t<int>;
int main()
{
int a;
scanf("%d", &a);
pi(a);
return 0;
}
How can I make this code work ? I want to have char argument default value in this te... |
How can I make this code work ?
You can't. Function pointers can't take default arguments. You can, however, workaround it by either wrapping the call into a function or lambda or using std::bind:
auto pi = std::bind(printf_t<int>, std::placeholders::_1, '\n');
pi(a);
Using a lambda:
auto pi = [](cons... |
62,728,880 | 62,729,026 | How to initialise a templated sub-class of vector | The following example to initialise a vector of vector works fine:
using DataElement = std::vector<double>;
using DataVector = std::vector<DataElement>;
DataVector data;
data.emplace_back(DataElement{ 1.0f, 1.0f });
data.emplace_back(DataElement{ 1.1f, 1.1f });
Now I would like to make the type of DataElement generic... | Use using with templates.
#include <vector>
template <typename T>
using DataElement = std::vector<T>;
template <typename T>
using DataVector = std::vector<DataElement<T>>;
int main()
{
DataVector<double> data;
data.emplace_back(DataElement<double>{ 1.0f, 1.0f });
data.emplace_back(DataElement<double>{ 1.... |
62,729,013 | 62,729,067 | C++ include error from #include "DevEngine/Core.h" | So there are 1 files that I want to link together, Core.h and Events.h.
Core.h is in a folder called DevEngine and the Events.h file is in a folder called Events witch is inside DevEngine.
Here are the file directorys:
Core.h = src/DevEngine/Core.h
Events.h = src/DevEngine/Events/Events.h
I have added a #include "Dev... | You can do #include "../Core.h".
You can also set the directories the compiler uses to search for the header files (-I option in gcc) and then use paths to those files relative to one of those directories. (See for example gcc documentation on search paths.)
This could be done differently depending on the way you are b... |
62,729,066 | 62,737,776 | How to define a LLVM GlobalValue variable in C++ with llvm-10 library? | In LLVM-10 library, I didn't find any C++ API to define a LLVM GlobalValue, please help me.
Here's document of LLVM-10 GlobalValue. But the constructor of GlobalValue is protected, not public.
| GlobalValue is a common base class for Function and GlobalVariable. It is not intended to be used directly, so you most probably want GlobalVariable, which does have public constructor: https://llvm.org/doxygen/GlobalVariable_8h_source.html#l00050
|
62,729,146 | 62,734,460 | Click function on Toggle Buttons in Unreal Engine 4 C++ | I have a doubt about CheckBoxes and click events. I have some button which executes a function OnClick, something like this on code:
SomeButton->OnClicked.AddDynamic(this, &ClassName::FunctionToExecute);
For style reasons, I thought that I should use a Toggle Button, implemented with a CheckBox, instead of a regular Bu... | If you are using a UMG Check box (which it sounds like you are), than we can look at the delegate declaration:
// In Checkbox.h
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam( FOnCheckBoxComponentStateChanged, bool, bIsChecked );
and notice that we need a bool input parameter for our callback function.
So that means tha... |
62,729,814 | 62,736,265 | Matrix Multiplication using SIMD vectors in C++ | I am currently reading an article on github about performance optimisation using Clang's extended vector syntax. The author gives the following code snippet:
The templated code below implements the innermost loops that calculate a patch of size regA x regB in matrix C. The code loads regA scalars from matrixA and regB... | The 2nd comment on the article links to https://github.com/pytorch/glow/blob/405e632ef138f1d49db9c3181182f7efd837bccc/lib/Backends/CPU/libjit/libjit_defs.h#L26 which defines the float8 type as
typedef float float8 __attribute__((ext_vector_type(8)));
(similar to how immintrin.h defines __m256). And defines the load /... |
62,730,091 | 62,737,026 | Is there anyway that I can determine whether the construct function is exist? | #include <iostream>
template<typename _OutType, typename _InType>
struct ConvertClass
{
_OutType operator()(_InType src)
{
return _OutType(src);
}
};
class OutClass
{
public:
OutClass(std::string str)
{
std::cout << "construct function works well!" << std::endl;
}
};
int mai... | to my knowledge there is not runtime checking if given class is constructible using argument of given type
as said in my previous answer you can resort to Concepts and check the types at compiletime, but if clause does not work at compile time
To me it looks like the best solution would be indeed making a template clas... |
62,730,157 | 62,730,510 | Uninitialized Usage in libstdc++ filesystem? | Consider the following code:
#include <filesystem>
int main() {
std::filesystem::path p{"/"};
}
When compiling with clang10 with the flags -std=c++17 -fsanitize=memory -g -O1 -stdlib=libstdc++ it compiles totally fine, but when running, the memory sanitizer finds the following error:
==166467==WARNING: MemorySani... | This is a false positive.
You should report it as a Sanitizer bug; it appears to be similar to issue 1238.
|
62,730,299 | 62,731,103 | Polygon transformation in Boost.Geometry in C++: Translation, Rotation, Reflection around a line | I have three types of queries for a polygon to implement using boost geometry:
translating a polygon to a given point
rotating a polygon about a reference point(not necessarily about origin)
reflecting a polygon around a line
As I am new to Boost Geomtry I am facing problems understanding the syntax. I searched for e... | The most generic transform I know of in the library is the matrix transform, which is a strategy you can use with transform.
Let's generate some random rectangles, rotated by random angles, translated over (-500..500, -500..500) and scaled between 1..3:
polygon gen_rectangle() {
using box = bgm::box<point_xy>;
... |
62,730,554 | 62,730,755 | C++ How to unpack array values as function arguments | I have an array of Strings that I would like to unpack as arguments for a function like:
Blynk.setProperty(V0, "labels", "label 1", "label 2", "label 3");
Where the array of strings would be:
labels = {"label 1", "label 2", "label 3"}
This array is actually built from an array of pointers to objects with a 'name' membe... | Well, you can do something like the following:
#include <utility>
template <std::size_t ... Is>
void setProperties(std::index_sequence<Is ...>, char const * labels []) {
Blynk.setProperty(V0, "labels", labels[Is] ...);
}
char const * labels [NUM_OBJECTS] = { "l1", "l2", "l3" };
setProperties(std::make_index_... |
62,730,646 | 62,730,852 | Extract integer from string and form an array | Starting out C++ in my school and it is looking so much more daunting than Python! Hopefully someone can guide me on this.
I have created a simple user I/O to practice on extracting integer from the user input and forming an array based on the inputs. See below:
#include <iostream>
#include <cstring>
using namespace st... | cin >> string will stop at whitespace, so let's use std::getline which will grab a whole line of input.
And regexs are certainly a way of doing this:
code
#include <iostream>
#include <cstring>
#include <regex>
int main() {
int number_array = {};
std::string user_input;
std::cout << "Enter your array ran... |
62,731,057 | 62,731,204 | Compilation failure when inner class uses outer class template parameter but only when using `ostream` | I run into a compiler error when an inner class uses the template parameter of the outer class, and I instantiate an output stream operator on the outer class on the member of the inner type.
I have spent a good bit of time trying to resolve this problem. I believe the following sources come close but I still do not u... | You got compile error because non-deduced context causes template argument deduction failing.
In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or expl... |
62,731,179 | 62,731,718 | My iterator implementation don't work, what's wrong with it? | I try to write my implementation of c++ iterator, but met some problems. When I try to iterate in range-based for, but get error that my iterator don't have suitable "begin" function and none was found. I wrote begin() and end() function. What's wrong?
#include <iostream>
template<typename T>
class iter final {
private... | For your question - make_shuffle returns a pointer to iter<T> class, which means that in order to iterate over this instance, you need to get the pointer value:
for (auto i : *shuffle_a)
std::cout << i << " ";
However, pay attention that you have another issue with your end function implementation. It checks for e... |
62,731,181 | 62,731,897 | Why do I not need a call to `add_test` in cmake? | I've seen add_test a few times in cmake and I'm confused because I'm using googletest and I haven't needed a single call to add_test. Could somebody please explain why? Is this handled directly by googletest or is this call just not used when you use googletest?
| The command adds a target (or custom command) to CTest. So whenenver you execute ctest inside the build directory, all added tests get executed. If you don't want to use CTest and simply execute your test binary manually, then there is no need to use add_test.
In larger projects, where tests usually consist of several ... |
62,731,368 | 62,731,670 | How can you redefine MPI_FLOAT, MPI_DOUBLE in a typedef way | I want to do typedef MPI_FLOAT/MPI_DOUBLE in the following way
#ifdef DOUBLE_PRECISION
typedef MPI_DOUBLE MPI_REAL_MYOWN;
#else
typedef MPI_FLOAT MPI_REAL_MYOWN;
#endif
I am using wrapper mpicxx from mpich. The idea is that I can now use MPI_REAL_MYOWN in my MPI APIs without having to worry about whether I... | MPI_FLOAT and MPI_DOUBLE are values of type MPI_Datatype. Just create a variable of that type if you wish.
#ifdef DOUBLE_PRECISION
const MPI_Datatype MPI_REAL_MYOWN = MPI_DOUBLE;
#else
const MPI_Datatype MPI_REAL_MYOWN = MPI_FLOAT;
#endif
|
62,731,516 | 62,731,642 | Under/over approximation while summing int multiplied by double | My code is supposed too evaluate the evolution of a sistem by a method of discretization of differential equations but all the data it needs to modify are integers which sum needs to be constant. The problem lies here,their sum diminishes. How can I try and solve this?
mystruct Population {
int T;
int S;
... | This is fairly simple. The multiplication to float/double auto-converts the integers to floating types. And converting floating types to integers has rounding errors: round-towards-zero is the default behavior.
If you simply want to ensure that sum remains constant while working with integers simply ensure the that num... |
62,732,114 | 62,732,742 | Distance function in Point class is not returning the correct value despite the formula being coded properly | #include <iostream>
#include <string>
#include <math.h>
using namespace std;
class Point{
int x,y;
public:
Point(){
x=0;
y=0;
}
Point(int a, int b){
a=1;
b=1;
}
Point(const Point &a){
x=a.x;
y=a.y;
}
void setvalues(int a, int b){
... | You can make distance a static member function. This way you can access the private elements and don't need an object to call the method on.
static double distance(const Point &a,const Point &b){
int x1=a.x,x2=b.x,y1=a.y,y2=b.y;
double d=sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
return d;
}
You can make i... |
62,732,350 | 62,732,409 | Why isn't a struct, empty other than inheriting an aggregate struct, aggregate-initializable? | Consider the following code:
struct A {
int x;
double y;
};
struct B : public A {};
int main() {
A a {1, 2.3}; // (*)
B b {1, 2.3}; // (**)
}
Line (*) compiles, line (**) doesn't.
Is this because B is not considered an "aggregate type"? If so, why isn't it? If not, what's the reason it can't be const... | GCC 10's default language version is C++14. In C++14 and prior, no aggregate could have any base classes.
The reason? No good reason. So, from C++17, this rule was relaxed; now no aggregate can have no virtual, private, or protected base classes … but others are fine.
Your code works in C++17. Add -std=c++17 to your co... |
62,733,347 | 62,733,548 | How to store a reference to a C-style array in a class? | class Class
{
public:
Class(array[3][3]) //the constructor
{
this->array = array
}
array[3][3];
};
int main()
{
array[3][3] = {...initialization...};
Class object(array[3][3]);
}
I want to make an object, which uses the 2d array and modifies it. I know that C arrays are just ... | If I finally got the question correctly, you can use a reference to an array:
struct Class {
Class(int (&array)[3][3]) : array_(array)
{}
void set11(int value) {
array_[1][1] = value;
}
int (&array_)[3][3];
};
int main() {
int array[3][3]{};
Class object(array);
object.set11(99... |
62,733,391 | 62,733,506 | Template specialization using another template | I have a problem with the template specialization, here's my example code:
struct Base;
template< class CLASS = Base >
void saySomething( const CLASS &b ) {
std::cout << "I'm base!\n";
}
struct Base {
};
template< class CLASS = Base >
struct X : public CLASS {
virtual void print() {
saySomething< CLA... | You are trying to do partial specialization of function templates, bu that's not allowed.
In this particular case, you can get the effect you want by writing the following overloads, so that you have either a complete specialization for Text or an overload for Number<N>, like this:
template <class CLASS = Base, size_t ... |
62,733,451 | 62,733,565 | Move constructor of class containing only movable std::map not working | I have a class containing a std::map<int, std::mutex> and somehow I'm not able to define a move constructor for it. std::mutex is not copyable nor movable but the move constructor of std::map still works because it doesn't require its type to be copyable or movable:
std::map<int, std::mutex> map1;
std::map<int, std::mu... | Your supposed move constructor takes a const rvalue reference. om cannot be modified, which means its members can't be moved from. Just drop const
|
62,733,524 | 62,733,557 | Why does GCC handle a const reinterpret_cast different when type alias is used? | In the following code:
#include <cstddef>
class s;
void foo(void* buffer) {
using s_ptr = s *;
const auto b_s = reinterpret_cast<const s_ptr>(buffer);
const auto b_s2 = reinterpret_cast<const s *>(buffer);
}
Compiling with -O3 -Werror=ignored-qualifiers I got the error:
<source>: In function 'void foo(voi... | Given:
using s_ptr = s *;
the type const s_ptr actually becomes s * const, which is not the same as const s *.
I suggest writing const to the right hand side of the type you want to const qualify, like this:
reinterpret_cast<s_ptr const>(buffer);
reinterpret_cast<s const *>(buffer);
and now it's clear that s_ptr cons... |
62,733,564 | 62,733,656 | file.open not creating a new file in C++ | I am trying to run below code but it is neither showing any file on the path nor reading anything from it. Whatever I am writing into the file through "cin >>" it is not being written. Can anybody please let me know mistake in my code below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;... | You should add the fstream::app flag in your open call and this will do the trick !
|
62,733,870 | 62,734,050 | Color specific treeview item using WIN32 API (C/C++) | I wanted to create a tree view where specific items have a different back & text colors.
I did found the following solution in the internet: Win32 Custom Draw Treeview Control, but here they color each item according to its level.
This is close to what I want, but I want to color just a specific treeview item regardles... | Yes. You can attach information to the tree item using the TVITEM::lParam member. This value is sent with the NM_CUSTOMDRAW message in the nmcd.lItemlParam member of the NMTVCUSTOMDRAW struct.
|
62,734,135 | 62,734,892 | Read a file as binary/hex | I'm currently trying to read a file as hex value, like a hex editor do. For the explanation of the issue let's suppose I've a test.txt with a simple "Hello world" inside. I'm trying to read as hex with a program close to this following code.
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
... | Change this to :
while (!stream.eof()) {
unsigned char c;
stream >> c;
std::cout << static_cast<unsigned>(c) << " ";
}
This:
unsigned char c{};
stream >> std::noskipws;
while (stream >> c) {
std::cout << static_cast<unsigned>(c) << " ";
}
std::noskipws disables skipping of whitespace.
Read this excel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.