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 |
|---|---|---|---|---|
66,157,548 | 66,157,965 | How to use memset to fill in max value for an array? | Here is my code, I would need to fill in every element in the 2d array with the maximum size ( INT_MAX), however, my code was unable to work properly?
#include <iostream>
#include <string.h>
#include <limits.h>
using namespace std;
int main(){
int arr[10][10];
memset(arr,INT_MAX, sizeof (arr));
cout << arr[... | C++ Standard Library has a function fill_n to fill arrays with n values.
#include <algorithm>
...
std::fill_n(&arr[0][0], 100, INT_MAX);
The number of values may be brittle here - if you change the size of the array in future, you have to remember to change the hard-coded 100 to a new correct value.
It's good enough f... |
66,158,160 | 66,160,725 | Intuition behind getting distance from the end of vector versus just counting | I am trying to solve a GeeksForGeeks question as below:
Count the number of ways to divide an array into three contiguous parts having equal sum: Given an array of n numbers, find the number of index pairs i and j such that sum of elements from 0 to i-1 is equal to the sum of elements from i to j is equal to the sum of... | You want to divide an array into three parts so that the sum of each partition is equal with others. let's assume our partitions are P1, P2, P3. we want this relationship:
P1=P2=P3=x
also we have P1 + P2 + P3 = 3x = total sum of array
so it is obvious that the sum of our array must be a multiple of 3 otherwise it is no... |
66,158,252 | 66,167,285 | Order of includes with standard libraries and local headers | I'm generating bitmap file. The program compiles every time but depending on order of #include at some point, it gives me good or corrupted .bmp file.
It is from a tutorial and all the file are here.
My structure is as follows:
main.cpp
#include <iostream>
#include "Bitmap.h"
using namespace std;
int main() {
Bitma... | The error is in BitmapInfoHeader.h
// issue #1: There is no guard to prevent re-entry into you header.
#pragma once // this should fix that, you can also place a classic
// #ifndef / #define / #endif guard, as advised by the
// C++ Core Guidelines
// https://isocpp.g... |
66,158,581 | 66,158,693 | C++ function will not print array to console in reverse | I'm working on homework for my c++ class we have just started arrays. I cannot figure out why the function reverse_array() does not print to the console when the function show_array() prints to the console without an issue. I've attempted googling the issue without success. I am just beginning c++ so it could be someth... | This loop for(x = 5; x < 5 ; x--) failed because it did not satisfy your condition the first time it checked (x = 5, but it needs to be smaller than 5 to enter the loop)
Change to this:
void reverse_array(int x, double dbval[]){
for(x = 4; x >= 0 ; x--){
cout << dbval[x] << " ";
}
cout << endl;
}
|
66,159,303 | 66,160,042 | how to get 3rd dimension array in 3d array in C++? | int array[3][3][8] = {
{{3, 4, 5}, {3, 5, 7}, {5, 6, 7}},
{{1, 3, 5}, {0, 1, 2, 3, 4, 5, 6, 7}, {1, 5, 7}},
{{1, 2, 3}, {1, 3, 7}, {0, 1, 7}}
};
User inputs x,y coordinate and direction, at that location they can only move in 0-7 direction. However, each location can only move towards certain direction. Th... | You could use std::copy:
#include <algorithm>
#include <iterator>
//...
int new_array[8];
std::copy(std::begin(array[1][1]),
std::end(array[1][1]),
new_array);
Done using std::array:
#include <array>
// ...
std::array<std::array<std::array<int, 8>, 3>, 3> array = {{
... |
66,159,459 | 66,159,623 | Get the return value of a parameter of async function | I want to get return value of the function wait_for_user_input before if condition!
int wait_for_user_input(){
// get input user
// return input user
}
const auto future = std::async( std::launch::async, wait_for_user_input);
while( future.wait_for( std::chrono::milliseconds(200) ) == std::future_status::timeou... | When using async, you need to call future::get() on your future.
|
66,160,337 | 66,160,383 | c++ for-loop end condition doesn't work when size() is used | vector<int> score= {1,1,1,1,1};
int z = score.size();
for(int j=score.size() - 1; j >= z - 5; --j)
cout << j << endl;
The code right now is fine but causes an error when I replace that line with:
for(int j=score.size() - 1; j >= score.size() - 5; --j)
From the print out, I've deducted it's because j go... | In this expression:
j >= z - 5
since both j and z are int the comparison works fine since the left hand side can be -1 when j becomes -1.
In this expression:
j >= score.size() - 5
the right hand side is unsigned, so the left hand side is implicitly converted to unsigned as well. When j becomes -1 that conversion give... |
66,160,515 | 66,160,599 | How to make an unordered_map only work with predefined keys? | How can I create an unordered_map, which will work only with the keys I want and throw an error otherwise.
For example, like in python:
my_dict = {
'a': 0,
'b': 0
}
my_dict['c'] # Will raise an error
But in C++, the equivalent code will initialize a 'c': 0 pair.
What to do? The most obvious solution is to che... |
but in c equivalent code will initialize 'c': 0 pair. What to do?
Simply don't use operator[].
You can use the at member function instead. It behaves similar to pythons dict:
Returns: A reference to the mapped_type corresponding to x in *this
Throws: An exception object of type out_of_range if no such element is ... |
66,160,597 | 66,161,001 | utsname/uname in C++ | I am writing a program that uses the <sys/utsname.h> header and the name functions to display the operating systems name, version, etc. I have included the header and have called the function, however, I am getting fatal errors stating that the header file is not recognized. Everything I have seen online shows the main... |
I am getting fatal errors stating that the header file is not recognized
You need to install the package which provides that header file (and much more) first.
Ubuntu:
sudo apt install linux-libc-dev
Fedora:
sudo dnf install glibc-headers
If you use any other OS, you need to find the correct package using the tools... |
66,160,819 | 66,161,094 | How to at a return value with double quote character enclosing it | I'm working on C++ homework, where we are creating overloaded functions. The instructor wants the values to be enclosed in ""s. I was able to accomplish that part, but he clarified that he wants the ""s to be added before the cout statements in the main() function.
The code below operates and produces an output that is... | If a function returns an int, double, etc then it CANT return values with quotes on them. Quotes only work on strings. You would have to do something like this instead:
#include <iostream>
#include <string>
using namespace std;
string iQuote(int);
string iQuote(double);
string iQuote(string);
int x ... |
66,160,964 | 66,161,684 | can I use a constructor to initialize any number of elements, in a class with a template that takes 1 and an associated structure? | i have such a class
template <typename T>
class Store {
private:
struct pointNode {
T data;
std::unique_ptr<pointNode> next;
pointNode():data(std::move(T{})),next(std::move(std::unique_ptr<pointNode>{})){}
pointNode(T n_data, std::unique_ptr<pointNode> ptr) : data(std::move(n_data... | If you are interested in a hacky two-liner:
#include <vector>
#include <memory>
#include <iostream>
template <typename T>
class Store {
private:
struct pointNode {
T data;
std::unique_ptr<pointNode> tail;
pointNode(T n_data, std::unique_ptr<pointNode> ptr) :
data(std::move(n_... |
66,160,973 | 66,233,033 | Finding world position of element in screen space | I'm attempting to find the world position of an object that exists in screen space. For example in the below screenshot the pistol and hands are rendered without being translated into world space (using only projectionMatrix * modelMatrix), while the other objects in the scene exist in world space (translated via proje... | If you render an object with standard model M, view V and P matrices, you get the P*V*M as the overall transformation. If you draw a model without the view transform, you're placing the object directly in view space. However, conceptually, that will be the same as first placing your object in world space (by applying a... |
66,161,298 | 66,161,539 | Error: no match for 'operator-' operand types are: string, int. Text display in cmd | I am trying to display this code in cmd so that it would send a text using two functions. The text:
"9 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around - 98 bottles of beer on the wall." However, it doesn't work and I don't know how to do it. Can anyone help?
#include <iostream>
#includ... | Some notable problems:
s is a string and you try to subtract 1 from it. A string does not support that operation.
You try to store the result of streaming to cout in a string (string text1=cout<<s ...). A string does not support that operation either.
You use global variables for an unclear purpose. I can't figure out... |
66,161,345 | 66,161,529 | error: invalid use of ‘class Animal::animalSound’ | could you please help me? I have a question about virtual functions.
I'm having a hard time getting this code to work. Could someone help me please? I can't get the attributes of the dog or cat to be printed at the end of the program.
This is the error code:
error: invalid use of ‘class Animal::soundDuringFeeding’
erro... | your structure and understanding of inheritance is little off, eather way you have to use it like this to achive common behavior:
#include <iostream>
using namespace std;
class Animal
{
public:
public:
virtual void eat() = 0;
// method has to have more general name but mainly the same name, the... |
66,161,448 | 66,163,585 | is there any way to prevent the derived class from initializing a base class reference | I have Base and Derived classes, and this code:
Derived d; Base& b = d;
Is there any cast in this initialization? Сan i theoretically disable this?
| Use private inheritance.
class derived : private base {};
|
66,161,484 | 66,161,681 | C++ Sorting numbers in arrays | I am trying to get this out put:
1 10
2 9
3 8
4 7
5 6
How do I do that?
My code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int n=10;
int Tab[n]={1,2,3,4,5,6,7,8,9,10};
for(int i=0; i<5; i++)
for(int j=5; j>=0; ... |
How do I do that?
You do not need 2 loops, you just use one loop and calculate second index:
for(int i=0; i<n/2; i++)
cout << Tab[i] << " " << Tab[n-i-1] << endl;
Live example
PS in this form for array with odd number of elements it will skip middle one. If you want it to be printed twice instead, chang... |
66,161,884 | 66,162,015 | Does a mutex lock apply to functions called after locking? | I'm trying to make a DirectX renderer for my game. I've heard that multi-threading is the best practice for optimization, so I'm trying my hand. I've got a basic renderer down, and I'm implementing multi-threading. So as the title says, Does a std::mutex lock apply to called functions?
void DXRenderer::draw(IDirect3DDe... |
As an example, if 2 threads called DXRenderer::draw(), would both threads call drawFRect
No, because only 1 thread at a time can hold the lock on the mutex.
would it wait until the mutex has been unlocked?
Yes. That is the whole point of a mutex. Once a thread owns the lock on a mutex, any other thread that tries... |
66,161,993 | 66,162,038 | Why I am not able to access string individual chars using index | string strMap[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//string digits received as parameter in function // digits = "234";
Accessing it as below:
int digitmapIndex = digits[index] - 46; //index is some int 0,1 etc..
int mapstr_len = strMap[digitmapIndex];
or
int mapstr_len = strMap[digits[i... | This line makes no sense:
int mapstr_len = strMap[digitmapIndex];
strMap[digitmapIndex] is a string object, and cannot be assigned to an int.
auto temp = strMap[digitmapIndex];
From temp, you can access its chars by index.
|
66,162,199 | 66,162,289 | C++: How to create a member unordered_map with values of pointers to functions | This question answers how to do it for a regular unordered_map, but what about the member one? The IDE reports the error in the comment. opcodes maps characters to pointers to functions, which should be called on behalf of concrete instances. Also I wonder if it's possible to make it constexpr.
// Foo.cpp
class Foo {
... |
How to create a member unordered_map with values of pointers to functions?
Like this:
struct example {
using fun = return_type(/*arg types*/);
std::unordered_map<key_type, fun*> map;
};
typedef void (*operation)();
static const std::unordered_map<char, operation> opcodes{
{'1', &Foo::operation1},
... |
66,162,465 | 66,165,482 | Maximum height of a huffman coding tree | What is the maximum height of a tree made with the huffman coding algorithm assuming that all bytes are accepted into it.
I'm curious since I somehow managed to get a path of 9 bits when I tried to compress I file which I generated randomly. Which means that I essentially inflate the size of the file. Though there migh... | If by "all bytes" you mean all 256 possible byte values as your set of symbols, the answer is that the maximum depth, and so the length of the longest code, is 255.
To get this though requires very large numbers for the frequencies of the symbols. The sequence that does this with the smallest total count are the Lucas ... |
66,162,539 | 66,162,812 | How to locally store 2D Array Passed in Class Declaration | I'm trying to locally store a 2D array in a private member variable but I'm not sure how to allocate the memory.
class Class1{
public:
Class1(string strings[][2], int size){
for(int i = 0; i < size; i++){
this->strings[i][0] = strings[i][0];
this->strings[i][1] = strings[i... | A way to do that would be :
class Class1 {
public:
Class1(string strings[][2], int size) {
this->strings = new string*[size];
for (int i = 0; i < size; i++) {
this->strings[i] = new string[2];
this->strings[i][0] = strings[i][0];
this->strings[i][1] = strings[i][1... |
66,162,898 | 66,163,937 | How can I split columns into a different vector | So there are 2 columns of these numbers:
1 10
2 -3
3 6
3 -6
1 -5
(data is taken from .txt) First column is number of client, second is balance I need to do operation like this. "for first client balance is equal to 10-5" "For second client client balance is equal to -3". How I can split columns to different for exam... | if you are sure that for n clients all the clients ID respect 0 <= ID <= n:
you can just use a vector account to store your data, where the client i balance is stored at account[i]
ifstream file2("number.txt");
vector<int> account;
int person, balance;
while (file2 >> person >> balance)
{
... |
66,163,187 | 66,226,009 | Finding neighbour vertices of a mesh inside a given radius | How to get neighbour vertices of a mesh inside a given radius using, e.g., CGAL?
A simple K-nearest search on vertices neglecting face and edge properties is not sufficient, because if meshes are close to each other, vertices of both will be found using a k-nearest approach.
An example:
blue -> query point, blue circl... | I solved the problem using the CGAL BGL package and the function CGAL::vertices_around_target.
A brief example:
typedef CGAL::Simple_cartesian<double> SCKernel;
typedef CGAL::Surface_mesh<SCKernel::Point_3> SurfaceMeshT;
typedef SurfaceMeshT::Vertex_index VertexIndex;
[...]
std::shared_ptr<SurfaceMeshT> mesh;
[...]
... |
66,163,428 | 66,164,170 | Is there a way to use decltype on a data member to declare a method argument | Consider some simple code:
struct A {
using Type = int;
};
struct B {
void test( A::Type i ) { printf("%d\n", i); }
A a;
};
In real example, however, "A" is a long, template type that's not fun to type. Even though I do need to type it (to declare it), I don't want to have to type it twice. Even if I got it ... | In these cases, make an alias. You then get to use it everywhere in your class - even when declaring a, so you don't need to reorganize the members in your class definition.
struct a_long_template_type_that_is_not_fun_to_type {
using Type = int;
};
struct B {
using type_alias = a_long_template_type_that_is_not_fun... |
66,164,458 | 66,165,641 | How to pass a method of an object instance to a std::function type callback? | The evpp library has a callback method with following signature,
void evpp::TCPServer::SetMessageCallback(evpp::MessageCallback cb)
evpp::MessageCallback is in fact,
typedef std::function<void(const TCPConnPtr&, Buffer*)> MessageCallback;
I have a non-static method called worker inside HTTPTransport class and it has ... | If you want to use std::bind(), you have to include placeholders for the arguments you are passing. Also, using & for the last argument is incorrect - what you need instead is std::ref(). Your expression becomes:
using namespace std::placeholders; // for _1, _2
server.SetMessageCallback(std::bind(&HTTPTransport::worke... |
66,164,477 | 66,164,628 | Private typedef and SFINAE in C++ | I am trying to get intuition with SFINAE and apparently it should detect private access violation.
However, the following code does not compile with my clang++ 10.0.0-4ubuntu1.
class K{
typedef void type;
};
template<typename T>
K::type f(T t) {}
void f(...) {}
int main() {
f(K()); //error: 'x' is a priv... | K::type is not dependent on any template parameters, and therefore SFINAE does not apply.
If you instead use a dependent name, SFINAE will kick in, and the second overload of f would be selected. For example:
class K{
typedef void type;
};
template<typename T>
typename T::type f(T t) {}
void f(...) {}
int m... |
66,164,903 | 66,164,979 | Partial template deduction in constructors | Problem: I'm often in a situation where some types can be deduced from the constructor's arguments, but not all:
template <typename Res, typename Arg>
struct adder {
adder (Arg a1, Arg a2) : a1 {a1}, a2 {a2} {}
void compute () { res = a1 + a2; }
Res result () { return res; }
Arg a1, a2;
Res res;
}... | An option you did not mention is to do as the standard library does1, and free the maker function:
template <typename Res, typename Arg>
auto make_adder (Arg a1, Arg a2) {
return adder<Res, Arg> (a1, a2);
}
Template argument deduction for functions allows one to specify part of the template arguments. make_adder... |
66,164,968 | 66,165,024 | Using #ifdef preprocessor around virtual functions causes runtime error in program linked against libraries | I was trying to use #ifdef preprocessor around virtual functions. A simplified version of code looks like following:
class Base
{
#ifdef ENABLE_FLAG
virtual void function1();
#endif //ENABLE_FLAG
virtual void function2();
virtual void function3();
};
class Child : public Base
{
#ifdef ENABLE_FLAG
voi... | Virtual functions are listed in a per-class table - the virtual function table or vtable - each instance of the class contains a pointer to this table which itself contains pointers to each of the virtual functions for that class, in the order in which they are listed in the class declaration (*). (There are plenty of... |
66,165,216 | 66,165,289 | How to use initializer list to initialize std::variant? | The non-variant version of initializer list works good:
std::map<int, double> a = {{1,0.1}};
But the variant version doesn't:
std::variant<std::map<int, double>, int> b = {{1,0.1}};
Is there a way to initialize b using initializer list? If not, what is the best way to initialize it?
| One way is to be more specific:
std::variant<std::map<int, double>, int> b = std::map<int, double>{{1,0.1}};
Not ideal, but the compiler cannot choose the right overload of std::variant constructor from a <brace-enclosed initializer list>. Because of how the relevant std::variant constructor is defined:
template< clas... |
66,165,335 | 66,165,379 | C++ when to return pointers | Suppose you have a function that is supposed to return an object, do you generally return a pointer of the object or the object itself? When should you return a pointer/object?
| Generally speaking you will probably want to return object references, since that way you are only transferring a copy of the pointer and not a copy of the entire object - especially if the object is large.
My understanding is that you'll only want to return a copy when you're creating an object on the stack within a f... |
66,165,380 | 66,165,515 | how can i fix this operator overloading with the same class but different in template argument? | I am very confused about how to get the template argument of the returned object in simple operator overloading.
This is my code:
#include <iostream>
template <typename T>
class numeric {
public:
numeric(): value_{0} {}
numeric(T value): value_{value} {}
numeric(const numeric& other) { val... | Even if your attempt didn't have a problem with accessing a private member of another class - which could be worked around by making the member public - you would have a problem with inconsistent behaviour where x + y results in 15 because the type of the result is numeric<int>. y + x would yield the desired 15.5.
You ... |
66,165,489 | 66,165,514 | C++ How works set of function's argument value? | I am learning C++ and I have code:
float x, y;
namespace X {
void SetMyX(float p) {
x = p;
}
void SetMyY(float p) {
y = p;
}
namespace XY {
void Set(float p = 0.0f) {
x = p;
p = y;
}
}
}
int main() {
X::SetMyX(5.4f);
std::cout << ... | Yes, the argument p is a completely normal variable and you can do everything with it.
This will also work in many other languages like C, Java, Javascript or Python.
|
66,166,025 | 66,166,190 | address of non static member function template | I'm trying to understand if it's possible to take the address of a non-static member function template. Below does not work and using &sz<int> results in other errors. What is the right way to get the address of non static member function template?
311 struct XYZ
312 {
313 template <typename Z>
314 void sz()
315 ... | It does not matter that void sz() is a template because sz<int> is a member function. There is no notion of "address" in C++ - this is an implementation detail. What you can have is a pointer to member function, and the syntax for it is:
auto z = &XYZ::sz<int>;
To call it inside func(), you need the following syntax:
... |
66,166,174 | 66,166,357 | How a friend function of a base class is calling the overridden virtual function of derived class even though they are private ?(C++) | My code-
class base{
private:
virtual void print(){
cout<<" from base"<<endl;
}
friend void show(base &obj);
};
class drived1 : public base{
private:
void print(){
cout<<" from drived1"<<endl;
}
};
class drived2 : public base{
private:
void print(){
cout<<" from drived2"... | This is how C++ works. Access specifiers (public, private, and protected) depend on the static type of your variable, not the dynamic type. In your example, when
void show(base &obj){
obj.print();
}
is compiled, the compiler does not know that the function will be invoked with a drived1 argument. It knows that obj... |
66,166,467 | 66,166,611 | NULL implicit pointer conversion causing ambiguous overload | Problematic C++03 code:
#include <cstddef>
struct Foo {
explicit Foo(const char *){}
Foo &operator=(const char *) {return *this;}
Foo &operator=(char) {return *this;}
};
int main() {
Foo s("foobar");
s = NULL;
}
Error:
In file included from /opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/cstdd... | A way to achieve it is to use a proxy struct for char, which will make operator=(const char*) preferrable. Like this:
#include <cstddef>
struct MyChar
{
MyChar(char c) : c(c){}
operator char() {return c;}
char c;
};
struct Foo {
explicit Foo(const char *){}
Foo &operator=(const char *) {return *th... |
66,166,621 | 66,166,735 | Why is my if statement not evaluating false when it should be? | In this part of my program, I want to take out the leading 0s in the string highScore. Here is what I have (not the entire program; this is just the part I'm having issues with):
//take out leading 0s
for (int i = 0; highScore.at(i) != '\0'; i++)
{
if (highScore.at(i) == '0')
highScore = highScore.erase(0, ... | You're both shortening the string and advancing the subscript. That takes you out of bounds pretty quickly. Your if should always test .at(0), and your loop, as others noted above, should test the size(). You can't look for the end with '\0'.
|
66,167,200 | 66,167,338 | How to print certain elements from vector? | I am trying to print out whatever is necessary from my program. What it does is it takes a long list from a text file and sort it based on first choice and GPA and put it into a vector. I manage to sort by First choice and GPA however how can I remove whatever output that isn't necessary?
This is an example of my Txt F... | your last for loop:
for (int i = 0; i < v.size(); i++)
{
sort(v.begin(), v.end(), greater());
cout << v[i].substr(9) << endl;
}
EDIT:
If you want to only display ones with CC as 1st choice you can add if statement to your loop:
for (int i = 0; i < v.size(); i++)
{
if (v[i].substr(0,2) != "CC") cont... |
66,167,247 | 66,167,509 | Editing an initialized struct member using fstream C++ | I am stuck in the code where I have initialized the struct member but I don't know how can I edit or delete it in a txt file. (Is this possible?) Since I am making a "pc part shop" about processors and motherboards.Any tips are appreciated. Also sorry if my code is not clean, I am beginner.
#include<iostream>
... | Not what you are asking about but really you are going to find this much easier if you make the following transformation to your code.
Instead of having two structs of arrays
struct Computer
{
string processor[size];
string motherboard[size];
};
struct Prices
{
double proc_prices[size];
double mboard_p... |
66,168,156 | 66,168,245 | Eigen Matrix[value], what does it mean? | In C++ using Eigen library writing the following example:
#include <iostream>
#include <eigen3/Eigen/Core>
using namespace Eigen;
using namespace std;
int main()
{
Matrix3f mat;
Matrix3f m[11];
cout << mat << endl;
cout << "\n" << m[11] << endl;
}
The first cout outputs:
-37392.8 4.57244e-41 ... | This is not operator[]. This is a C-style array.
int a[42];
defines an array of 42 ints named a.
In the same line, for a type T and positive integer N, this:
T bla[N];
defines an array of N objects of type T.
So your code
Matrix3f m[11];
defines an array of 11 Matrix3f objects.
The array indexing starts from 0, so t... |
66,168,238 | 66,168,490 | Comparing the outputs between a function and a function template on Compiler Explorer | I implemented simple versions of the factorial function which both can be seen here. I'm using GCC Trunk. There are 2 source files, the first being the function version and the second being the templated version. Each source file has 2 attached compilers with an associated output. The only difference between the two at... | main is defined to return an int. After main returns the c++ runtime will call std::exit (or equivalent code) with the value returned from main.
std::exit also takes an int exit code. How this exit code is turned into a process return code is implementation defined.
On Unix the return code for a process is usually a si... |
66,169,386 | 66,169,713 | How to read Json string starting with square brackets in it? | I am using c++ code to read json string to retrieve value based on specific key names. Example of my json response from web API is in array format like below.
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "a... | Yeah. Boost Property Tree is a property tree library, not JSON.
You're in luck though, Boost has a JSON library now https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
Note: your input isn't valid JSON either, because JSON doesn't strictly allow trailing commas. You can enable them with an option in Bo... |
66,170,047 | 66,171,400 | std::function in std::unordered_map, error C3867 non-standard syntax; use '&' to create a pointer to member | I try to replace if/else by using a map to call some api
why the initializer list throws the error?
...
#include <functional>
#include <unordered_map>
class MyClass final : public Base
{
std::string InfoInquiry(Class_1& request, Class_2& response);
std::string ActivateDeactivate(Class_1& request, Class_2& respon... | I would argue for using pointers-to-members for this. std::function comes with a cost (at least one extra indirection, i.e. slow).
Something like this (edited for brevity):
#include <functional>
#include <map>
#include <iostream>
class MyClass
{
public:
std::string InfoInquiry() { return "info!"; }
std::string... |
66,170,556 | 66,171,032 | Is it possible to print specific lines out of this code? | I am trying to print out whatever is necessary from my program. What it does is it takes a long list from a text file and sort it based on first choice and GPA and put it into a vector.
I manage to sort by First choice and GPA however how can I remove whatever output that isn't necessary?
I know I asked this before but... |
Previous point:
As was noted in the comment section using namespace std; is a bad choice and your code has an example of one of the reasons why that is, the redefinition of greater which is already present in the namespace.
The provided link has further explanation and alternatives.
As for you code, if the goal is to... |
66,170,617 | 66,170,970 | Use ranged algorithm on custom container | I want to upgrade my custom container to compatible with std::ranges algorithms such as find_if and others, like bellow
auto is_satisfy = [](CustomContainer::value_type x) { ... };
std::ranges::find_if(custom_container, is_satisfy);
// instead of std::find_if(custom_container.begin(), custom_container.end(), is_satisfy... |
What is the input_range concept
It is this:
template<class T>
concept input_range =
range<T> && input_iterator<iterator_t<T>>;
In English, input_range is a range whose iterator is an input_iterator. The range concept on the other hand is:
The range concept defines the requirements of a type that allows it... |
66,170,769 | 66,171,281 | Mapping Intellij keyboard settings to Visual Studio | Can you map/transfer the navigation/edition settings of your keyboard from Jestbrains Intellij (Java) to Visual Studio (c++) under Windows?
| There is a Visual Studio plugin for that.
https://marketplace.visualstudio.com/items?itemName=JustinClareburtMSFT.HotKeys
There is a one for VS Code as well.
https://marketplace.visualstudio.com/items?itemName=k--kato.intellij-idea-keybindings
|
66,171,289 | 66,171,531 | C++ I don't know how to find a word(eg.banana,sandwich) inside of a string(sentence) THE USER ENTERS the sentence and then write that word out | I've tried this but I'm stuck honestly.
I'm trying to find the first character, and then search for the ending of that substring (for eg. if the word is "sandwich" and it finds 's' that it figures out that its "sandwich") and then write out the word sandwich. And also I'm new to C++.
#include<iostream>
#include<string... | You can find the end of a word with std::find_if:
#include <algorithm>
#include <string>
template <typename Is>
std::string find_word(Is& stream, char needle) {
auto const nonword = [](char c) {
if ('a' <= c && c <= 'z') return false;
if ('A' <= c && c <= 'Z') return false;
if (c == '-') return false;
... |
66,171,497 | 66,171,946 | Segmentation fault: unable to fix the problem | I'm new to C++, and I'm trying to write a project that interacts through command line. Right now, whenever I run my main (which is the executable), I always receive a segmentation fault error when the main program finished.
Edit comment:
I'm told by tutor to use as little as C++ features such as vectors or strings ...... | Just to give you an idea, this would be an example of C++ code
#include<iostream>
#include<fstream>
#include<string_view>
#include<string>
#include<sstream>
#include<exception>
int main(int argc, char** argv) {
std::cout << "starting mvote...\n";
//parse command line argumentand get the filename
std::stri... |
66,171,584 | 66,171,660 | Renaming variable yields different results | I wrote a simple function which finds the oldest person in an array of structs. The structure stores information about age and name.
#include <iostream>
struct Person
{
int age;
char name[16];
};
char* oldest(Person* arr, int len)
{
int max = 0;
char* ptr = nullptr;
Person elem;
for (int i = 0... | ptr = elem.name; assigns to ptr the address of the first element of elem.name (because the arary elem.name is automatically converted to a pointer to its first element). elem.name is of course an array inside elem, and elem is an object with automatic storage duration, meaning it is created automatically in the block i... |
66,172,000 | 66,172,174 | Difference between deque circular array and list implementation | From the research that I have done, it seems that deque is implemented either as a linked list or as a circular array. What is the difference in terms of performance between the two and why would one choose one implementation over the other?
| std::deque cannot be implemented as a simple array nor as a linked list. It is implemented as vector of pointers to fixed size arrays.
In general, double ended queue - if not burdened by the requirements of std::deque - can indeed be implemented using an array or a linked list.
What is the difference in terms of perfo... |
66,172,214 | 66,175,566 | class from a different file, variable declaration doesn't work "incomplete type is not allowed" | I have a file like this:
#include <list>
#include "term.h"
class Term {
};
class Number : public Term {
private:
double m_number;
Term* m_exponent = nullptr;
public:
Number(double number) {
m_number = number;
}
Number(double number, Term* exponent) {
m_number = number;
... | Okay, a quick tutorial.
C++ separates the concept of the definition of a class and the implementation. This makes it different from languages like Java. Now, you can, if you want, inline portions of your class in the definition, but you don't have to.
Your .h file should have things like:
class Foo {
... the full defin... |
66,172,538 | 66,172,539 | QQuickWidget Custom Resizing Mode | Note: This a self answered question. It cause me some headache to solve it in past, so I think it is worth to share.
I have a qml application designed for HD resolution(1366x768). It's using QtQuick.Layouts, so adaptable to custom resolution. But resizing it to less than HD resolution makes it squishy and meaningless. ... | It's kinda ugly but working solution. I checked the source code of QQuickWidget, and realized inner updateSize function does nothing when ResizeMode is invalid.
CustomQuickWidget(QWidget* parent = nullptr)
: QQuickWidget(parent)
{
//set invalid resize mode for custom resizing
setResizeMode(static_cast<QQui... |
66,172,578 | 66,172,701 | Is this a thread safe vector, and if so why do some methods of std::vector require locking for thread safety while others do not? | As a complete newby to threading I've done some poking around in search for an implementation of a thread safe std::vector. Based (heavily) on my reading I've come up with this:
# include <vector>
template<class ContainedType>
class ThreadSafeVector {
public:
ThreadSafeVector()
... | No, this is not thread safe.
Thread 1 can go into:
ContainedType &operator[](int index)
{
return vec_[index];
}
and have just computed the reference ContainedType & and has just written it to the return value. Then Thread 2 goes into:
void push_back(ContainedType in) {
And the vector gets invalidated... |
66,173,083 | 66,173,299 | undefined reference to `boost::system::generic_category() | I'm developing a cpp project in Clion. For the build I use cmake. Last weekend I upgraded from ubuntu 18.04 to 20.04, from then I cannot build my project and I get the error:
/usr/local/include/boost/system/error_code.hpp:221: undefined reference to `boost::system::generic_category()'. It seems that something in the li... | That's a lot of stuff, all randomly ordered and commented out. The obvious error is a failure to link Boost System
I'd go with
FIND_PACKAGE(Boost 1.65.0
COMPONENTS system program_options REQUIRED)
LINK_DIRECTORIES(${Boost_LIBRARY_DIRS})
INCLUDE_DIRECTORIES(${Boost_INLUDE_DIRS})
LINK_LIBRARIES(${Boost_LIBRARIES})
... |
66,173,137 | 66,173,228 | What are the implications of calling vector::size / map::size in a non-thread-safe manner? | As far as I can tell, map::size and vector::size, while const are not guaranteed thread-safe. One implementation of vector I found looks like this:
size_type size() const _NOEXCEPT
{return static_cast<size_type>(this->__end_ - this->__begin_);}
If I call this method in a non-thread-safe way, what could go wron... | What could go wrong?
Adding elements to the vector may cause reallocation and invalidate all iterators. If between your query to begin and end a reallocation happens, their difference will be gibberish.
|
66,173,203 | 66,173,535 | switch over template parameters | When the value of a template parameter of a function is known only at run time, one has to write a code that consider all possible parameters, and accordingly call the function.
This (over-)simplified example illustrate the problem
#include <iostream>
template <int i>
void f()
{
std::cout << i << std::endl;
}
int ... | Here is a way to do that for 1 template argument:
#include <cstdio>
#include <stdexcept>
#include <utility>
template <int i>
void f(char const* s, bool b, double d) {
std::printf("%d -> %s %d %f\n", i, s, b, d);
}
template <class T, class ...Args>
[[noreturn]] void call_f(T&&, Args&&...) {
throw std::invalid_argu... |
66,173,223 | 66,173,373 | millis(); Arduino "out of scope" | I have build a custom clock / weatherstation. But for a couple of purposes I wanna be able to run timers inside my code. I have done this many times before in C++ with the SDL lib (SDL_GetTicks()). And I know I can get ticks the same way in the Arduino IDE by using millis().
So I just copy pasted my code for a previous... | you have to include arduino.h in your header file, this should solve the problem.
#include <Arduino.h>
|
66,173,235 | 66,173,799 | Split vector into new smaller size vectors | Problem
I have vector V = {1,2,3,4,5,6,7,8,9,10,11} and suppose I want to create N new vectors from this large vector.
Example : N = 3 means it will split the vector by the largest available size i.e. 4-4-3
v1 = {1,2,3,4}
v2 = {5,6,7,8}
v3 = {9,10,11}
Code
std::vector<int> v;
for (int i = 1; i < 12; i++) v.push_back(i)... | A simple way is to build a vector of vector to collect the different arrays.
To control the boundaries, one possibility is first to calculate the maximum size of these arrays,
and then to manage two indices, one ibegin corresponding to the beginning of a subarray, and one iend corresponding to the end of the same subar... |
66,173,542 | 66,173,672 | recursively get complete key path to all values in a boost property tree | I'm reading an XML file into a boost::property_tree and trying to get the complete key path for every value.
Does boost have a built in way to do this
Were is the error in my recursion?
example input - my_file.xml
<foo>
<bar>abc</bar>
<baz>
<buz>def</buz>
</baz>
</foo>
desired result
"foo.bar"
"f... | Every iteration of your for loop adds to the parentKey value so it will have all the children's names in it by the end of the loop. Use a separate variable to hold the key name for each node:
void walk_ptree(const boost::property_tree::ptree& tree, std::unordered_set<std::string>& key_set, const std::string& parent_key... |
66,174,105 | 66,174,363 | addition and subtraction of two numbers using operator overloading | #include<iostream>
using namespace std;
class add
{
private: int a,b;
public: add(int x=0)
{
a=x;
}
add operator+(add const &c) // sub operator-(sub const &c)
{ //{
add sum; // sub diff;
... | You can define any reasonable combination of:
Foo operator+(arg);
Foo operator-(arg);
Foo operator*(arg);
Foo operator/(arg);
And the arg can be another Foo or some other type entirely. For instance:
#include <iostream>
using namespace std;
class Operators {
public:
Operators() = default;
Operators(int v) : ... |
66,175,002 | 66,175,567 | How to deal with template const and non-const parameters? | I have a Template function taking in const types such as:
template <class T, class U>
void process(const T& v1, const U& v2)
{
//do some things
verify(v1);
verify(v2);
}
Then the verify function checks the Type for T using if constexpr as follows:
(The function also returns the variable. ... | This is one of those things you'd need to know.
The form you're looking for is
template <class T> auto verify(T&& t) {
The reason is that T can be const U, a const-qualified type. The double && is necessary for rvalue references.
You probably want std::is_same_v<std::remove_cv_t<T>>, ...
And to simply things:
template... |
66,175,034 | 66,175,507 | Why linux ld somtime use the symbolic link of libs | I use the jsoncpp lib in my linux cli tool.
The CMakeLists.txt contains
find_library(LIB_JSON jsoncpp)
target_link_libraries(${PROJECT_NAME} ${LIB_JSON})
The result is
/usr/bin/c++ -rdynamic CMakeFiles/cktwagent.dir/agent_main.cpp.o -o cktwagent -ljsoncpp
When i check the binary I found:
$> ldd cktwagent
linux-... | That's a version compatibility feature. By convention, API compatibility is determined by the major version number. So 6.0.28 would be is compatible with 6.1.1, but not with 5.0.1 or 7.0.1.
To allow for compatible upgrades, libstdc++.so.6.0.28 is symlinked as libstdc++.so.6. Then it can be binary-upgraded to e.g. libst... |
66,175,166 | 66,176,377 | fake crc32 (add 4 bytes in the end of the file) | I'm trying to fake the needed CRC32, I have found the app called PEid, so it has a plugin called crc32 that can do this
as you can see the CRC of the file is 0x97B9850E, I need 0x73CBFFB5
when I click to fix it, the app will append 0xA6D43474 to the file, and crc32 will become 0x73CBFFB5
I found the source code for th... | In the first case it is appending four bytes to the file to get the desired CRC. The result is a file of length 3440. In the second case it is telling you that you can exclusive-or the first four bytes of the file (you gave it offset 0) with the provided constant to get the desired CRC, keeping the file length of 3436.... |
66,175,605 | 66,176,123 | Why does std::tuple call operator <=> twice? | The following code calls operator <=> twice, with arguments reversed. But why?
GCC 10.2 and clang 12 both seem to be using libstdc++-10, whose <tuple> does provide operator <=>, so it doesn’t appear to be a case of missing standard library support and my code has to be incorrect. How to fix it?
#include <tuple>
#includ... | Short answer: You need to define operator== for X.
std::tuple compares elements via a synthesized three-way comparison that uses <=> only if the type satisfies std::three_way_comparable_with<T,U>. Ultimately, this requires std::three_way_comparable<X>, which requires an expositionary weakly-equality-comparable-with con... |
66,175,990 | 66,177,243 | (MATLAB/C++) Is it possible to pass functions as arguments to C++ MEX functions? | I have only been working with mex functions for a couple of weeks, and am now working on writing a Runge-Kutta, 4th order solver as a C++ mex function.
I am wondering whether it is possible to take a function as an input.
Effectively, it would be nice to have my dynamics function written in MATLAB and pass it straight ... | Just quickly skimming the MATLAB C++ API doc, it looks like you can do this using the matlab::engine::MATLABEngine::feval interface found here:
https://www.mathworks.com/help/matlab/matlab_external/cpp-mex-api.html?searchHighlight=fevalAsync&s_tid=srchtitle#mw_723048ca-e22f-4bfb-aa12-47b8007da774
I.e., pass your functi... |
66,176,215 | 66,177,127 | Cannot compile file using catch2 CATCH_CONFIG_MAIN | I've started out learning how to use Catch2 for testing my C++ code and am trying to set up a simple test.
My folder structure consists of three files all in the same folder:
catch.cpp //this is the catch_amalgamated.cpp file from GitHub
catch.hpp //this is the catch_amalgamated.hpp file from GitHub
test.cpp //this is... | The error was occurring because the default branch that google takes you to is the development branch of catch2, so I was using version 3 files and following version 2 documentation (as it has not been updated yet). Once I downloaded the v.2 file everything started working fine.
|
66,176,258 | 66,176,331 | Multiple functions for a class does not store previous results | Problem
I want to create a function inside a class which function2 will use the result generated from function1. I have a small code snippet where I tried to make it easy to understand.
#include <stdio.h>
class GreaterSmaller {
public:
int greater, smaller;
};
GreaterSmaller findGreaterSmaller(int a, int... | Define the second method as taking an argument of the first type, and pass it when you call it, as such:
void print(GreaterSmaller &s)
{
std::cout << s.greater << s.smaller << std::endl;
}
print(result); // I want it to print 4 & 3
|
66,176,347 | 66,176,898 | Error loading DLL (think that VC++ runtime is missing) | I ve created some DLL in Visual Studio. Then i wanted to use it in C# application.
On my first machine it worked well, but crashes on laptop with such error "Can't load DLL 'MyDLL.dll'".
I ve used DependencyWalker tool and found a lot of garbage that is missed, some of these:
API-MS-WIN-CORE-APIQUERY-L1-1-0.DLL
API-MS-... | From the comments. Dependency walker has some false positives. There is a new / updated tool that fixes this issue:
https://github.com/lucasg/Dependencies
|
66,176,464 | 66,176,712 | Race conditions due to speculative reordering / Linux RCU facility | The following excerpt is taken from the website https://lwn.net/Articles/262464/ and it is dealing with read-inconsistencies of shared data structures (for which there was the RCU created):
p = gp;
if (p != NULL) {
do_something_with(p->a, p->b, p->c);
}
Although this code fragment might well seem immune to misorder... | C++
That article was written in 2007, so it predates C++11.
C++11 was the first to define anything about threads in the standard, and with it defines1 what does or doesn't constitute a data race.
Under the current rules, I believe your conclusion is basically correct--with the quoted code, evaluating p->a, p->b and/or ... |
66,176,623 | 66,176,682 | Why mi code compiles ok in SSE2 but not in ARM(no NEON)? | Well, this is the problem: i was trying to compile my altoin in ARM and i get stack smashing error: . Aborted. then, i try to compile exactly the same code but with SSE2 flags in my other linux computer, and it success. if i disable stack protection on the makefile im able to compile. But isnt good idea disable that. I... | double x[NptGQ], w[NptGQ]; variable length arrays are not standard in C++. Use std:: vector in C++
std::vector<double> x(NptGQ), w(NptGQ);
gauleg(a2, b2, x.data(), w.data(), NptGQ);
|
66,176,642 | 66,176,688 | Difference between `constexpr` and `#define` | So I read the interesting answers about what are the differences between constexpr and const but I was curious about are the differences between #define and constexpr ? I feel like constexpr is just a #define where the type can be chosen.
| Statements defined using #define are called macros. And macros are used in a multitude of uses.
We can use them to conditionally compile sections of code.
#ifdef ONE
int AddOne(int x) { return x + 1; }
#else
int AddTwo(int x) { return x + 2; }
#endif
When we don't need to store constants in a variable.
#define M... |
66,176,720 | 66,178,351 | Why introduce `std::launder` rather than have the compiler take care of it? | I've just read
What is the purpose of std::launder?
and frankly, I am left scratching my head.
Let's start with the second example in @NicolBolas' accepted answer:
aligned_storage<sizeof(int), alignof(int)>::type data;
new(&data) int;
int *p = std::launder(reinterpret_cast<int*>(&data));
[basic.life]/8 tells us th... |
depending on whether or not the code does something like in these examples
Because the compiler cannot always know when data is being accessed "this way".
As things currently stand, the compiler is allowed to assume that, for the following code:
struct foo{ int const x; };
void some_func(foo*);
int bar() {
foo ... |
66,176,748 | 66,179,731 | Map of template function | I have a class like this:
class factory;
using factory_ptr = std::unique_ptr<IComponent> (factory::*)() const noexcept;
class factory {
public:
factory();
~factory() = default;
std::unique_ptr<Chipset> &create(const std::string &type);
private:
template<class T>
std::un... | The issue is that your Tcreate function does not have the required signature. You're trying to create a map of functions which return an std::unique_ptr<IComponent>, but Tcreate() returns std::unique_ptr<T>.
I'm assuming Chipset inherits from IComponent. And as you note each T inherits from Chipset. So the conversion f... |
66,176,770 | 66,177,171 | std::variant declaration is not found by compiler | What I am trying to do is very simple, I need to create a vector that can hold different types of data. So I read about std::variant and am trying to use it, however, when declaring my "std::vector< std::variant< typenames > >", the compiler complains about not finding the declaration for variant<> even though I includ... | I am not a Clang expert, but try using the option -std=c++17.
According to this the default seems to be C++98.
|
66,176,783 | 66,178,876 | specific field value in mongocxx | I want to have all the values of a specific field in my mongodb using mongocxx. I have 100 documents in my collection and each having a field "X1_position", the values of this field is float. I want to get all the 100 values of that field and want to store it into an array.
I am using following code, but it is not work... | I think that what you're after is projection.
You don't need to filter since you said you want all docs, but you need to tell MongoDB which fields you want back:
auto coll = conn["my_data"]["exp1"];
bsoncxx::builder::stream::document mydoc;
// Use projection to pick the field you want
// _id must be explicitly remove... |
66,176,810 | 66,177,088 | ranges::subrange in MSVC on Compiler Explorer | The following code compiles and runs just fine with GCC 8.3 and with Clang 10.0.1, whereas it fails miserably on MicroSoft shiny compiler.
#include <vector>
#include <range/v3/view/group_by.hpp>
int main(){
std::vector<int> edits{1,1,3,2,2,4,4,4,4,1,1,3,3,2};
auto xxx = ranges::subrange(edits.begin(), edits.en... | You've specified /std:c++17 and ranges::subrange is not present in C++ 17. Ranges-v3 also requires C++ 20 because it uses Concepts.
Compiling instead with /std:c++latest succeeds.
The errors turn out to be coming from a Concepts emulation layer bundled in Ranges v3, which evidently does not work correctly on the lates... |
66,177,067 | 66,179,981 | How should I call a function from .so using python ctypes.CDLL? | I am trying to run a C++ code in my python project.
This is the recompile.sh, it builds the shared objects well.
g++ -fPIC -shared -I /home/pathto python/python3.8/ src/example.hpp \
/usr/lib/x86_64-linux-gnu/libboost_python38.so -o src/example.so
example.hpp:
#include <boost/python.hpp>
int get_answer_c(){
retur... | EDIT:
It compiles correctly only if I use .cpp instead of .hpp
(and libboost_python38.so is after src/example.cpp)
I compiled it correctly using this makefile.
First it compiles example.o and later example.so.
Item -lboost_python38 have to be after src/example.o
I keep code in .cpp because .hpp seems for headers.
ma... |
66,177,097 | 66,178,623 | Python Shared Memory using mmap and empty files | I'm trying to make a fast library for interprocess communication between any combination of Python and C/C++ processes. (i.e. Python <-> Python, Python <-> C++, or C++ <-> Python)
In the hopes of having the fastest implementation, I'm trying to utilize shared memory using mmap. The plan is for two processes to share me... | To answer the questions directly as best I can:
The file needs to be sized appropriately before it can be mapped. If you need more space, there are different ways to do it ... but most portable is likely unmap the file, resize the file on disk, and then remap the file. See: How to portably extend a file accessed usi... |
66,177,153 | 66,177,295 | Inserting a struct variable into a c++ vector inside a loop | I have a vector of structures called "Cell", which contains a position (x, y), radius, and some other variables.
I need to add more cells to the end of my vector during the program execution as I loop over the vector and check a condition.
Is it safe to create new cells inside the loop and add them to the vector with p... | It's not safe as the past-end iterator will be invalidated when push_back causes the vector size to increase.
|
66,177,296 | 66,177,896 | Read access violation in internal class variable | The code compiles, but when I try to assign a new value to a variable in the update_Data method of the now_Playing class, it crashes with a variable access error.
At the same time, if in this method you output data from new_Data["song_Name"], then the data appears, that is, the variable contains data. The error is in ... | _NOW_PLAYING never initialized. Initialize it in constructor.
Create a new one:
IC_Server::IC_Server(QObject *parent)
: HttpRequestHandler(parent),
_NOW_PLAYING(new now_Playing(this))
{}
Or share a created one:
IC_Server::IC_Server(now_Playing* nowPlaying, QObject *parent)
: HttpRequestHandler(parent),... |
66,177,337 | 66,201,841 | cmake acting differently when compiling in different directories | my file structure looks like this:
gameFolder
|-cmake-build-debug
|-CMakeLists.txt **for clion build**
|-src
|-example.cpp
|-example.h
|-emscripten **web build**
|-build
|-CMakeLists.txt
the issue here is when I run cmake .. in the build folder under emscripten cmake is unable to find the boost library, howev... | So I stumbled around a bit and found a solution to this:
include_directories("path-to-emscripten")
for me it was installed using brew so I just entered this at the top and it did the trick
include_directory("/usr/local/Cellar")
|
66,177,346 | 66,177,871 | What is causing c++ function signature to be different? | Our build machine is set up with an earlier version of Android NDK. Most of our code is built on this machine and the final Android image is created.
My development machine uses the latest version of Android NDK.
I am creating a static library from my C++ code on my development machine and copy it over to the build mac... | There is no name mangling going on here. There seems to be two different standard libraries in use, one defines basic_string in an internal namespace called __ndk1, the other one in __1. This is basically an implementation detail. Make sure to use the same compiler and standard library implementation for these to match... |
66,177,458 | 66,226,563 | How to filter debug output window on visual studio? | How do i remove or filter this kind of message?
This is very annoying and keeps displaying the whole time I cant understand why.
Im using visual studio 2019 c++.
After reading this line of code:
MessageBox(g_hWnd, string.data(), L"", MB_OK | MB_ICONSTOP | MB_SETFOREGROUND | MB_APPLMODAL | MB_TOPMOST);
The message alwa... | I have added #include <Dwmapi.h> and now it's not spamming that message in the debug console anymore.
https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/nf-dwmapi-dwmgetwindowattribute
I think the error was because it was not loading the lib dwamip.dll.
|
66,177,826 | 66,178,841 | Why isn't std::optional<boost::variant<A, bool>> successfully constructed from `std::optional<A>`? | std::optional has copy conversion and move conversion templated constructors that make it possible to construct an instance of std::optional<B> with an instance of std::optional<A> when B is constructible from A.
Unfortunately, it seems that those constructors do not work with a boost::variant that has bool within the ... | boost::variant<B, bool> claims to be constructible from std::optional<A>, because bool is constructible from std::optional<A> (due to the explicit conversion operator).
Because of that, std::optional<boost::variant<B, bool>> will try to construct the contained object directly from std::optional<A> without unwrapping.
B... |
66,177,887 | 66,179,426 | Bison if statements - setting symbol table prior to parsing block statements | In my language I have the ability to declare a variable in the current symbol table scope and also create a if statement which will generate a new symbol table scope for its statements.
stmts : stmt { $$ = new Block(); $$->addStatement($1); }
| stmts stmt { $1->addStatement($2); }
| /*blank*/ { $$ = new Blo... | Usually you would do this with an "embedded" action:
ifstmt : TIF TLPAREN exprBase TRPAREN {
semanticAnalyzerParser->enterScope("if statement scope"); }
TOPENBLOCK stmts TCLOSEBLOCK {
semanticAnalyzerParser->leaveScope("if statement scope");
$$ = new IfStateme... |
66,177,936 | 66,178,498 | How to recursively inherit a template class from itself? (not CRTP!) | I am going to try an interesting trick!
I want to recursively build an inheritance of template classes.
I am expecting to see this:
T<int, int, int> inherits T<int,int> inherits T<int> inherits T<void>
/*Here should be specializations with void...*/
template<typename T, typename... Ts>
class ToPack : ToPack<Ts...>
{
... | As mentioned in the comments, void is itself a type, not a placeholder for empty. What you really have is ToPack<int, int, int> -> ToPack<int, int> -> ToPack<int> -> ToPack<>. ToPack<> isn't valid since it requires at least one template parameter, so this fails to compile.
You need to change your base case by specializ... |
66,178,855 | 66,179,348 | Finding keys near other keys [C++] | I'm sorry if the title is undescriptive, I'm not sure how to summarize my issue into a few words.
I'm looking to find which characters are physically near other characters on my QWERTY (UK, but I don't mind if you provide information specific to US) keyboard.
e.g:
charsNearChar('j') // OUTPUT -> U,I,H,K,N,M.
I can't s... | There is no (simple) calculation that you could perform to get the list of adjacent keys. You simply need to use an explicitly written list of adjacent keys for each key.
any solutions beside switch cases
You don't need switch cases. What you're essentially asking for is a graph where nodes are keys and edges are to ... |
66,179,559 | 66,180,410 | using boost::units to calculate geo coordinates | I'm trying to do a type-safe C++ implementation of the formula from [Calculate distance, bearing and more between Latitude/Longitude points][1]. Unfortunately I'm running into C++ type errors that bury the actual problem under endless template expansions. I think I'm really close:
#include <iostream>
#include <boost/un... | Problem is, that
const auto angular_distance = distance / earth_radius;
is dimensionless when it should be an angle. Changing this to
quantity<degree::plane_angle> angular_distance{(distance / earth_radius).value() * radians};
makes the code compile.
|
66,180,206 | 66,180,766 | C++ - How to call a templated method of a recursively inherited templated base class | I'm trying to create a Tuple class with an arbitrary number of entries with arbitrary types using variadic templates and the ability to get the nth entry with a templatized entry method, so I can use it as follows:
Tuple<int, int, std::string, double> t(1, 2, "Hello World", 3.4);
std::cout << t.entry<1>() << std::endl;... | Assuming you're using at least C++14, you can use auto& instead of a trailing return type, and as pointed out by max66 you need to add the template keyword before the member function invocation in your syntax.
You can also simplify your definition because you just need an empty base class, not a class which implements ... |
66,180,263 | 66,252,507 | How to resolve C++ Error C2039 using Sciplot modern C++ library? | I just tried to use Sciplot for C++ found here:
https://sciplot.github.io/
Using Visual Studio Community 2017.
Copied the sciplot folder of headers into my dependencies folder of project.
Added include folders into project settings.
Copied the example code provided on their git.
#include <sciplot/sciplot.hpp>
using nam... | This resolved the C2039 error:
#include <algorithm>
#include <sciplot/sciplot.hpp>
using namespace sciplot;
|
66,180,705 | 66,564,683 | How to get VS Code to propose more limited rename? | In Visual Studio Code, F2 rename on purely local C++ symbols is fine, but trying it on a symbol with wider scope, results in a very aggressive scope of suggested renaming, going as far as suggesting to rename unrelated symbols with the same name in the system header files. These typically default to unchecked, but at o... | The problem isn't with vscode, it's the linter vscode is using.
The easiest way to try to resolve the problem is using a different more advanced c++ linter. It's what I did to resolve a similar issue using golang.
Maybe the below link will help you find your new favorite linter.
https://www.reddit.com/r/cpp/comments/5b... |
66,180,747 | 66,181,349 | How to determine if strong type's base type is std::array<char, N> using only standard library | Want to extend base_is_char_array for any size character array.
Open to an entirely different solution than using is_base_of. But I am constrained to the standard library for reasons far outside my control.
Outside of something gross that iterates to a fixed maximum array size, I'm out of ideas.
#include <array>
#incl... | cppreference gives a possible implementation of std::is_base_of. You can use the same technique to implement your base_is_char_array:
namespace details {
template <std::size_t N>
std::true_type test_ptr_convertible_to_char_array(const volatile std::array<char, N>*);
std::false_type test_ptr_convertible_to_... |
66,180,951 | 66,187,102 | How to initialize "RInside" instance in a function NOT main function, and call it multiple times without getting "R is already initialized"? | I would like to use RInside in a function that is NOT the main function in my c++ program. After debugging, I found out that the function works for the first round and I get the output as expected but when it is called for the second time my program stops and I get the error message "R is already initialized". Can anyb... | It would appear (I am not an expert on RInside) that an application must have no more than one RInside object created over the course of an application's lifetime. This corresponds to C++'s concept of "static storage duration". When a variable is defined in the main function, the difference between "automatic" (the def... |
66,181,029 | 66,187,821 | C++ Safely and Efficiently Casting std::weak_ordering to int | C++20 is introducing a new comparison type: std::weak_ordering.
It allows for representing less than, equal to, or greater than.
However, some older functions use an int for a similar purpose. Such as qsort, which uses the signature
int compar (const void* p1, const void* p2);
How can I cast std::weak_ordering to int ... |
Is there a better solution that would be guaranteed to work?
No.
The standard does not specify the contents or representation of the ordering classes. Barry's answer is based on reasonable assumptions, that are likely to hold, but they are not guaranteed.
Should you need it, your best bet is to write something like y... |
66,181,709 | 66,189,721 | Allow implicit type conversion during template evaluation | I'm writing a wrapper class for C++ types, which allows me to instrument when a wrapped object is constructed, accessed, modified, and destroyed. To make this transparent for the original code, I include implicit conversion functions back to the underlying type, but this fails when a wrapped object is passed directly t... | The fault in this example lies with is_same. It declares that it requires two arguments of the same type, which is a requirement it does not need, and fails to require that type to have an ==, which it does need.
Granted, it is common to find C++ that poorly constrains template functions because it is difficult and ver... |
66,181,735 | 66,182,704 | Rust, how to use global variable from DLL? C++ equivalent requires __declspec(dllimport) | Edit: After some research, I have found a partial solution. The link_name attribute can be used to change the name that is linked for an external variable. My question is now if this attribute can automatically be applied by bindgen to resolve linking errors. Context:
I am trying to get my Rust project to work with Jul... | The ultimate solution turned out to be that Rust's #[link(name="libname", kind="dylib")] annotation functions like the __declspec(dllimport) annotation in C++. I added some code to my build script to automatically insert this annotation above every part where bindgen created bindings for a global variable:
let mut code... |
66,182,031 | 66,182,144 | how can I pass variable i in linearSearch function? | In this code I need to check index of the value-
Sample Input :
1
7
2 13 4 1 3 6 28
3
Sample Output :
4
#include
using namespace std;
int linearSearch(int *arr, int n, int x)
{
//Write your code here
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int *arr = ... | if your array is not sorted simple linear traversal of array is what you can do:
int linearSearch(int *arr, int n, int x)
{
for(int i=0; i<n; i++){
// if match found.
if(arr[i] == x){
return i;
}
}
// if not match found
return -1;
}
|
66,182,101 | 66,182,189 | using functions from outside a class | First of forgive me if this has been answered, i could not find it.
i m pretty new to C++ and programming in general just fumbling my way thorough. I created a class called "Angle". outside of this class i have a function to test input from user to make sure its an integer called "isInt". But i keep getting an error "i... | To use any function you must declare/define it before using it.
i.e if you write
bool isInt(std::string); before defining your class, your problem will be solved.
Other things
your getters (getDegrees/Minutes/Direction) should be constant.
input argument should be constant.
why don't you include isInt in your class as ... |
66,182,230 | 66,182,272 | C++ Iterating over vector of class pointers and using base function | I am trying to loop over a vector of pointers to my class, let's call it MyClass, and call a method within MyClass for each element in the vector, let's call it MyMethod. That is:
std::vector<MyClass*> ClassOne;
for(auto it: ClassOne){
ClassOne[it].MyMethod();
}
But evidently this does not work. Could someone plea... | When you use,
for(auto it: ClassOne)
{
// ...
}
it is a MyClass*, not an an int. Hence you need to change the call to MyMethod to
it->MyMethod();
The for loop needs to be:
for(auto it: ClassOne)
{
it->MyMethod();
}
|
66,182,453 | 66,182,481 | C++20 template lambda: how to specify template argument? | Let's say I have a C++20 template lambda:
auto foo = []<bool arg>() {
if constexpr(arg)
...
else
...
};
But how do I call it? I can't seem to find a description of the syntax. I tried the usual foo<true>(); and template foo<true>();, neither of which gcc seems to like.
| foo.template operator()<true>();
is the correct syntax. Try it on godbolt.org
The reason for this strange syntax is because:
foo is a generic lambda which implements a template<bool> operator() method.
foo.operator()<true>() would interpret < as a comparison operator.
If you want a slightly more readable syntax, try... |
66,183,002 | 66,183,095 | Operator Overloading in C++: unqualified-id error | We just started learning about classes and operator overloading in my computing module and I have a problem with one of the examples given:
#include <iostream>
using namespace std;
int main()
{
class PositivePoint
{
// Must return PositivePoint object by value
PositivePoint operator+(const Pos... | your code is almost ok, at least with the syntax of the operator..
you need to move the class and the operator out of the main function...
define mX, My and correct the typo declared for ret
after that i tested and works...
#include <iostream>
using namespace std;
class PositivePoint {
public:
int mY;
int mX;
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.