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 |
|---|---|---|---|---|
63,932,835 | 63,932,937 | Finding if a string is contained in another string without "find" in c++ | I wrote this program to find if a string is contained in another string (see paragraph below this, I tried to explain what I want it to do). When I test it, sometimes it works, most of the times it gives me the error "String subscript out of range". I'm very new to C++, I'd appreciate someone to tell me how can I impro... | #include <iostream>
#include <string>
int main()
{
std::string way, one;
std::cin >> way;
std::cin >> one;
bool found{};
for (size_t i = 0; i < way.size() - one.size()+1; i++)
{
if(one == way.substr(i, one.size())) {
found = true;
break;
}
}
std:... |
63,932,848 | 63,933,033 | Why am I not able to print 32.0 instead of 32 inspite of typeconversion? | So Here's my code. the inputs are
5
10 40 30 50 20
1 2 3 4 5
I'm trying to find the weighted mean of an array of size n, vector a holding the n elements with their corresponding weights in vector b. I'm unable to understand why 32 is being printed out instead of 32.0? Can someone tell me why and how I can change ... | Whether it prints 32 or 32.0 is a subject of output formatting. By default, it clips all unnecessary digits (and the decimal point as well) if possible. (The *1.0 doesn't help for this.)
The relevant functions are available in <iomanip>:
std::setprecision
std::setfixed.
Example:
#include <iomanip>
#include <iostream>... |
63,932,964 | 63,933,092 | Using smart pointers to keep track of data members that may be deleted | I have two classes A and B. I compute a B deterministically from an A. For each A, I want to keep track of the B with my_B for as long as it exists. Once the B is destructed, I want the my_B to be changed to something like nullptr.
class A{
// stuff
public:
B ComputeB(){
if (my_B is null){
B res... | You can return a std::shared_ptr from ComputeB(), and make my_B a std::weak_ptr. Something like this:
std::shared_ptr<B> ComputeB() {
if (my_B.expired()) {
auto result = std::make_shared<B>(*this);
my_B = result;
return result;
} else {
return std::shared_ptr<B>(my_B);
}
}
p... |
63,933,123 | 63,933,248 | Unable to read memory when accessing file using fstream | I know this question as been asked before, but it was never answered and my situation is different
I am creating a student struct to store student information:
struct Student {
std::string m_firstname = "";
std::string m_lastname = "";
int m_testscore = {0};
char m_grade;
};
I want to read the student name fro... | The error occurred because I was promising to return a type that was never returned with the read_data() function. it should be:
void read_data() {
Student students[20];
// Open input file
std::ifstream input("name.txt", std::ios::in);
// Check if file is good
if (!input) {
std::cout << "Err... |
63,933,163 | 63,938,557 | Why didn't `accumulate` make it into Ranges for C++20? | I suspect that accumulate isn't the only algorithm that didn't make it.
Maybe now there's a better way to perform accumulation (folding) over a range and therefore the accumulate is obsolete?
| No, accumulate is a perfectly reasonable algorithm, and it's not made obsolete by any other algorithm. The reason for it not being included in c++20 is simply a matter of time. It was considered better to add as much as possible with regards to ranges, without worrying about adding everything at once. Otherwise, there ... |
63,933,350 | 63,933,683 | Math function preventing vectorization in C++ | I have a code like the following and I wish to vectorize it.
I analyzed the whole code using an intel advisor.
It says I cant vectorize this because it has math functions in it.
It of course points out towards the sin and cos function used inside the loop.
How to vectorize this loop without using intel short vector mat... |
It says I cant vectorize this because it has math functions in it.
Actually it's the Ar += and Ai += terms that are preventing vectorisation, because it means that the output at j = 2 would depend on output for j = 1. If Ar and Ai are just outputs, you could make them arrays instead, and sum over them after running t... |
63,934,014 | 63,934,266 | C++ iterate over subvectors of size N | I have an input vector which can be of any size. What I want is to divide this vector into vectors of size 64 each and do something. The input vector's size should not necessarily be of size multiple to 64.
So let's say I have a vector of size 200, then I should divide it into 3 vectors of size 64 and 1 vector of size ... | You can use iterators to create a subvector:
vector<double> inputVector;
vector<vector<double>> resultVector;
for (auto it = inputVector.cbegin(), e = inputVector.cend(); it != inputVector.cend(); it = e) {
e = it + std::min<std::size_t>(inputVector.cend() - it, 64);
resultVector.emplace_back(it, e);
}
|
63,934,130 | 63,934,201 | How to create pointer with `make_shared` | I was looking at this page http://www.bnikolic.co.uk/blog/ql-fx-option-simple.html, on the implementation of shared_pointer.
There is one such line -
boost::shared_ptr<Exercise> americanExercise(new AmericanExercise(settlementDate, in.maturity));
I understand that, with this line, we are basically creating a shared po... | You seem to be missing the namespace from your second example. Also you can construct your derived type in make_shared.
boost::shared_ptr<Exercise> americanExercise = boost::make_shared<AmericanExercise>(settlementDate, in.maturity);
|
63,934,567 | 63,934,859 | Vector of pointers: Why does changing the pointer externally not change the vector element? | Please look at the following example:
#include <iostream>
#include <string>
#include <vector>
class Base {
public:
virtual void price() const = 0;
};
class D1 : public Base {
public:
virtual void price() const {
std::cout << "Price of D1\n";
}
};
class D2 : public Base {
public:
virtual void... | I'll try to explain it on a lower level.
First of all, understand that a pointer is essentially simply a variable that holds a value, which happens to be an address in memory.
Let's simplify things and assume that every type has the same size and that there are only 5 addresses of memory (on the heap). (Also I will ign... |
63,934,922 | 63,935,070 | How to simulate std::array<15,int &> with tuples | It is clear that std::array<type,count> can't store references. However it is possible to write
std::tuple<int &, int &, int &, int &, int &>
and get what you expect. See
#include <array>
#include <tuple>
#include <iostream>
int main(){
int a = 10;
int b = 20;
int c = 20;
// Does not compile
//st... | Based on a C++11 implementation of std::index_sequence (that I stuffed into the std14 namespace):
namespace impl {
template <class T, class Idx>
struct TupleAllSame;
template <class T, std::size_t... Idx>
struct TupleAllSame<T, std14::index_sequence<Idx...>> {
template <class U, std::size_t... |
63,935,323 | 63,935,400 | How to find multiple of a number in c++ | for example I have an variable of int data type...Now i want to find out all possible multiple pair of that number. Take integer as 12 So ans should be (3,4) (6,2) (1,12) ...using c++ only.
| Start iterating from 2 to square root of number in question. operator % allows check if value is actually a divider. Result of division is the second of the pair, if result of % is zero. If value is greater than the second from previous pair, you can stop.
|
63,935,438 | 63,935,587 | c++ - too many characters in character constant | I have the following legacy code:
unsigned int code = 'abcd';
I need to add one character to the above code:
unsigned int code = 'abcd2';
but then I get the following error: too many characters in character constant. Why using unsigned long int type doesn't resolve that issue ? Is it possible to fix it or I should mo... |
Why using unsigned long int type doesn't resolve that issue ?
Because the type of the variable has no effect on the type of the literal. The type of multi-char literal is int. There are no unsigned long multi-char literals.
Also, on some systems unsigned long has exactly as many bytes as int has.
Is it possible to f... |
63,935,564 | 63,935,700 | How does c++ interpret 6e(or any number with e) as an input? | When running this code and entering 6e or any other digit with e, the program does not recognise it and ends up on the else state. What am I doing wrong here?
#include "../std_lib_facilities.h"
int main() {
cout << "Please enter amount of money followed by the currency name:"
+ "y for yen, p for pound or ... | operator >> reads elements separated by whitespace (or until an unparseable character).
6e cannot be parsed as a double (but e is a valid character for scientific notation, so it is consumed), and cin goes into a failed state and every subsequent >> call fails.
For cin >> amount >> currency; to work the input should lo... |
63,936,984 | 63,993,727 | Why is my data in the frequency domain "mirrored" when performing (2d) IDFT into DFT using FFTW? | I am manually initializing a state in the 2d frequency domain by setting the real components of certain modes in a 16x16 data set. I then perform a 2d IDFT to acquire the real domain data. This all works as expected.
I then perform a DFT on the real domain data to get back (what should be) identical frequency modes to ... | You need to read up on the Discrete Fourier Transform.
For a real-valued time domain signal, the DFT has a conjugate symmetry:
F(k) = conj(F(N-k)),
with N the number of samples. By inverse transforming a non-symmetric frequency-domain signal, you obtain a complex-valued time-domain signal, but because you use a complex... |
63,937,024 | 63,937,329 | Does C++ include C99 or C89? | I am about to learn C++.There are two of the C language's syntax. Pointers and arrays. They are defined on the C Standard with so many subclauses. I know that C++ is a superset of C(It may be a generalization). Then are these features same as C++? If so, what version of C++ has what version of C?
|
Does C++ include C99 or C89?
Currently, C++ includes neither in its entirety, although the common subset of C and C++ is significant. Some features are missing, and there are incompatible differences between the languages. The non-normative sections of the C++ standard "Compatibility / C++ and ISO C [diff.iso]" and "... |
63,937,090 | 63,938,037 | C++ QuickSort implementation that sorts everything but a single element | This is my first time writing C++. I am trying to implement QuickSort referencing the MIT open course ware slides (Slides 4 and 17 specifically).
However, there is a bug:
input: 6 10 13 5 8 3 2 11
output: 2 5 3 6 8 11 10 13
I'm not sure why the 5 is out of place. My code seems to mirror the slides perfectly.
#includ... | The slide says for j ← p + 1 to q, which you turned to for (int j = p+1; j < q; j++). This is an off-by-one error.
|
63,937,385 | 63,939,022 | Is Assimp able to load embedded texture of a 3mf file? | Today I found a 3mf file with an embedded texture (by embedded I mean, the .png texture is present in the 3mf zip).
As I'm currently learning Assimp librairy I tried to load it and it worked fine, mesh are loaded correclty however, the png texture is not loaded at all.
Is Assimp able to load embedded texture of a 3mf ... | At the moment embedded textures are not supported in Assimp. Do you have the link to your file? We can try to add this feature. Just add a new issue here
|
63,937,519 | 63,938,468 | c++ add statements to an expression | There are somecases I have to add statement, like logs or trace to an expression, for example (I wanna log exactly the time for prep_stmt.executeQuery() and still I need its return value):
zdb::PreparedStatement prep_stmt = conn.prepareStatement(sql.data());
prep_stmt.setLLong(1, key);
zdb::ResultSet result = prep_stmt... | Maybe better to write a templated wrapper like this:
void log(const std::string& str)
{
std::cout << str << std::endl;
}
template <class Functor>
typename std::result_of<Functor()>::type my_wrapper(Functor f)
{
// do whatever you need inside
auto start = std::chrono::system_clock::now();
auto result = f();
a... |
63,938,495 | 63,939,677 | Branch points of the skeleton | My code should find the branch points of the skeleton, but the points it finds are not them. Most likely this is because IMREAD_COLOR = 1, not 0. But if I set the value to 0, then it stops finding and marking points altogether. Is it because the type of points (p1, p2, etc) does not match Mattype or something else? How... | There are a few things you should do with your code:
Read the image in using cv::imread("binary_skeleton.jpg", cv::IMREAD_GRAYSCALE). The option you are using forces the image to be RGB, but you are using the image as if if had a single channel.
Instead of comparing if (0 == p1) to find set pixels, use if (128 > p1).... |
63,938,881 | 63,939,097 | Why does the copy constructor (of a C++ class) get called when a function returns? | Here is a fragment of a program:
cls fun(cls a)
{
cls v;
v = a.scale(2.0);
return v;
}
int main()
{
cls a(0.0,1.0,2.0);
cls a2;
a2 = fun(a);
return 0;
}
In the above code assume that the class definition of the class "cls" has the constructor function and the "scale" function already... | The compiler generated copy constructor takes a const reference as the parameter.
An anonymous temporary is allowed to bind to a const reference, so compilation passes.
Note that the implied value copy created by return v; is elided in later C++ standards.
|
63,939,268 | 63,939,461 | Why is not Processing char in switch statement? C++ | I am trying to take and process the user decision by using char +, -, /, *, Why is switch statement ignoring them thus I don't see any mistake in my Code.
#include <iostream>
using namespace std;
void optionMenu();
double UserOutput(int);
int main ()
{
int UserChoice;
optionMenu();
cout << " Choice: ";
... | Your issue is right here:
int UserChoice;
optionMenu();
cout << " Choice: ";
cin >> UserChoice;
You're asking the user to enter +,-,/,* characters, but you're reading it into an int variable. This will cause std::cin to fail and 0 to be written into UserChoice (see here for more).
Instead, read that choice in as a ch... |
63,939,887 | 63,939,974 | Ownership and move semantics | Given the following definition of an owner, does it make any sense to talk about move semantics for objects that do not own resources?
https://www.stroustrup.com/resource-model.pdf
An owner is an object containing a pointer to an object allocated by new for which a delete is required.
Stated in another way, does it m... | Definitely. The definition quoted is a simplification. In general, any API that works with an acquire/release pattern can support move semantics. As a C++11 example, std::unique_lock is a movable object. It owns a mutex, not a heap allocation. The acquire/release methods are .lock and .unlock instead of new and delete.... |
63,939,964 | 63,940,191 | Context depended template argument deduction - type/value mismatch at argument | Minimal example
#include <vector>
#include <tuple>
template<typename T>
void function(std::vector<T> vec)
{
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
}
int main(int argc, char* args[])
{
std::vector<int> vec = {1,2,3};
auto tup = std::tuple<decltype(vec)::iterator>(vec.begin());
f... | Since iterator is a dependent name, you need to use the typename keyword to disambiguate it:
auto tup = std::tuple<typename decltype(vec)::iterator>(vec.begin());
// ^^^^^^^^
Note that vec is only a dependent name inside function. Inside main it's not dependent, and so you don't need to say typename... |
63,940,030 | 63,940,114 | Cannot infer template argument 'T' | I have pretty simple code:
#include <iostream>
#include <list>
using namespace std;
template <typename T, typename Function>
int ex_count(typename list<T>::iterator v, typename list<T>::iterator v2, Function match)
{
int count = 0;
while(v != v2)
{
if(match(*v))
count++;
++v;
... | The template parameter T can't be deduced because of non-deduced context.
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 explicitly specified. If... |
63,940,235 | 63,940,452 | How to dynamically update members that depend on other members? | Suppose I have a class MyClass:
class MyClass{
private:
vector<vector<float>> _vec;
public:
MyClass(vector<vector<float>> arg){
_vec = arg;
// shape is a 2-element vector where shape[0] = #elems in _vec
// and shape[1] = #elems in _vec[0]
shape.pu... |
How can I dynamically update MyClass.shape as and when MyClass._vec changes?
Write a function that updates shape, and call it whenever you change _vec.
But is there a better way of doing this?
Don't use shape member at all, but instead call _vec.size() and _vec.begin()->size() when you need those values. This way t... |
63,940,382 | 63,942,203 | Creating a type-safe and maintainable config file for C++ | I have a nested struct representing a configuration, say:
typedef struct Config_t {
bool IsOK = true;
struct Server_t {
string Address = "192.168.1.50";
unsigned short Port = 9000;
// macro sets up serialization for a struct by member
// by adding << and >> operators.
ALLOW_SERIAL(Server_t, Ad... | I've used operator-> to achieve some similar things before. We can let it return a proxy class that locks a mutex and also dereferences to the underlying Config_t object.
class ConfigWrapper {
private:
Config_t cfg_;
string file_;
std::mutex mux;
class MutexWrapper {
private:
std::lock_guard<std::m... |
63,941,067 | 63,943,531 | c++ how to bind a general function with multiple map object and call it clear function | My system defines multiple unordered_map-like data, e.g.
std::unordered_map< int, int> int_map;
std::unordered_map< int, double> double_map;
std::unordered_map< string, string> string_map;
std::unordered_map< string, string> string_map_2;
...
std::unordered_map< string, vecto... | you can have single template to do it if you just don't want to dupe code.
#include <functional>
#include <unordered_map>
#include <iostream>
using namespace std;
void register_undo_handler(void(*callback)(void*), void* data){
callback(data); //I'd not gonna implement all undo in C so let me do this instead
}
tem... |
63,941,337 | 63,941,851 | C++ threads why the cout statements are not getting printed even after fflush | I have a sample code:
#include <iostream> // std::cout
#include <thread> // std::thread
void pause_thread(int n)
{
if(n != 4)
{
std::this_thread::sleep_for(std::chrono::seconds(100));
std::cout << "pause of " << 100 << " seconds ended\n";
}
std::cout << "Thread number " << ... | "Joinable" does not imply that the thread is still executing.
You first join thread #0. This will take ~100 seconds.
During that time, thread #4 finishes since it doesn't sleep, and the other threads are sleeping.
If the threads happen to be scheduled differently, any of the "sleep threads" could be printing that they... |
63,941,833 | 63,941,924 | Passing arbitrary random number distributions to a function | I am writing a matrix initialization method that fills a matrix of type T with random numbers of type T from a random number distribution that the user can choose. The section of my implementation file would look something like
// file name: Matrix.h
#include <random>
typedef std::default_random_engine rnd_eng;
templ... | What you are asking for is a function that accepts multiple different underlying types of objects (generators) that share a common signature, but no hierarchy.
This is a problem most easily solved with templates:
template<class T, int N, int M>
class Matrix{
...
template <typename RandomNumberDistribution>
... |
63,942,514 | 63,943,402 | Do C++20 ranges support group by functionality? | Sometimes it is quite useful to group/partition the objects based on value of one of their member functions(either getter or some computation).
Do C++20 ranges enable something like
std::vector<Person> {{.Age=23, .Name = "Alice"}, {.Age=25, .Name = "Bob"}, {.Age=23, .Name = "Chad"}};
// group by .Age and put into std::... | There are really three different kinds of functionalities that languages offer under the name group by:
Take a binary predicate ((T, T) -> bool) and group consecutive elements for which that predicate evaluates to true (e.g. Haskell, Elixir, D, range-v3 kind of)
Take a unary function (T -> U) and group consecutive ele... |
63,942,650 | 63,942,748 | C++ Integral Approximation- For Loop function Addition | Please bear with me as I am new to coding. I am trying to approximate the integral 4 / (1+x^2) from 0 to 1 using C++. I am required to use the formula:
P = 1/n [sum from i to n-1: f(x)] with x = (i+0.5)/n and i equal to 0, 1, 2, 3.... n-1.
Specifically I am struggling with writing the portion of the code to add f(x) fo... | There are 2 issues in your code. In your loop that calculates the sum, you are not initializing s. Also, you are resetting s to a different value every time you iterate, so the sum is not added correctly.
You can write the loop like this:
double s = 0;
for ( i=0; i<=(n-1); i++)
{
double x = (i ... |
63,942,740 | 63,942,853 | Initializing member variables with a lambda | Suppose I have a template class:
template<class T>
class Entity
{
public:
Entity(std::function<void(T*)> init, int idx) : index(idx)
{
init(data);
}
T* getData(){ return Data; }
private:
int index;
T* data;
};
And I create an instance of the class as so:
Entity<Button> myEnt([](Button* button){
but... | You are passing data to init() by value, which means the lambda is receiving a copy of data. So any value the lambda assigns to its input parameter will be assigned to the copy and not reflected back to data.
You need to pass data by reference instead, eg:
template<class T>
class Entity
{
public:
Entity(std::functio... |
63,942,932 | 63,945,827 | Memory considerations for an array in a function with a variable size | I have the size of the array as a variable instead of as an actual number. For my program I call the function diagonalize three times with different values of array_size -- would the array be allocated and deallocated for each value of array_size, or would only one array be used and overwritten during the program? The... | In
void diagonalize(unsigned long long int array_size) {
lapack_complex_double z[array_size];
}
z is variable-length array (VLA) feature from C99, C++ standard doesn't have it, but some C++ compilers support it as an extension for built-in types.
The default stack size is around 8MB on Linux, so using unsigned lon... |
63,942,976 | 63,943,206 | Issue with template argument deduction | I have a quite simple template problem.
I wanted to have some mathematical functions that work with scalars and vectors. For arguments, I want my scalars to be passed by copy, and my vectors by reference.
So I ended up using a templated helper struct.
But when I use my functions, the compiler does not manage to deduce ... | This will not work, since all the uses of T (which are CopyOrConstRef_t<T>) in the argument list of Lerp are in non-deduced contexts:
The non-deduced contexts are:
The nested-name-specifier of a type that was specified using a qualified-id.
Here's an example from the reference:
Template parameters do not particip... |
63,943,379 | 63,944,033 | Function to reverse the bits of the hex number in decimal and return hex value of the reversed bits | Given hex number 0x1234 passed as parameter to function I trying to write the function that will reverse the bit of the number and return that reversed number 0x2C48
I can explain the solution which I am trying to reach.
0x1234 this is the input hex number which will be given to the function
0x2C48 will be the output w... | There are many methods to do this. Here is one using bit shifting.
Let A be the original value, such as 1100.
Let B be the result value.
+---+---+---+---+ +---+---+---+---+
| 1 | 1 | 0 | 0 | | 0 | 0 | 0 | 0 |
+---+---+---+---+ +---+---+---+---+
A B
Step 1: Set the least si... |
63,943,706 | 63,944,316 | Maybe and Either monads, short-circuiting, and performance | Functional Programming in C++, at page 214, with reference to an expected<T,E> monad which is the same as Haskell's Either, reads
[...] as soon as any of the functions you're binding to returns an error, the execution will stop and return that error to the caller.
Then, in a caption just below, it reads
If you call ... | Consider the following expression:
result :: Maybe Int
result = x >>= f >>= g >>= h
In that expression, of course, x :: Maybe a for some a, and each of f, g, and h are functions, with h returning Maybe Int but the intermediate types of the pipeline could be anything wrapped in a Maybe. Perhaps f :: String -> Maybe Str... |
63,943,720 | 63,943,974 | A Function in an application(.exe) should be called only once regardless of how many times I run the same application | Suppose there are two functions, one to print "hello" and other to print "world" and I call these two functions inside the main function. Now, when I compile it will create a .exe file. When I run this .exe for the first time both functions will print "hello world".This .exe is terminated.
But if I run the same .exe fo... |
Can I achieve it without any external help that the application itself
should be capable of performing this behaviour?
Not by any means defined by C or C++, and probably not on Windows at all.
You have to somehow, somewhere memorialize the fact that the one-time function has been called. If you have nothing but the ... |
63,943,809 | 63,944,042 | C++: Statically initialize container with data from other statically initialized container | Is there a way to map keys/values of one statically initialized container to other statically initializing one? Something like that:
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
( "three" , 3 ),
( "seven" , 7 ),
( "twelve", 12 )
};
//how to statical... | no need for special library or c++20
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
{ "three" , 3 },
{ "seven" , 7 },
{ "twelve", 12 }
};
//how to statically extract pairs' first values?
const set< string > my_strings = []{
set<string> data;
f... |
63,944,077 | 63,944,134 | Passing a pointer into methods in C++ resulting in weird output | I am trying to convert a string of characters to Upper case by passing a pointer into a toUpper method that I have created. The logic seems to be fine but I get a weird output like ìëïà. Any ideas where I have gone wrong here?
#include <iostream>
#include <string.h>
using namespace std;
void toUpper(char *);
int ma... | Your problem boils down to bad magic numbers, which makes it nearly impossible to tell even from a close look because they're magic numbers!
Instead, I'd use character literals to make things obvious:
if(asciiValue >= 'a' && asciiValue <= 'z')
{
asciiValue = asciiValue + ('a' - 'A');
p[i] = asciiValue;
}
Now i... |
63,944,091 | 63,944,800 | Libvirt virDomainGetInfo() results in segmentation fault | I am following an example from Libvirt's documentation to list all domains using virConnectListAllDomains. The function is working, and it shows the correct number of active domains. Now I am trying to use virDomainGetInfo to print information about domain but I am getting a segmentation fault. Below is the code and fo... | To pass the structure to be filled in,
Change:
virDomainInfoPtr domainInfo;
int virRet;
virRet = virDomainGetInfo(domains[i], domainInfo);
To:
virDomainInfo domainInfo;
int virRet;
virRet = virDomainGetInfo(domains[i], &domainInfo);
|
63,944,156 | 63,944,598 | Blocking queue with order guarantee | I have 8 threads that process an image in strips. The strips are ordered in raster order. When each thread is finished with a strip, the thread adds its strip id number to a blocking queue. I want the queue to only allow a pop when the number is in sequence from 0 to N. So, regardless of the order in which the threads... | The structure you want is a min heap (see std::priority_queue). This gives the element with the lowest ID.
Wake up the consumer thread every time the newly added element is at the beginning of the queue.
Consume all elements that are in sequence in one go.
|
63,944,197 | 63,945,090 | How can I draw C++ concepts in UML class diagram? | How would I draw C++ concepts in an UML class diagram?
Specifically, I have the following code:
template<typename T>
concept Printable = requires(T a, std::ostream &where) {
{ where << a };
};
template<typename T>
concept Identifiable = requires(T a) {
{ a.getId() } -> std::convertible_to<std::string>;
};
tem... | The C++ concepts defines constraints on the types associated with a template class:
Since UML supports class template, you would typically express this constraints for its parameters, between curly brackets, either in natural language or in OCL. The former is perfect at an early design stage. But you could as well... |
63,944,299 | 63,944,374 | How do programs calculate square roots? | I understand that this is a pretty math-y question, but how do programs get square roots? From what I've read, this is something that is usually native to the cpu of a device, but I need to be able to do it, probably in c++ (although that's irrelevant).
The reason I need to know about this specifically is that I have a... | Computers use a method that people have actually been using since babylonian times:
def square_root(number):
old_guess = 1
guess = 2
while old_guess != guess:
old_guess = guess
guess = ((number / guess) + guess ) / 2
return guess
|
63,944,410 | 63,944,759 | How can I implement `my_class_instance(a, b) = value` operation | I have a class Flight and I need to implement two operations:
Flight s;
auto value = s(1, 2);
s(3, 4) = value;
I know how to implement first operation:
class Flight
{
public:
int operator()(int a, int b) {
return cache.for(a, b).get();
}
private:
// cache
}
But I don't know implement second operation. So... | There is no ()= operator. It is two separate operators - operator(), and then operator= on the return value of operator().
Since you want to use separate get() and set() methods inside the cache, you will have to make your Flight::operator() return a helper proxy, and then you can implement proxy::operator int to call... |
63,944,427 | 63,944,486 | C++ Variable destruction | Suppose I have this:
std::wstring str = std::to_wstring(100);
str = std::to_wstring(1000); // Is the previous str destroyed?
If I reassign the local variable to another variable, is the old one destroyed?
|
Is the previous str destroyed?
Yes. There is no memory management happening in the code snippet you shared, it's all automatic storage.
|
63,944,765 | 63,945,104 | Marking a function `noexcept` that could cause an exception constructing the returned object | Consider this function:
std::vector<unsigned> copy(std::vector<unsigned> const& v) noexcept
{ return v; }
int main()
{
try {
(void)copy({1, 2, 3});
} catch(...) {}
}
The construction by copy of the returned object could throw. In this case, would the exception be propagated to the caller (i.e. it's cons... | C++17 had a wording change that added sequencing around the return statement. The following paragraph was added.
[stmt.return]
3 The copy-initialization of the result of the call is sequenced
before the destruction of temporaries at the end of the
full-expression established by the operand of the return statement,
whi... |
63,945,051 | 63,953,825 | Exception safety in the composite pattern | I used the composite pattern to represent devices, which I would like to shut down before killing their power (calling their dtor).
I ran into a problem trying to group the devices, especially regarding their state.
How would I proceed in the following scenario:
class IDevice
{
public:
virtual void shutdown() = 0;
... | The main big problem is that you want to throw from the dtor.
https://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml has a nice explanation of why this does not play nicely with the language and its idioms.
In general, if you expect that a device can fail at shutting down, then you should probably handle this part expl... |
63,945,844 | 63,946,092 | Is it possible to have a "named constructor" return a privately-constructed, non-moveable, non-copyable std::optional<T>? | I mostly work on system-level C++ projects that don't allow exceptions to be thrown, but RAII is (rightfully) strongly encouraged. Right now, we handle the lack of failing constructors using infamous tricks many C++ programmers are familiar with, like:
Trivial constructor followed by a call to bool init(Args...) to do... | If you want to make any indirect object construction work (emplace in its various forms, in_place constructors of optional, make_shared, etc) , the constructor in question must be public. You can make a constructor public without allowing all public use by using something called a private key.
Basically, you create a t... |
63,945,852 | 63,945,938 | Lining up columns in C++ | I am trying to line up columns using the standard <iostream> library and nothing else (so I can't use std::setw, this is for a school exercise).
This is currently my code:
cout << endl;
cout << number_1 << endl;
cout << number_2 << " x" << endl;
cout << "--" << endl;
cout << number_3 << endl;
cout << number_4 << " +" <... | set max width and align right
cout.width(4); cout << right << "245"<< endl;
cout.width(4); cout << right << "2100" << endl;
But...the solution expected by your teacher is this:
string cout_width(int w, string s){
int len = s.length();
while(len++ < w)
s.insert(0, " ");
return s;
}
int main(... |
63,946,397 | 63,949,079 | C++ How to pass a type member of a class as a template paremeter? | I'm trying to create a file manager, but I have one problem in the constructor.
This is the record struct.
struct Records {
char code[5];
char name[20];
char career[15];
Records() = default;
Records(string code, string name, string career) {
// ...
// Constructor
// ...
... | Code by @JerryJeremiah
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <string.h>
#include <algorithm>
using std::sort;
struct Records {
char code[5];
char name[20];
char career[15];
Records() = default;
Records(string code, ... |
63,946,645 | 63,948,335 | Is there any difference between a deduced template arg and auto arg? | Are these two functions different in any meaningful way? Is there any reason to generally prefer one over the other?
void foo(auto x, auto &... y) { /* ... */ }
template<typename T, typename... Tx>
void foo(T x, Tx &... y) { /* ... */ }
I would tend to use the first when I don't need the type T handy because it's sho... | It is literally defined to be equivalent [dcl.fct]
An abbreviated function template is a function declaration that has one or more generic parameter type placeholders. An abbreviated function template is equivalent to a function template whose template-parameter-list includes one invented type template-parameter for e... |
63,946,790 | 63,946,829 | Issue using functions (c++) | so I am having a little bit of trouble getting this program to work without it throwing the errors:
"request for member 'insertArray' in 'arr', which is of non-class type 'int [10]' " and
"request for member 'print' in 'arr', which is of non-class type 'int [10]' ".
Both of those errors have to do with using my functio... | arr is just a plain-old C array, you can't define new functions on it. You need to define a class or struct if you want to do that.
What you have here is procedural code, so you're constrained by that model and must pass in arr as an argument.
I've tried to wrangle your original code into this form with as few modifica... |
63,947,195 | 63,947,217 | C++ | Comparing two arrays using std::mismatch (or another STL alternative) | I am faced with the task of comparing two c++ arrays that are of int data type. I specifically cannot use any loops (for, while) of my own, and was encouraged to use an STL function. I found std::mismatch() and it seems to be what I want, but I am unable to get it working with a basic array.
Here is my code:
#include... | std::mismatch returns a pair of iterators to the container, not a pair of ints. In this case, since you have an array, the iterator type is int*.
The simple solution is to deduce the type when calling it instead:
auto result = std::mismatch(a, a + 9, b);
From c++17, you can name the individual elements of the pair as ... |
63,947,319 | 63,947,433 | Writing and loading a large array to/from a file in C++ | I'm creating a large 2D array(5000*5000) of data which I need to use later in my program. The process of filling up the array takes 10 seconds but the array data in the end are always the same. So, I was thinking I could avoid these 10 seconds by reading the array from a file each time I run my program.
However, I can'... | Simply write out the entire array as-is in its original binary form, not in a textual form.
vec4* F = new vec4[size*size];
// fill and use the array as needed...
std::ofstream out("filename.data", std::ios_base::binary);
out.write((char*)F, sizeof(vec4)*(size*size));
delete[] F;
You can then read the file back into... |
63,947,352 | 63,969,053 | How to load a sf::Image from an array of pixels in SFML? | I would like to load an image in sfml from a 2d array containing 3 values for each pixel (RGB). The array would look something like this:
{
{{255, 255, 255}, {255, 255, 255}},
{{255, 255, 255}, {255, 255, 255}}
}
The array above describes a 2x2 image which is white. How can I turn this into an Image in sfml (sf::Ima... | If you want to create an sf::Image object from a pixel array, then you are interested in the sf::Image::create() member function overload that takes a const Uint8 *:
void sf::Image::create(unsigned int width, unsigned int height, const Uint8 * pixels);
As the name suggests, the last parameter, pixels, corresponds to... |
63,947,366 | 63,947,432 | Precision of double when reading from file | I'm trying to read double values from a file into a std::vector. However, I've noticed that the values do not match what is on the file, but has a slight but consistent shift of ~0.000000007. Is this normal?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
std::vector< dou... | In the range of 10^10, 64-bit IEEE 754 double-precision floating point numbers have a precision of about 10^-6. So, yes, this inconsistency is normal and cannot be avoided.
If you want higher precision, then you might want to try using long double. Some platforms provide hardware or software support for 80-bit or 128-b... |
63,947,613 | 63,948,874 | Compare a string to a list of Ints? C++ | I'm trying to have a string only work if it matches an int in the list.
Code
int Keys[] = { 23454563, 1262352, 634261253, 152352 };
string key;
int main()
{
cout << ("Please Enter Key: ");
cin >> key;
if (key = Keys)
{
//Activate Code
}
else
{
//Don't activate
}
}
I've... | hmm. First, I don't know why you have to input a 'string' instead of an 'int'. Also, why do you make 'key' a global variable? Just put it inside 'main'. Moreover, 'Keys' is an array and you can't compare a variable with an array.You have to search through the array using a loop.
My prefer answer
#include <iostream>
in... |
63,947,848 | 63,947,952 | Program with bound method is built but fails to launch | Consider following code compiled under C++11 with gcc:
#include <cstdio>
#include <functional>
#include <unordered_map>
using namespace std;
using namespace std::placeholders;
class Box
{
char* box;
public:
Box(): box(new char[128]) {}
~Box()
{
delete[] this->box;
}
void example(int a,... | This is a combination of several arcane aspects of C++:
unordered_map<char, function<void(int, int)>> methods = {
{'a', bind(&Box::example, box, _1, 8)}
};
If you change this to:
unordered_map<char, function<void(int, int)>> methods = {
{'a', bind(&Box::example, &box, _1, 8)}
};
The code should still compile,... |
63,947,852 | 64,172,927 | C++ how to prevent import loops | I am a bit in the dark for the moment so I am trying stack overflow. My problem is that I have a classed named ‘Scene’ which will have a map of ‘GameObject’. The problem is that these GameObject need to use some function from there scene so I create a Scene* that is assigned to the main scene. The problem with this cas... | For those who got the same problem i just forgot you can do forward declaration and when you need to use the full class just import the files you need in the .cpp file of your class.
|
63,948,129 | 63,948,219 | Is it possible to explicitly call a name mangled function? | Suppose I have something along the lines of
struct Foo {
void goo() {printf("Test");}
}
external void _ZN3Foo3gooEv(Foo *f);
int main() {
Foo f;
_ZN3Foo3gooEv(&f);
}
Is it possible to call Foo::goo() through the name mangled version of the function here?
Edit:
As a clarification, this is just an ... | You can, with some caveats.
You either have to use the member function in a way that code will be generated or have it be not inline, and your mangled definition should be extern "C" to prevent "double mangling". E.g.:
#include <cstdio>
struct Foo {
const char* message;
void goo();
};
void Foo::goo() {
st... |
63,948,391 | 63,952,050 | Anyone has experience on using GetAppContainerNamedObjectPath? | Recently I came across a Windows API called GetAppContainerNamedObjectPath. But I have no idea on how I can use it.
I found a msdn page for this api (https://learn.microsoft.com/en-us/windows/win32/api/securityappcontainer/nf-securityappcontainer-getappcontainernamedobjectpath). But it does not have a right example and... | if you call RtlGetLastNtStatus(); instead GetLastError(); after GetAppContainerNamedObjectPath you will got
STATUS_INVALID_PARAMETER_MIX - An invalid combination of parameters was specified.
this give you more info compare simply invalid parameter.
then look for function signature
BOOL
WINAPI
GetAppContainerNamedObject... |
63,948,418 | 63,948,455 | My program is not correctly outputting the amount of students in my struct | i am making a program which is supposed to collect input from the user by asking for id, name, units attempted, units earned and the gpa of a student and store that into a struct. Currently, when i input more than one student into the struct, it only outputs the last student in the array. What can i do to fix this?
Her... |
Currently, when i input more than one student into the struct, it only outputs the last student in the array.
It looks most likely that the scope of your i is incorrect:
int i = 0; //<-- this should be declared outside the `while` loop
As it stands, your i is scoped inside while loop, so it will be reset every... |
63,949,032 | 63,949,186 | The issue about the exception which occurs with return statement | #include <iostream>
struct A {
A(int id):id_(id){
std::cout<<"construct A with id: "<<id_<<"\n";
}
int id_;
~A(){
std::cout<<"destory A with id: "<< id_<<"\n";
}
A(A const&) = default;
};
struct Y {
~Y() noexcept(false) {
std::cout<<"destory Y\n";
throw 0;... |
Well, even if I agree that at #1 and #2 will create these temporary objects of type A,
Nothing said anything about "temporary objects" (which is a special term in C++ with a well-defined meaning, which is not applicable here). The return statement initializes the prvalue returned by the function.
If you search for in... |
63,949,182 | 63,949,601 | how to pass a string by pointer in C++? | In C++ programming i was passing string as pointer
Code:
#include<iostream>
using namespace std;
void changeString(string *s) {
// change s[1] to 'a' inside this function
}
int main(void) {
string s = "ayush";
changeString(&s);
cout<<s;
}
i wrote code *s[1] = 'a', but it is showing error. how do i acc... | According to the C++ Operator Precedence, subscript has higher priority than dereference.
So as @dxiv mentioned in comment *s[1] is parsed as *(s[1]).
So you need to use parenthesis to change priority as (*s)[1].
By the way, using string::replace instead of assign operator is safer way to change string.
Better yet, IMH... |
63,949,191 | 63,950,254 | How can we use mean filter as adaptive one? | When we have noise in background area then we can use mean filter to remove noise since there is no sharp features for our processing. when we do the noise removal for the image region which contains edges (finer details).This region completely blur and we miss the finer details.
Can we apply a filter such that which w... | A very good adaptive filter is the bilateral filter. It applies a Gaussian filter for smoothing, but additionally weighs each sample by how similar it is to the central value under the mask. Thus, it effectively only averages over pixels that have a similar value. In a flat region, all pixels have a similar value, henc... |
63,949,440 | 63,949,584 | Move unique_ptr ownership from one class to another | I want to create a unique pointer in one class, class A, then pass on the ownership to another class, class B. Am I ok doing such a thing?
The code below gives me error in getC:
error: call to deleted constructor of 'std::unique_ptr<C>
What am I doing wrong?
class A {
...
void func(shared_ptr<B> Bptr) {
A_pass = m... | Your question does not state where the compiler error occurs, but I would guess it’s the getC() member function:
class A {
...
unique_ptr<C> getC()
{
return A_pass;
}
unique_ptr<C> A_pass;
};
The function as written is attempting to copy A_pass, which of course is not possible for the std::unique_ptr<T> t... |
63,949,833 | 63,950,015 | Variadic template - type modifiers | Is it possible to wrap or change the type of variadic template arguments? E.g. when giving template arguments int, float, double to return a std::tuple<const int*, const float*, const double*> or a std::tuple<std::unique_ptr<int>, std::unique_ptr<float>, std::unique_ptr<double>>?
I'm asking because I've got this piece ... | Yes, you can define a type trait like this:
template <
template <typename...> typename V,
template <typename> typename Op,
typename... Args
>
struct modify {
using type = V<typename Op<Args>::type...>;
};
where V is a template template arguments that accommodate variadic template arguments such as std:variant... |
63,950,132 | 63,950,178 | CrossWord Puzzle getting error: no match for ‘operator==’ | Firstly I would like to say sorry if this is a repost, onto the question.
I'm new with c++ stl and got stuck at this point.
I have created this function for solving crossword puzzle in c++ but it is showing me the
prog.cpp:17:49: error: no match for ‘operator==’ (operand types are ‘__gnu_cxx::__alloc_traitsstd::allocat... | You're clearly getting confused between strings (which are sequences of characters) and chars (which are individual characters).
Look at this code
if(matrix[i][j]=='-' || matrix[i][j]==word[0])
matrix[i][j] is a string (because matrix is a 2D vector of strings) but '-' is a char and word[0] is a char (because word is ... |
63,950,392 | 63,950,685 | Why doesn't 'using A::X' avoid ambiguity with multiple inheritance? | This is similar to this question and this one, but I think (hope!) different enough to deserve an explanation.
I have a complex configuration framework, with decorator classes used to implement some common, simple actions (like flagging when a class Set accessor is called). I'm trying to introduce a new decorator (rat... | Two solutions.
If you really want to keep the private and multiple inheritance:
class A {
public:
void Set() {};
bool Ready() const {};
};
class B : private A {
};
class C : public B, public A {
public:
void SetParam() { C::A::Set(); }
};
Or if that is not needed, then a simpler one:
class A {
public:
... |
63,950,540 | 63,951,394 | Forcing clang to generate compilation error on this snippet of C++ code | I have this invalid code:
class X {
public:
virtual void func() = 0;
};
class JustDeclared {
X missing();
};
int main() { return 0; }
It doesn't compile under gcc because it's impossible to create an instance of an abstract class X, and exactly this has been declared as a return value of the JustDeclared::m... | Up until C++14, and in the original release of C++17, this is considered a bug in both Clang and MSVC, for Clang (see below) and likely for MSVC due to abstract class type diagnostics being performed at the time of function definition rather than at (first) function declaration (contrary to ISO standard rules). As is c... |
63,951,075 | 63,951,197 | How to return value from DLL using parameter of function as a pointer in C++? | I have a simple DLL:
dllmain.cpp:
#define MYDLLDIR
#include "pch.h"
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
...
}
void callByPtr(int *i) {
(*i)++;
}
pch.h
#include "framework.h"
... | Your exporting definitions are also not correct. Should be something like:
#ifdef MYDLL_EXPORT
#define MYDLLDIR __declspec(dllexport)
#else
#define MYDLLDIR __declspec(dllimport)
#endif
and use the same macro (MYDLLDIR) for both export (dll, #MYDLL_EXPORT defined) and import(clients, #MYDLL_EXPORT NOT defined)
You ha... |
63,951,270 | 63,952,100 | Using default copy constructor corrupts a tree in C++ | For example:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct TreeNode {
vector<TreeNode> children;
string name;
};
int main() {
TreeNode leafNode;
leafNode.name="c";
TreeNode middleNode;
middleNode.name="b";
middleNode.children.push_back(leafNode);
... | As others have pointed out in the comments, you should really try to setup a debugger and debug your code first. That is how you learn a lot in programming.
However, if you are not used to debugging it will probably be hard for you to find the issue, since the code in question is compiler generated.
You are right that ... |
63,951,549 | 63,951,780 | Is this the right way to use std::move? | I am trying to save a copy of char[10] in the below code snippet, just would like to know if this is the right way to use std::move and this will in fact save a copy of char[10] as Struct2 object is being constructed.
#include <string>
#include <iostream>
#include <cstring>
#include <memory>
using namespace std;
stru... | A C array has the same semantics for move and copy. In other words a copy and a move of a C array do the exact same thing.
The advantage will be on std::string, e.g. member Struct1::b.
And yes, that is the correct syntax/usage of std:: move.
|
63,951,571 | 63,954,157 | Are function declarations with abstract class types ill-formed? | Inspired by this question, I had a look around the standard. There is a note in [class.abstract]
[Note: An abstract class type cannot be used as a parameter or return type of a function being defined ([dcl.fct]) or called ([expr.call]), except as specified in [dcl.type.simple]. [...]
For definitions [dcl.fct.def.gene... | This is P0929. Prior to C++20, function declarations are also ill-formed, but it lead to surprising semantics. Suppose
struct S;
S foo(); // 1
struct S { virtual void bar() = 0; }; // 2
At 1, the function is well-formed, yet 2 retroactively made it ill-formed. This is highly unintuitive, and so was changed.
|
63,951,606 | 63,951,901 | I can't double characters inside string with function | I am trying to create a simple function that double the characters inside of a string and outputs the new string. Ex. "hello world" would become "hheelloo wwoorrlldd" However, with the function I wrote, the output is empty. If anyone can tell me why this is, I'd greatly appreciate it. Thank you!
using namespace std;
st... | Altough the solution by songyuanyao is nice, I think more C++ functions can be used...
#include <string>
#include <string_view>
// use string view, so a character array is also accepted
std::string DoubleChar(std::string_view const &str) noexcept {
std::string newString;
newString.reserve(str.size() * 2);
... |
63,951,782 | 63,951,865 | How can I disable changing tabs in a QTabWidget? | I have a QTabWidget with multiple tabs. I want to disble the tabwidget itself so that the user cannot change the current tab, but the contents of the current tab have to stay enabled. How can I achive this in Qt?
If I disable the entire QTabWidget, the contents of the current tab will get disabled as well, which I don'... | I did some more research and found a solution, what I want is to disable the tabBar of my QTabWidget, like this:
ui->mytabWidget->tabBar()->setEnabled(false);
|
63,952,131 | 64,460,456 | Visual studio SOMETIMES loads symbols and sometimes does not | I am working on a code in c++. This code is compiled into a dll file which is loaded by a java application. When debugging, I normally run the application (from Eclipse) and attach to javaw.exe process in Visual studio 2017. This worked fine for a long time until I got a new computer (with same operating system, window... | in the "Attach to Process" window (Debug>>Attach to Process), the "Attach to:" field is set to "Automatic" by default.
In my case, I was debugging native code, but there were some small parts of the big project that dealt with exporting to/importing from excel. So visual studio sometimes (specially when the app had jus... |
63,952,326 | 63,952,541 | Can concepts be used to put a constraint on values as well as types? | Concepts can be used to put a constraint on types as template parameters like the example below:
template<typename t, int v>
concept the_concept1 = sizeof(t) > v;
template<int v, the_concept1<v> t>
struct some_struct1{};
I am trying to use a similar method with values like the example below:
template<int v1, int v2>
... | If you want to use a concept as a named type constraint on a template parameter, as in your example, the concept needs to apply to a type template parameter.
You can still define concepts that apply only to e.g. non-type template parameters, however, as long as you use it in a context which allows these; e.g. using a r... |
63,952,494 | 63,952,770 | How to find the size of a single index of string vector and print index if size equals a specific number? | I have a vector of strings and now I want to print a single index of that vector if the size of that index equals 4, for example.
std::vector<string> str = {"Time", "Hello", "User"};
I know how to iterate through the vector and print out the indices but I do not know how to get the size of, for example, the first inde... | Have a look at std::string::size() and If you are comfort with range loop
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> str = {"Time", "Hello", "User"};
for (const auto &s: str)
{
if(s.size() == 4)
{
std::cout<<s;
bre... |
63,952,759 | 63,953,368 | Variadic function and variadic template overloading lookup | I have a function with 2 overloaded arguments
template<typename... Args>
void f(Args&&...) {
cout << "Args..." << endl;
}
void f(...) {
cout << "..." << endl;
}
Can someone explain how does the lookup work? In my opinion, purpose of each function is the same (except first one is c++ style and second is c sty... | Yes there are many rules around this in C++.
When the compiler encounters a call like f(5, 10), first a list of viable candidates is synthesized, which involves instantiation of function templates (which involves deduction of template arguments).
Then, if the list has more than one candidate, overload resolution is per... |
63,952,768 | 63,952,833 | Do you need to store the std::future return value from std::async? | Consider the follow code:
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
void func()
{
std::async(std::launch::async, []{std::this_thread::sleep_for(std::chrono::milliseconds(1000)); });
}
int main()
{
std::cout << "start " << std::chrono::duration_cast<std::chrono::milliseconds>(s... | If the std::future is created via std::async, the destructor waits for end of the task. This does not mean that the task does not run in parallel - it just waits for the end of the task at the end of scope of variable. Yet it makes usage of std::async without storing a std::future a bit tricky and I would generally rec... |
63,952,981 | 63,953,462 | Is it always safe to return limit numbers (e.g. INT_MAX) to signify false? | Say, I have the following (member) function that returns the nearest left or right side of a rect, if the rect has been hit:
int hit(int x)
{
if (rc.left <= x && x < rc.right)
{
if (x <= (rc.left + size.width / 2)) return rc.left;
else return rc.right;
}
else return INT_MAX;
}
My concer... |
My concern is that INT_MAX, which is just a macro of a number on my machine, can't be represented on machine on which the code will run.
INT_MAX is not a fixed value. Yes, it is a macro, but different machines will have it differently defined. It is per machine, per compiler just like almost every other thing. The co... |
63,953,373 | 63,955,209 | How to ignore the rest of the line? | I have written a program that is graded by its speed, and I assume that generally I/O is the bottleneck even when the inputs are read from a file (and not manually inserted). In some cases, the program does not need the whole input of the current line and should just continue reading on the next line of input.
I have f... |
more input numbers remaining on that line than UINT_MAX
You want to use
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::numeric_limits<std::streamsize>::max() is a special value that instructs ignore not to count characters. Even if your line is longer than that (which is rather unlikely, unless ... |
63,953,536 | 63,954,977 | Tell me the Input in which this code will give incorrect Output | There's a problem, which I've to solve in c++. I've written the whole code and it's working in the given test cases but when I'm submitting it, It's saying wrong answer. I can't understand that why is it showing wrong answer.
I request you to tell me an input for the given code, which will give incorrect output so I ca... | As noted in the comments: Just picking the first two neighbours that have the same value and combining those will lead to suboptimal results.
You will need to investigate which two neighbours you should combine somehow. When you have combined two neighbours you then need to investigate which neighbours to combine on th... |
63,953,555 | 63,955,061 | C++ How to set char array to hexadecimal enum | Here is my enum:
enum ServerOpcode : uint16_t{
SMSG_AUTH_CONNECTION_RESPONSE = 0x001,
SMSG_LOGIN_REQUEST_RESPONSE = 0x002,
SMSG_LOGIN_REQUEST_RESPONSE_TEST = 0x0A6,
};
Here is my char array:
enum { body_length = 1024 };
enum { header_length = 8 };
cha... | The code
header_[header_length] = serverOpcode;
assigns the byte value of the enum into the memory address header_+8.
You should replace this code with
snprintf(header_,header_length,"%x\n",serverOpcode);
which safely formats the byte value into hex string and stores into header_. By safely, I meant header_length res... |
63,953,997 | 63,954,675 | mongocxx count documents in collection | Counting the number of documents in a collection is easy and fast (apparently constant time) in the shell.
> db.my_collection.count()
12345678
>
In C++ I try this:
mongocxx::client client;
mongocxx::database db = MongoInit(client, ...);
vector<string> collection_names;
mongocxx::cursor cursor = db.list_collections();
... | count and count_documents are very different functions.
MongoDB maintains metadata about each collection which contains the number of documents stored. This number is incremented when a document is inserted, and decremented when one is deleted. It is possible for this number to get out of sync with the collection, so... |
63,954,060 | 63,956,528 | Solving a constructor problem that uses static polymorphism | I have a base class that allows the option to inherit from several other classes.
template<class T>
class Option1 {
protected:
T m_optional_1;
public:
void setOptional1(const unsigned int); // Initialized from a size
T getOptional1() const;
};
template<class T>
class Option2 {
protected:
T m_optional_... | I would suggest that you do not implicitly skip constructors for optional mixins that don't match, and instead let the caller initialize each mixin explicitly:
template<class T>
class Option1 {
// ...
public:
// Constructor(s)
Option1(const unsigned int) { }
// ...
};
template<class T>
class Option2 {... |
63,954,425 | 63,966,514 | Back Traversal issue in linked list | following is C++ written linked list with Node class and main function. List is traversing forward using "next()" function but producing execution time error when traverse back using "back()".
#include <iostream>
using namespace std;
class Node {
public:
int object;
Node *nextNode;
Node *pr... | First, let's fix the code:
bool next(){
if(currentNode == nullptr) return false;
// if next is null we are at the end, don't go futher
if ( currentNode->getNext() == nullptr ) return false;
currentNode = currentNode->getNext();
return true;
}
bool back(){
... |
63,954,484 | 63,954,945 | Get a description of ANativeWindow_lock error codes | I have an Android APP using Android NDK and a ANativeWindow. Sometimes, the app hangs and my logs show:
unable to lock window buffer (error code: -38)
Or
unable to lock window buffer (error code: -19)
This issue goes away if I press the power button to lock the device and again to unlock it. The app returns and start... | I believe these are INVALID_OPERATION and NO_INIT.
You can find the error codes typically used internally by the Android framework here.
As you can see, many of these error codes are defined as the negatives of error codes from errno.h. Those error codes can be found here (first 34) and here (the rest).
So, if for exam... |
63,955,355 | 63,955,611 | Unable to build protobuf 2.4.1 on Ubuntu | When I was trying to run make command to build protobuf on Ubuntu 20, I faced this error
google/protobuf/compiler/command_line_interface.cc:913:55: error: cannot bind rvalue reference of type ‘std::__cxx11::basic_string<char>&&’ to lvalue of type ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’}
913 | prot... | Three things spring to mind:
You may need to specify a given C++ version e.g. -std=c++11
It appears you can install multiple versions of gcc on Ubuntu 20 as well: https://linuxize.com/post/how-to-install-gcc-on-ubuntu-20-04/
If all else fails, you could create a docker image to perform your compilation, base the doc... |
63,955,371 | 63,955,480 | Can we assign const char* to a string in cpp? | Although my compiler doesn't throw an error while assigning const char* to a string, I am wondering if this assignment is really valid and will not throw some unexpected result
string name;
const char* name2 = "ABCD";
name = name2;
| You absolutely can.
std::string was meant to replace the tedious and error-prone C strings const char* so for it to be a good replacement/successor it'd need backwards compatibility with const char* which it does.
name = name2; calls operator= so if we check basic_strings overloads for this operator we can see (3):
ba... |
63,955,544 | 63,955,668 | Un-defined behavior when using hex values without Casting | This is the strangest problem I have ever encountered. I am programming a chess engine and I have a function that returns a rank mask. For example, Consider this 64-bit bitboard.
00000000
00000000
00000000
00000000
00000100
00000000
00000000
00000000
The 1 in the middle is a piece.
Now my function should return
000000... | 0xFF is an int. Assuming an int has 32 bits, shifting this value left by 32 will invoke undefined behavior.
In the second version, you are storing 0xFF in an unsigned integral type. This can be shifted any number of bits, and that operation is well defined. In your case, you are storing it in an unsigned int with 64 bi... |
63,955,568 | 63,963,718 | How to find the window that contains the QtVirtualKeyboard | I'm using qt widgets on embedded device and have problem with virtual keyboard. Keyboard is shown as fullscreen and overlaps all app.
In article Virtual keyboard top black screen in Yocto is described hack how to solve this issue.
In short, you need to find the QQuickWindow with the keyboard and call setMask on this wi... | To obtain all the windows you can use QGuiApplication::allWindows() but that is not enough since the QtVirtualKeyboard window is not necessarily created at the beginning, so the visibleChanged signal of the QInputMethod must be used. I did not filter using the information from the QQuickWindow since in general the appl... |
63,955,901 | 63,956,265 | Repeating elements in vector | I am a C++ student. And I need to solve this problem: "Write a program that receives a number and an array of the size of the given number. The program must find all the duplicates of the given numbers, push-back them to a vector of repeating elements, and print the vector". The requirements are I'm only allowed to use... | Consider what you're doing here:
if(foundInRepeated) {
continue;
} else {
for(int i = 0; i < n; ++i) { // why?
If the element at some index i (from the outer loop) is not found in repeatedElements, you're again iterating through the entire array, and adding elements that are repeated. But you already ... |
63,956,218 | 63,956,219 | unique_ptr for non-polymorphic derived class with C++20 destroying operator delete | C++20 new feature of destroying operator delete, allows to "hook" the call to the destructor and "replace" it with our own operation (e.g. theoretically, calling the proper destructor of a derived class).
Is it possible to use destroying operator delete, to allow a unique_ptr<A> to hold a pointer to an actual non-polym... | Yes, it is possible. In fact it resembles a use case raised in P0722 for Dynamic dispatch without vptrs.
Before C++20 A unique_ptr<A> holding a pointer to a derived class of A required either:
a virtual destructor in A -- OR
a custom deleter
The C++20 specification added new delete operator - destroying operator dele... |
63,956,748 | 63,957,026 | Assigning object to an object of different class | Given 2 classes class Euro and class Dollar
I've overloaded the assignment operators so object of same type pass their private value to each other.
MRE:
#ifndef EURO_H
#define EURO_H
#include <iostream>
#include <iomanip>
#include "Dollar.h"
class Euro
{
public:
Euro();
~Euro();
Euro(int ... | You are most probably facing the problem of cyclic dependency between two classes.
Your Euro class is including "Dollar.h" while most probably your Dollar class is including "Euro.h". One of the includes would be blocked by the include guard (ifdef / pragma once). Only one would appear above the other, they cannot be b... |
63,956,782 | 63,956,886 | Uniform Initialization to call a constructor other than initializer list | I am recently having a problem with uniform initialization on C++14 standard. I wrote a code which declares a class having two constructors, first one is parameterized constructor and the other one is a constructor having intializer_list. The code looks as follows,
#include <iostream>
#include <vector>
class MyClass f... | This code:
MyClass a2{ (1, 2) };
could not call the 2 argument constructor. What is happening is that in the expression (1,2), the 1 is evaluated before the comma operator, it is discarded, and the result of the expression is 2. This obviously calls the initializer_list constructor.
Enable warnings, e.g. with -Wall an... |
63,956,848 | 63,956,981 | Moving a vector into an unordered_set | I have a vector<T> that I would like to initialize unordered_set<T> with. vector<T> will never be used again afterwards.
How I've been doing it is the following
std::vector<T> v{ /* some large amount of data, typically strings */ };
std::unordered_set<T> ht;
std::move(v.begin(), v.end(), std::inserter(ht, ht.end()));
... | This solution actually requires more characters, but it does express the intent more directly:
std::unordered_set<T> ht(std::make_move_iterator(v.begin()),
std::make_move_iterator(v.end()));
|
63,956,875 | 63,956,910 | Not able to understand why friend function is not working | #include<iostream>
using namespace std;
class A;
void test(A &a);
class A
{
private:
int x;
int y;
friend void test();
};
void test(A &a)
{
a.x = 1;
a.y = 2;
cout << a.x << " " << a.y << endl;
}
int main()
{
A a;
test(a);
}
The errors I am getting are as follows-
1.erro... | #include <iostream>
using namespace std;
class A {
private:
int x;
int y;
public:
friend void test(A &);
};
void test(A &a) {
a.x=1;
a.y=2;
cout << a.x << " " << a.y << endl;
}
int main() {
A a;
test(a);
}
|
63,956,973 | 63,989,834 | How to use parallelise two independent for loops in openmp? | I have the following loop setting:
for( int k = 0 ; k < N ; j++ )
{
while( 1 )
{
for( int i = 0 ; i < N ; i++ )
{
int sum = 0;
for( int j = nums[i] ; j < nums[i+1] ; j++ )
{
sum = sum + nums[i];
}
}
if( sum == s... | As long as N is much bigger than the number of physical cpu cores at your disposal, you should not parallelize the inner loop as well. In parallel lingo one would say that the outer loop provides enough parallelism, such that trying to parallelize the inner loop will in the best case add more overhead due to thread cre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.