question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
61,963,568 | 61,966,559 | Allocation of pointers in MPI collective communications | I wonder how MPI collective communications such as Bcast, Scatter, Gather etc. behave when the send buffer is allocated in root but it is not allocated in the other ranks.
For example:
rowptr = (int*)malloc(sizeof(int) * (row_count + 1));
MPI_Scatterv(all_rows, rowCounts, rowDispls, MPI_INT,
rowpt... | From the MPI 3.1 standard (chapter 5.6 page 160)
The send buffer is ignored for all non-root processes.
[...]
All arguments to the function are significant on process root, while on other processes, only arguments recvbuf, recvcount, recvtype, root, and comm are significant.
Same story for MPI_Gather() but replace re... |
61,963,715 | 61,963,936 | linking static class member function throws undefined reference error c++ | I've gone through many similar threads on this kind of question but I'm still unable to resolve this error. Any help would be appreciated.
/*samp.h header file*/
#include<iostream>
using namespace std;
class test
{
private:
test();
public:
static void const_caller();
};
/*samp.cpp file*/
#include<iostream>
using na... | In the samp.cpp file you define test class again.
You need to include samp.h header and implement methods of test class:
#include "samp.h"
using namespace std;
test::test()
{
cout << "priv cont called\n";
}
void test::const_caller()
{
cout << "calling priv const\n";
}
|
61,963,881 | 61,964,118 | How to set magic pointer values on arbitrary pointer types | I have an application in which I've experienced some rare segmentation faults due to nullptr dereferences. The pointer values in the application follow a pretty standard life cycle:
I initialize them to nullptr.
They get set to a value at some point early on when information becomes available to set them to a construc... | You an use a function template to remove the tedium a bit.
template <typename Object>
Object* get_pointer()
{
return reinterpret_cast<Object*>(0xCAFEBABE);
}
template <typename Object>
Object* get_pointer(Object* /*unused*/)
{
return get_pointer<Object>();
}
and use it as:
A* a = get_pointer(a);
or
A* a = get_... |
61,964,239 | 61,964,291 | Why do defining type name is optional in an if statement? | Saw several examples that doesn't define type name for Y side and I used to to think C++ is type-strict. Is it safe to use a code snippet like below one in production?
I also curious to hear why it works..
#include <string>
int main() {
std::string X = "car";
if (X == "nothing") {
return 1
}
... | Thanks to operator== overload, std::string can compare to char* as well as to other std::string.
This is perfectly OK.
|
61,964,643 | 61,964,774 | Subtracting pointers with structure data | I found some legacy code and think it has UB in subtracting pointers.
If i right and UB is here - can i find it with ASAN?
I try option -fsanitize=address,pointer-subtract, but it doesn't find problem.
g++ -O0 -fsanitize=address,pointer-subtract main.c
ASAN_OPTIONS=detect_invalid_pointer_pairs=1 ./a.out
Or maybe i mis... | Casting pointers to unsigned char* for the purpose of accessing raw bytes, and casting pointers for the purpose of performing pointer arithmetic within an object, or an array of objects (in this case, data can be treated as an array of 1 Data object), are well-defined behaviors in the C and C++ standards.
However, the ... |
61,964,725 | 61,964,841 | How can I set a particular member of an inner templated class according to different specializations? | In terms of specializing an inner templated class of an outer non-templated class, I know that the following is possible (taken from another SO question):
struct X
{
template <typename T>
class Y
{};
};
template<>
class X::Y<double>{
};
However, what if I'd like to only set the member of a specialization ... | This is the correct syntax:
template <>
const int C::Inner<int>::x = 30;
template <>
const int C::Inner<double>::x = 40;
|
61,964,860 | 61,966,309 | Why do I need to include <compare> header to get <=> to compile? | I know the technical answer is: because the standard says so.
But I am confused regarding the motivation:
I see nothing "library" in the defaulting the <=>: it may return some type that is technically defined in std but it is a "fake library" type in a sense that compiler must know about it since it must be able to def... |
it may return some type that is technically defined in std but it is a "fake library" type in a sense
Well, <=> returns types that are very much real, that are actually defined in <compare> and implemented there. In the same way that an initializer list is used to construct a std::initializer_list<T>, which is very m... |
61,965,023 | 61,965,099 | How do I convert an unsigned char buffer to a double in C++? | I am trying to convert an unsigned char buffer array into a double.
Why does this not copy the bytes into the double as they are in the array?
#include <iostream>
#include <string>
int main() {
unsigned char buffer[8] = {63, 240, 0, 0, 0, 0, 0, 0};
double x = *(double*)buffer;
std::cout << x << std::endl;... | You've got your buffer round the wrong way. It should be:
{0, 0, 0, 0, 0, 0, 240, 63}
(on a little-endian machine using IEEE floating point).
Live demo
|
61,965,061 | 70,901,514 | How To Add The Value Of A Static Mesh Component From C++ Instead Of The Unreal Editor? | New to Unreal Engine here, but not new to c++. In the tutorials I saw, the way they created the UStaticMeshComponenent was by first using
mesh = CreateAbstractDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
and then opening up the unreal editor and setting the shape of the mesh manually. For example, select the ... | First you need to attach the component to your actor's root via:
mesh->SetupAttachment(RootComponent);
After that reference your static mesh. This is done via:
const ConstructorHelpers::FObjectFinder<UStaticMesh> MeshObj(TEXT("/path/to/mesh"));
Afterwards simply call UStaticMeshComponent::SetStaticMesh like this:
mesh-... |
61,965,124 | 61,965,150 | Why does the following piece of code return the value pointed at by the pointer and not the address of the pointer? | I have the following two lines of code:
const char* skimfile = argv[3];
cout << "skimfile = " << skimfile << endl;
I know that the above two lines of code work, but I am not sure why. If we want to print out the value that the pointer is pointing to, should we not use *skimfile? How is it that the above code uses only... | If you want to output the value of the pointer then write
cout << "skimfile = " << static_cast<void *>( skimfile ) << endl;
Otherwise the operator << for character pointers is overloaded such a way that it outputs a pointed string.
Without such an overloaded operator you had to write for example
const char *s = "Hello... |
61,965,647 | 61,965,696 | read character array with cin.get | I try to write a program that get max to 20 characters and index them as character array then print out the array. The program compiles but the output are random words and symbols in place of the variable. Any idea why?
# include <iostream>
using namespace std;
int main ()
{
const int MAX = 20;
char str[MAX];
int ind... | The condition un the while statement is invalid. There is a typo
while (index < MAX -1 &&
(str[index++]==cin.get()) != '\n');
^^^
Write
while (index < MAX -1 &&
(str[index++] = cin.get()) != '\n');
Take into account that the new line character '\n' can be stored in the result stri... |
61,966,069 | 61,966,130 | Initializing an object with garbage data when there is no default constructor | I'm trying to allocate some objects on the HEAP since I am trying to design a "tree" data structure, which essentially is implemented as a linked list with an added pointer to the head of a child linked list. My problem is that I initialize the "trunk" of the tree (which is the single parent-most node in the tree) upon... | If you are using C++17 or higher, instead of having an actual object stored, you could instead use std::optional. This allows for default-construction even if the underlying type isn't default-constructable, and this is way safer than copying garbage data onto an object. :-)
|
61,966,342 | 61,966,643 | Is a Preprocessed C/C++ file machine-specific? | Say I am on a linux machine, and I run the following command:
cpp main.cpp > main_p.cpp
Where main.cpp is a c++/c file. Would I be able to take main_p.cpp and compile/execute it on any other machine? Or is this program compiler-specific?
Edit 1: cpp is the C preprocessor, as defined by the cpp(1) man page.
| Preprocessor output is very much system specific, particularly if standard header files are involved.
The standard header files in particular have a lot of system specific things in there as they are considered part of the implementation and as such can have a lot of implementation specific things.
For example, the fol... |
61,966,376 | 61,966,538 | Should i respect the order of instructions when i'm using Asynchronous tasks (std::async Function Template)? | I was working on a multi-threaded program when I crossed a case in which when I ask some asynchronous implementations like the following:
#include <iostream>
#include <thread>
#include <chrono>
#include <future>
using namespace std::chrono;
int increment(int i){
i++;
std::this_thread::sleep_for(seconds(5));... | y = result.get();
x=increment(x);
In this case, the main thread will be blocked until the created thread finishes its work because get block the thread where it's working until it finishes its work
x=increment(x);
y = result.get();
Here is no blocking because y = result.get(); comes at the end and this way is the wa... |
61,966,451 | 61,966,758 | Constructor Asking for Wrong Number of Arguments | I have build a class in Unreal called Groundmode
GroundMode.h:
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "Components/BoxComponent.h"
#include <NMR\GroundDirection.h>
#include "GroundMode.generated.h"
UCLASS()
class NMR_API UGroundMode : public UObject
{
GENERATED_BODY()
... | The new expression, like you're doing here, does two things.
It allocates memory for the object by calling an appropriate allocation function for that object.
It constructs the object in that allocated memory.
When it calls the allocation function for a class T, it first determines the size of that class, std::size_t... |
61,966,763 | 61,967,009 | Floating point determinism when reading text files | I'm writing some code that needs to be deterministic across platforms. To avoid small floating point rounding errors in math, I'm using a fixed precision class based on an integer instead of a float.
However, the code is given plain text configuration files that use decimals like "0.1234" which I'm then converting to t... | IEEE floating points are deterministic.
Many C++ compilers do intermediate results in higher precision than what you ask for. This can cause differences between compilers asto what value is calculated.
Asking for a file to be compiled with strict IEEE eliminates that.
Whatever IO library you are using could guarantee ... |
61,967,026 | 61,969,763 | Opengl issue: Most likely simple texture issue | I get a black quad when running this code. The screen should be completely white. The shader itself works perfectly fine, I can change the value in the out vec4 and it works. The issue is either loading the texture into the shader or generating the texture.
GLFWwindow *window = nullptr;
GLuint shaderProgram = -1;
GLuin... | You have to set the texture minifying function (GL_TEXTURE_MIN_FILTER) by glTexParameter ( this can be done before glTexImage2D):
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
If you do not generate mipmaps (by glGenerateMipmap), then setting the GL_TEXTURE_MIN_FILTER is important. Since the defaul... |
61,967,368 | 61,967,506 | What is the logic behind while(sline >> n >> c && c== ',')? | vector<int> ParseLine (string line){
istringstream sline(line);
char c;
int n;
vector<int> row;
while(sline >> n >> c && c == ",")
row.push_back(n);
return row;
}
This is one of the functions to read 2d vector from the file. I was wondering the logic behind the while loop.
| This does several things in series, in order, this code:
sline >> n Reads an integer from sline into variable n. Importantly, this also returns sline.
We now effectively have sline >> c which reads a character from sline into variable c.
The && operator returns true only when both sides are true. sline >> c will once ... |
61,967,464 | 61,967,771 | Simple Boost::Asio asynchronous UDP echo server | I'm currently making my way through a book on C++ called "C++ Crash Course". The chapter on networking shows how to use Boost::Asio to write a simple uppercasing TCP server (synchronously or asynchronously). One of the excersises is to recreate it with UDP, which is what I'm having trouble with. Here's my implementatio... | Templates have the ugliest of compiler error messages. You often just have to go through the compiler error output and look for the first reference in your own source file. Ala:
/home/atmaks/Code/CCC_chapter20/main.cpp:53:9: required from here
In any case, on Visual Studio, the error was a bit more clear. (Not real... |
61,967,784 | 61,967,917 | std::bind and std::function term does not evalue as taking 0 arguments? | I'm working on generic class that will be used to run functions of different prototype for performance testing of algorithms.
I stuck because std::function can't execute what it was bound with, here is sample code, with comment where the error happens:
#include <utility>
#include <functional>
template<typename ReturnT... | The problem is, the std::function type, i.e. Algorithm is declared to take two parameters (with type int); when calling on them two arguments are required.
After std::bind applied, the returned functors take no parameters; arguments (std::ref(x) and std::ref(y)) have been bound. Algorithm should be declared as
using Al... |
61,967,806 | 61,968,633 | Reverse memory layout for tuple-like class templates | I'm creating a tuple-like class template using template meta programming. Unlike a std::tuple all of the values in my tuples are the same type, and the number of values is equal to the number of "channel constants" listed in the template parameter list.
Here's an example:
enum class Foo { Foo1, Foo2, Foo3, Foo4 };
My... | Why not just make the storage an array?
template <typename Rep, typename Space, Space... Channels>
struct MyTuple<Rep, Space, Channels...>
{
std::array<Rep, sizeof...(Channels)> m_values;
};
|
61,967,964 | 61,968,013 | is there any kind of error in my code as it is not giving correct output | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long int ll;
void prime_sieve(vector<int> p, int n)
{
//first mark all odd number's prime
p[2] = 1;
p[1] = p[0] = 0;
for (int i = 3; i <= n; i += 2)
{
p[i] = 1;
}
//sieve
... | You have a vector out of bounds error (and other errors)
In your function
void prime_sieve(vector<int> p, int n)
n is the size of the vector. Then you have this
for (int i = 3; i <= n; i += 2)
{
p[i] = 1;
}
If n is odd, then p[i] is an out of bounds error when i equals n.
Same issue here
for (ll j = i * i; j <= n... |
61,968,163 | 61,968,340 | Does global variable increase speed of compilation significantly in c++? | For a problem
https://codeforces.com/problemset/problem/760/B
when i submitted solution having declaration inside int main() it shows TLE, but when declaration is above int main(), it's accepted in c++.
So my question is does global declaration affects the compilation speed significantly or i am missing something?
H... | There should be no difference. If your sample size is small (you submitted both solutions once or twice), perhaps you were on the border of Time Limit Exceeded vs not, and just got lucky sometimes.
|
61,968,248 | 61,968,282 | How to set release/debug mode to compile a cpp file at a command prompt using Microsoft C++ toolset | I have a code that works fine in VS2019 release x86 mode but not in debug mode. Is there any way to use the release mode feature in the command line? For example an option for CL or link.exe. The CL command line syntax is
CL [option...] file... [option | file]... [lib...] [@command-file] [/link link-opt...]
Here is t... | Visual Studio's configuration properties for your project will tell you exactly what compiler and linker options are being used in each build configuration. See: https://learn.microsoft.com/en-us/cpp/build/working-with-project-properties?view=vs-2019
|
61,968,955 | 61,969,001 | Why use a reference when returning an ostream class? | The full code looks like this:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Point {
double x;
double y;
public:
Point();
Point(int x, int y);
void setPoint(int x, int y);
int getX(void)const;
int getY(void)const;
Point operator + (const Point & point);
Point& operator=(const Point... | If you would return an ostream then you would have slicing. In case the passed os was an ofstream then the returned ostream would only be the ostream part of the ofstream and not the full ofstream. When returning by reference you don't have slicing and don't lose information about the full type of the stream.
|
61,969,150 | 61,970,360 | Undefined symbols for architecture x86_64: linker error | I'm trying to do a test of basic linking for cpp files, I've been searching all over and am having a lot of trouble trying to find a solution. I understand that I have to include the header in both cpp's, but I'm having trouble trying to run these two together.
//testMain.cpp
#include <iostream>
#include <stdio.h>
#in... | You're supposed to specify all translation unit files when linking a C++ program.
Your program consists of two source files, testMain.cpp and functions.cpp.
Hence the compile-and-link command should be something like:
g++ testMain.cpp functions.cpp -o testMain
Alternatively you can compile each source into separately ... |
61,969,200 | 61,969,274 | What is the purpose of wrapping this private deleter function in a struct? | I've been trying to understand an answer to a different question and for the most part I think I do. However, what is the purpose of wrapping the private deleter_fn in a struct?
For convenience, here is the code I'm looking at:
class C {
public:
void foo() {
underlying_foo(handle.get());
}
void bar() {
... | In your version there is no deleter so std::unique_ptr<T, deleter> handle doesn't make sense. You would need to write std::unique_ptr<T, C> handle; (because your operator() is a member of C). The problem with this is that C is not empty and stateful. If the deleter of std::unique_ptr is an empty class then it can do so... |
61,969,316 | 61,969,524 | Is it possible to put lambda expressions into a map or list in C++? | @DanielLangr @luxun @cdhowie sorry for the XY problem. i am not sure i can explain well, but i try my best. the situation is almost like this: there is a base object "Worker" and some children. chef、tailor... children has the same action like walk、run、sleep...but different skill,chef can make food, tailor can Make clot... | It is possible but using function wrapper.
For example,
std::map<std::string, std::function<void(std::string)>> my_map;
my_map.emplace("first", [](std::string i) { std::cout << i << std::endl; });
However, if you want to pass any type of argument to your function and return any type from your lambda/function, use boos... |
61,969,331 | 61,969,699 | Non const field fine in a function but recognised as const in another one | I have a non const field ctxt.
And I have a funtion like this:
inventory_input inventory_selector::get_input()
{
inventory_input res;
const input_context ip;
res.action = ctxt.handle_input();
res.ch = ctxt.get_raw_input().get_first_input();
std::tuple<point, bool> tuple = ctxt.get_coordinates_inv... |
I have a non const field ctxt
...
the funtion get_coordinates_inventory is not const
There is your problem. Note the const qualifier on this method:
inventory_entry *inventory_selector::find_entry_by_coordinate( point coordinate ) const
... |
61,969,356 | 61,969,378 | What happen when we write empty copy constructor in derived class? | #include <iostream>
using namespace std;
class A {
int i;
public:
A(int );
};
A::A(int arg) {
i = arg;
cout << "A's Constructor called: Value of i: " << i << endl;
}
// Class B is derived from A
class B: A {
public:
B(int );
B(const B& ref)
{
cout<<"copy constructor get called"<<e... | Even if you don't use the copy constructor of B it still has to be valid.
Currently it does not invoke any constructor from A, so then it will default to contructing the base class with the default constructor.
Since there is no default constructor, you get an error.
|
61,969,688 | 61,969,768 | c++ parenthesis in front of member variable | I am translating a c++ code to another language and am having difficulties understanding some code block in c++ code.Here is the line i am having trouble understanding the concept.
here is code snippet :
DynamicUint &operator=(const DynamicUintView<Iterator> that) &
{
view(*this) = that; // <== this line ... | view is a type alias for DynamicUintView<iterator>, so this code does the following:
Constructs a temporary DynamicUintView<iterator> object by invoking the implicit DynamicUintView<iterator> conversion operator, which in turn invokes the two-arg constructor of DynamicUintView<iterator>.
view::operator= is invoked on ... |
61,969,929 | 61,970,238 | C2783: Could not deduce template argument for a helper function | I have a Node and BinaryTree class:
template<typename Elem>
struct Node {
Elem Key;
Node <Elem>* parent = nullptr;
Node <Elem>* left = nullptr;
Node <Elem>* right = nullptr;
Node(Elem k);
};
template<typename Elem>
Node<Elem>::Node(Elem k):Key{k}{}
template<typename Elem>
class BinaryTree{
publi... | There are several contexts in which an argument to a template function is non-deduced. The case where there is a template argument to the left of the :: (scope resolution operator) is one such case.
In the following cases, the types, templates, and non-type values ... do not participate in template argument deduction... |
61,969,943 | 61,970,416 | Read a file line by line in c++ (Translating code from Python to C++) | I have to translate a code from Python to C++, but I can't find a way to translate this part :
with open(files.square, "r") as f: # files.square is a txt file
lines = f.readlines()
with open(files.bs, "a") as f: # files.bs is a txt file
for i, line in enumerate(lines):
if line == "L... | Try something like this:
void txt_line(int, std::string, std::vector<std::string>){}
void txt_arch(int, std::string, std::vector<std::string>){}
int main()
{
std::ifstream firstFile("../square.txt");
std::vector<std::string> contentOfFirstFile;
std::string aLine;
while(std::getline(firstFile, aLine))... |
61,970,039 | 61,971,937 | VS Code C/C++ Intellisense stop working after update | After I migrate from TDM-GCC 9.2.0 to Winlibs (GCC 10.1.0 + LLVM/Clang/LLD/LLDB 10.0.0 + MinGW-w64 7.0.0 - release 2), Insellisense stop working. Any solution?
Here's my settings.json:
{
"files.autoSave": "afterDelay",
"C_Cpp.default.cppStandard": "c++17",
"files.trimFinalNewlines": true,
"edito... | Add
"C_Cpp.default.compilerPath": "C:\\mingw64\\bin\\g++.exe"
to settings.json
|
61,970,256 | 61,970,873 | How to let this sruct to save another coffee type by a user? | Hey this code is for a coffee machine..I want to add a operator mode for this coffee machine.At the moment i have 7 types of coffee cups.In operator mode i have to write a code to add another couple of coffee types to the existing struct(drink).And operator should have the ability to do that(Any one who check the code)... | Instead of fixed array drink in your code, use vector. Read about it here
Your drink will be modelled now as:
vector<coffee> drink {
{ "Espresso", 120, "Italy", 20 },
{ "Iced coffee", 150, "France", 20 },
{ "Long black", 80, "Austral", 20 },
{ "Americano", 100, "America", 20 },
{ "Latte", 200, "Ital... |
61,970,271 | 61,970,586 | Why is the lifetime of objects with explicit destructors extended? | I have been learning C++ and programmed this out of curiosity:
#include <iostream>
class A {};
class B {
public:
~B() {}
};
A get_a() {
A a;
std::cout << &a << '\n';
return a;
}
B get_b() {
B b;
std::cout << &b << '\n';
return b;
}
int main() {
A a = get_a();
std::cout... | This is most likely an optimization feature of your compiler. For example, when I compiled your code using CL (MSVC compiler) without any optimization option, I got the following results:
But turning on fast code option, resulted in a more optimized memory usage:
Commands for disabled and fast code options of CL, res... |
61,970,301 | 61,970,458 | C ++ associated container custom type is initialized in the class | Two initialization codes for association container objects of custom type comparison
first , not in class:
class A
{
public:
int a;
};
bool compare(const A &a1 , const A &a2)
{ return a1.a > a2.a; }
multiset<A , decltype(compare)> ml(compare);
this code is safety
but () initialization statement cannot be used in t... | This is not particular to your compare. While C++11 allows to initialize class members within the definition, you do that either with {} (brace initializer) or with assignment (equals initializer).
struct A {
int a = 42; // works
int a{42}; // works
int a(42); // unsupported syntax
};
In your example, this... |
61,970,311 | 61,970,370 | Does `name_compare()` calls the default construction or the `operator()` of `class name_compare` in `sort(vs.begin(), vs.end(), name_compare());`? | Does name_compare() calls the default construction or the operator() of class name_compare in sort(vs.begin(), vs.end(), name_compare());?
I think it's the first one.Am i right?
I would be thankful for any hint on this question.
struct Record {
string name;
// ...
};
struct name_compare { // ... | In this call
sort(vs.begin(), vs.end(), name_compare());
there is created a temporary object of the type name_compare as a function argument using the default constructor. Within the function std::sort there is called the operator function of the object.
Here is a demonstrative program
#include <iostream>
#include <st... |
61,970,545 | 61,971,986 | Finding Perpendicular Points Given An Angle With Piece-wise Hermite Splines | I am given a Hermite spline from which I want to create another spline with every point on that spline being exactly x distance away.
Here's an example of what I want to do:
.
I can find every derivative and point on the original spline. I also know all the coefficients of each polynomial.
Here's the code that I've ca... | If you build normals of given length in every point of Hermite spline and connect endpoint of these normals, resulting curve (so-called parallel curve) is not Hermit spline in general case. The same is true for Bezier curve and the most of pther curve (only circle arc generates self-similar curve and some exotic curves... |
61,970,675 | 61,972,323 | C++: Alignment when casting byte buffer to another type | I have a block of memory allocated through char buffer, is it legal to view it via buffer of another type?
char* buffer = new char[1000];
int64_t* int64_view = static_cast<int64_t*>(static_cast<void*>(buffer))
Is int64_view[0] guaranteed to correspond to first 8 bytes of buffer?
I am a bit concerned about aliasing, if... | Your example is violation of the strict aliasing rule.
So, int64_view anyway will point to the first byte, but it can be unaligned access. Some platforms allow it, some not. Anyway, in C++ it's UB.
For example:
#include <cstdint>
#include <cstddef>
#include <iostream>
#include <iomanip>
#define COUNT 8
struct alignas... |
61,970,966 | 61,971,450 | When this temporary object is destoryed?Before entry the function or after the function returned? | When this temporary object(CTest()) is destoryed?Before entry the function(fooFunc) or after the function(fooFunc) returned?
I know the code below is not right indeed(Thank you,asmmo. ).
The reason is that:
"The idea is that a function taking a non-const reference parameter is
stating that it wants to modify the par... | Temporaries are destroyed at the end of full-expression. In your case this means that CTest() will be destroyed after fooFunc returns.
Note, that your example is ill-formed. fooFunc's parameter should be an rvalue reference or a const lvalue reference. Supposedly you use Visual Studio. Pass the /W4 flag, so VS will emi... |
61,970,969 | 61,971,170 | glCullFace is not correctly working, do you have answers for that? | I am rendering a terrain and because the underside will never be seen I though face culling would bring a nice performance boost. I looked up a tutorial and came to these settings:
glCullFace(GL_FRONT);
glFrontFace(GL_CCW);
The problem is, that this is only working partially. The terrain is made out of quadrilaterals ... | I cannot see any issue in your code.
The winding order of the 1st triangle is the same
0 : i
1 : i + 1
2 : i + CHUNK_SIDE_LENGHT + 1
2
+
| \
| \
| \
+-------+
0 1
as the winding order of the 2nd triangle:
3 : i + CHUNK_SIDE_LENGHT + 2
4 : i + CHUNK_SIDE_LENGHT + 1
5 : i + 1
4 3
+... |
61,971,280 | 61,972,051 | DirectX11 each triangle using first vertex in the buffer | I'm currently having a problem with my DirectX 11 voxel renderer where whenever a triangle is rendered, the first vertex in the buffer is being used rather than one of the correct vertices.
I have a working version of the same mesh generation algorithm in Unity, and after comparing the Indices and Vertices, they are ex... | Your index buffer is declared as an R16_UINT, but the buffer you're providing is using 32 bit indices. Either change indicesArray to unsigned short*, or change your buffer to be R32_UINT.
|
61,971,339 | 61,971,376 | I have a problem with std::unique (algorithm) C++ | I have a problem with finding 2 minimal numbers. I am getting a wrong output.
Example:
Input: {-1, 2, 5, 3, 8, -1, 3, 5, 0}
Output: {-1, -1}
Right answer: {-1, 2}
I believe that there is a problem with unique because it doesn't delete all same numbers.
Is there a better way of doing this?
Following is my code:
#inclu... | Your array needs to be sorted for unique to work correctly.
|
61,971,368 | 61,971,460 | Is there a way to detect a classes constness inside of itself? | Consider the following example and output:
#include <type_traits>
#include <iostream>
struct X {
bool is_const = std::is_const_v<std::remove_pointer_t<decltype(this)>>;
constexpr bool isConst1() const {
return is_const;
}
constexpr bool isConst2() const {
return std::is_const_v<std::remove_pointer_t<decltyp... | You might do
constexpr bool isConst() const {
return std::is_const_v<std::remove_pointer_t<decltype(this)>>;
}
Demo
your issue is that decltype(this) is /*const*/ X& (not /*const*/ X)
Another issue is that you need 2 versions (the one for non-const object):
constexpr bool isConst() {
return std::is_const_v<st... |
61,971,592 | 61,977,576 | Visual Studio 2019 - Set a default extension for a file type | Visual Studio uses .cpp for cpp source files and .h for cpp header files by default. I want to change the extensions to .cc and .hh, respectively. Is there a way to configure Visual Studio?
PS: I know this is not very important but, I just like it that way.
| Your question's solution is, quite frankly, of dubious practical value. While you might satisfy you're "I just like it that way" preference, you're trying to change convention--expected, standardized extensions for one of the world's most popular programming languages and sealing yourself off from many third-party tool... |
61,971,690 | 61,972,489 | Unable to use iterator to find a class object. (binary '==': 'userInfo' does not define this operatortor) | I am fairly new to C++ especially when it comes to using iterators with class vectors.
I am trying to create a function that would verify the user username/password on login through searching a vector that contains all the class objects (users) and matching it with the input. However, I am getting this error:
binary '=... | You need to add an equality comparison operator to the userInfo class:
class userInfo
{
public:
bool operator==(const userInfo& rhs) const
{
if (this == &rhs)
return true;
// rest of implementation
}
bool operator!=(const userInfo& rhs) const
{
return !(*this == rhs);
}
}... |
61,971,982 | 62,037,009 | Problem in taking multiple inputs in 2d vector | The following is the code for taking input from the keyboard in the form of a 3x3 2d integer vector, for n number of times(n also input from the keyboard). I wish the code to store a new vector after each iteration, which goes on n times, but it only stores the first input. to verify this, i printed the element at the ... | You read in one long vector of 3 columns and 3 × n rows, so the entry at (2, 1) will always refer to the first matrix. If you want to represent each matrix as separate, you should make your vector nest three levels deep: matrix, row and cell:
int main()
{
vector<vector<vector<int>>> test_case{};
int n;
cin... |
61,972,039 | 61,972,081 | Can someone explain { } container in c++ | Can someone explain the {} in c++.
it is used with all containers.
example.
I generally use it to make a container like set or vector empty.
I have confusion in using the min/ max function for multiple values with it.
vector<int> v = {1,2,3,4,5};
int a = min(v) // doesn't work.
int b = min({1,2,3,4,5}) // works and giv... | Both std::min and std::max have an overload taking std::initializer_list, which could be constructed from braced-init-list like {1,2,3,4,5}.
min(v) doesn't work because there's no overload taking std::vector.
Since C++11 STL containers like std::vector and std::list could be list-initialized from braced-init-list too; ... |
61,972,181 | 61,972,569 | return bool as a value in bool operator[] in cpp | So basically i have an std::vector container that contains bool values (true, false), and i need an operator[] for it, but when i return the value(bool) with the right index, it gives me an error like this:
cannot bind non-const lvalue reference of type 'bool&' to an rvalue of type 'bool'|
my operator looks like this:
... | A little performances improve to @Jarod42 answer:
std::vector<bool>::reference operator[](unsigned int idx) {
for (auto &inner : data) {
if (idx < inner.size()) {
return inner[idx];
}
idx -= inner.size();
}
throw std::runtime_error("out of range");
}
And assume all of th... |
61,972,252 | 61,972,653 | Why/Are unordered_map and unordered_set slower? | I was solving a simple problem of finding unique elements in an array. I used a std::unordered_map to count unique elements but it gave Time Limit Exceeded in one test case. Then I used a std::unordered_set with the same result.
PS: I used std::unordered_map and std::unordered_set because I read that these two are much... | std::unordered_set<int> is a node-based container, where each element is stored in separately allocated list node. The list node contains an int element and two list node pointers, which, on a 64-bit platform, makes each list node occupy 24 bytes due to alignment. There is also allocator overhead for each allocated chu... |
61,972,350 | 61,972,509 | How do I output the two new strings in main function in C++? | I need to write a program where a char array is initialized and split into 2 new c style strings without the connecting character. When I use the void function as a separate program it works but when I call it in my main function it doesnt. Is my way of calling the function incorrect or is there some mistake in the way... | Although I could recommend lot of changes in your code, like using C++ standard strings instead of C style strings, do proper bounds checking etc., the simplest changes that would fix your code are:
(1) Initialize counter variable to 0 in splitter function
(2) Inner for loop is written wrongly as for (i=0; i!='+'; i++)... |
61,972,450 | 61,972,468 | Why is this template always evaluated to false_type? | I would like to enable_if a member function exists in a class T, so I try to write the code below.
template< typename T, typename = void >
struct has_member_func : std::false_type {};
template< typename T >
struct has_member_func< T, decltype(&T::some_func) > : std::true_type {};
However, it always ... | When you use it like has_member_func<X>, the 2nd template parameter would use the default value void; but the partial specialization's 2nd template parameter's type is not void, then the specialization won't be selected; unless you specify the 2nd template argument explicitly to make them match like has_member_func<X, ... |
61,972,493 | 61,973,790 | How to generalize this C++ wrapper around a C 'class'? | I am writing a C++ wrapper around a C library. Here is an example of my strategy.
// header file
class LibrdfUri { // wrapper around librdf.h librdf_uri*
/*
* If the deleter of std::unique_ptr is an empty
* class then it can do some optimizations and
* not actually store the... | This is a better deleter:
template<auto f>
using deleter=std::integral_constant< std::decay_t<decltype(f)>, f >;
use:
deleter<librdf_free_uri>
is a stateless deleter that calls librdf_free_uri.
But we don't need that I think. Here is what I might do:
There are 3 pieces of information you need.
How to construct
How ... |
61,972,625 | 61,973,477 | To confirm only 1 and 0 exist in the Binary | I wanted to use only 1 and 0 for the binary. But instead the answer keep giving me the 2nd option with whatever number I typed. I had tried where did I programmed wrongly but unfortunately I still can't find it. So I hoped that I could get some help here.
#include<iostream>
#include<cmath>
using namespace std;
int Du... | Keep in mind that input from the console is text. If you need to check that the text matches a particular format (in this case, consists entirely of 1's and 0's), the simplest approach is to look at that text:
std::string input;
std::cin >> input;
bool input_is_valid = true;
for (int i = 0; input_is_valid && i < input.... |
61,972,761 | 61,972,809 | If statement will not run in do - while loop | Below is a demonstration of an issue I'm having.
The if statement in the do - while loop will not run. Even though the logic for the "while" is exactly the same and executes correctly. I've stepped through the issue with the debugger and the value of testVar is -1.00000000 and so on.
#include<iostream>
using namespace ... | "Yep!"; isn't a statement that does anything.
You probably meant std::cout << "Yep!\n";.
I'd have expected your compiler to warn about this.
|
61,972,787 | 61,984,282 | c++ how to free memory | I have the following issue:
I created a data structure to represent a Binary Search Tree using a class called Node. Each Node is connected by pointers to left child and right child.
Trees that will be built are very big (up to 1 milion nodes) so I need a way to free memory after each tree build.
The tree is represented... | In C++, this code:
BST_Node *bst = new BST_Node(...);
should be written:
auto bst = std::make_unique<BST_Node>(...);
This will create bst as a unique_ptr<BST_Node> object. The unique_ptr is a smart pointer class. Smart pointers automatically destroy the underlying object whenever they go out of scope. This frees you ... |
61,972,894 | 61,972,938 | Arduino use Parent class Method at child class | Is it possible a method defined by the parent class to use it with the child class without define it there again.
Like so:
Parent Header:
class parent
{
public:
parent(uin8_t);
void doit(uin8_t);
}
Parent cpp:
#include <parent.h>
parent::parent(uin8_t i)
{
...
}
void parent::doit(uin8_t i)
{
...
... | Yes, you just have to inherit the parent with public permissions (which means to keep the current class functions' permissions).
Change:
class child : parent
To:
class child : public parent
Read about:
Inheritance and access specifiers
|
61,973,137 | 61,973,278 | What is the difference between these two types of value assign in C++ pointers? | What is the difference of these two ways of variable value assignment ?
int x = 100;
int *valuePtr = &x;
*valuePtr = 20;
Why cannot I use int *valuePtr = x; this way ?
I will give a compile error. But after int *valuePtr = &x; and then *valuePtr = 20; will not give compile error.
Can anyone explain this ?
| int x = 100;
This declares an int variable called x and initializes it to 100.
int *valuePtr = &x;
This declares a pointer-to-int variable called valuePtr and initializes it with the address of x (& is the address-of operator).
*valuePtr = 20;
The expression *valuePtr dereferences the pointer and obtains a reference... |
61,973,294 | 61,973,339 | Prevent copy of shared pointer on return | I have a container derived from std::map that holds shared pointers, and a custom method for looking up elements, similar to the code below.
The container does not change while I use it, and I would like the lookup to return the shared pointer without making a copy, and not increment the pointer's counter. How can I en... | You might use null object to allow to return reference:
struct Xs : std::map< int, Xp >
{
const Xp& get( int n ) const {
static const Xp nullObject{nullptr};
auto p = find( n );
return p != end() ? p->second : nullObject;
}
};
|
61,973,463 | 61,997,615 | When injected into a program's memory space, how do you read each byte from 0 to 0xFFFFFFFFF? I am creating a pattern scanner | I am trying to create a pattern scanner, to find every byte sequence starting with "MZ" (4d5a) inside a programs memory. For that I'm injecting a DLL into the target program.
I try to look for the "MZ" pattern as I see some sneaky modules that are unlinking themselves from the modulelist.
From within the program's mem... | Virtual Address Space
The virtual address space for a process is the set of virtual memory
addresses that it can use. The address space for each process is
private and cannot be accessed by other processes unless it is shared.
Default Virtual Address Space for 32-bit Windows:
Low 2GB (0x00000000 through 0x7FFFFFFF... |
61,973,725 | 61,973,779 | Functional dependent attribute in c++ class/struct | I want to make a class/struct where one of the attributes is functionally dependent on other attributes. How can this be achieved?
struct Numbers {
int a;
int b;
int c; // c == a+b
}
Numbers n1 {1, 2, 3}; // Ok.
Numbers n2 {1, 2, 4}; // Error!
In my use case, a, b, c are constant, if that matters (so const in... | If a and b are mutable then you can't enforce that c is kept in sync; all three would have to be const for you to enforce this invariant.
The simplest approach would be to make c a function:
struct Numbers {
int a;
int b;
int c() const { return a + b; }
}
If you want the value of c to be cached instead of comput... |
61,973,982 | 61,974,582 | Using template to avoid free store? | I'm reading "The C++ Programming Language" Third Edition by Stroustrup Page Page 332. He says the following code specific to the template avoids use of the free store:
template <class T, int i> class Buffer {
T arr[i];
int sz;
public:
Buffer() : sz(i) {}
};
int main(int argc, char *argv[])
{
int arr[10];
Bu... |
Simple and constrained containers such as Buffer can be important where run-time efficiency and
compactness are paramount (thus preventing the use of a more general string or vector). Passing a
size as a template argument allows Buffer’s implementer to avoid free store use.
Variable-sized arrays require the use o... |
61,974,060 | 61,974,229 | c++ threading 'no matching overloaded function found' | #include <thread>
void f(int*& ptr)
{
ptr = new int[4];
ptr[0] = 0;
ptr[1] = 1;
ptr[2] = 2;
ptr[3] = 3;
}
int main()
{
int* ptr;
std::thread thread{ f, ptr };
thread.join();
delete[] ptr;
return 0;
}
I don't understand what I'm missing. I tried different combinations of refe... | The problem is that your function f takes a reference to a pointer. However, threads can't store reference-arguments for later invocation, so you must use a pointer to a pointer instead.
#include <thread>
void f(int** ptr)
{
*ptr = new int[4];
*ptr[0] = 0;
*ptr[1] = 1;
*ptr[2] = 2;
*ptr[3] = 3;
}
... |
61,974,096 | 61,996,968 | Getting -6.27744e+66 for vertex coordinate from CGAL 3D Mesh Generation: mesh_implicit_sphere example | I am extracting facet data from the generated mesh from the example code mentioned in the title with:
vector<CGAL::Mesh_complex_3_in_triangulation_3<Tr>::Facet_iterator> Facets;
for (CGAL::Mesh_complex_3_in_triangulation_3<Tr>::Facet_iterator it = c3t3.facets_begin(); it!=c3t3.facets_end() ; it++)
{
Fa... | The vertex 3 is most probably the infinite vertex. In CGAL triangulations are represented using an extra infinite vertex that is connected to all the points on the convex hull. You can use the function is_infinite() to check that.
As pointed by Alex, you should use a Cell_in_complex_iterator to access all the finite ce... |
61,974,219 | 61,974,590 | how to remove repetitions using map c++ | So i have Text.txt where are countries and rivers.So i have to output river and all countries where that current river exists.
Text.txt :
Spanish Taho
France Rhine
Ukrain Dnipro
Germany Rhine
Russia Dnipro
Portugal Taho
Code:
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;... | Your data structure is not appropriate for the solution.
Try below:
map<string, vector<string>> riverToCountryMap
And while inserting data:
riverToCountryMap[river].push_back(country);
|
61,974,598 | 61,975,150 | How do you pass fixed sized initializer lists of initializer lists through function parameters in C++? | I am making a matrix class where I want users to be able to instantiate the matrix like so:
Matrix<float, 2, 2> mat = { { 10, 20 }, { 30, 40 } };
My Matrix class is defined like so:
template<typename T, unsigned int ROWS, unsigned int COLS>
class Matrix
{
public:
Matrix(std::array<std::array<T, ROWS>, COLS> matrix)... | This seems to work...
template<typename T, unsigned int ROWS, unsigned int COLS>
class Matrix
{
public:
Matrix(const std::array<T, ROWS> (&matrix)[COLS]) {
// ...
}
};
int main() {
Matrix<float, 2, 2> mat = {{ { 10, 20 }, { 40, 40 } }};
}
Though the error message is quite bad when it fails, and i... |
61,974,961 | 61,975,455 | Error when trying to initialize a union inside a struct | So I a function which returns a pointer to a struct (parse_files_result_t*). This struct contains a union:
struct parse_files_result_t{
result_tag tag;
union {
struct parse_file_error_t *err_ptr;
struct parse_file_response_t *ok_ptr;
} data;
};
And I wanted to use the union to retur... |
Even though I wrote result->data.ok_ptr, my compiler tries to put the parse_file_response_t response into the parse_file_error_t part of the union.
Well, yes. You compacted so much into a single line, you lost track of what you are telling the computer to do.
*result = parse_files_result_t{result_tag::Ok, result-... |
61,974,999 | 61,975,131 | How can I recursively call a class member function via a function pointer? | I'm writing a library to run certain algorithms on tree-like objects. I have an edge_t class that has const unsigned int data members edge_id and weight that serve, respectively, as the edge_t's unique identifier and the weight of the edge.
I have written tree_t and subtree_t classes in C++, both of which contain maps... | f is already a pointer to the desired member, so just pass that:
populate_map(S, c, m, f);
&basic_tree_t::*f makes no sense in that context. It looks like an attempt to declare a pointer to a data member, which isn't what you want anyway.
|
61,975,605 | 61,983,922 | CreateWindowW window is too small | When I create my window, it is smaller than the width and height specified, that should be 840x840. The actual window created is only approx 825x782 (not including menus etc). I can't work out why the window is small and have never had this problem before. Thanks in advance.
CreateWindowW(wc.lpszClassName, L"Window",
... | The solution is to use AdjustWindowRect function as commented by Simon Mourier, where rect is the size of the client window.
RECT rect = {0, 0, width, height};
AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, true);
CreateWindowW(wc.lpszClassName, L"Window",
WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 200,
rec... |
61,975,715 | 61,975,812 | c4-pedestrian-detector.cpp:283:8: error: ‘Show_Detection_Steps’ was not declared in this scope | I am trying to compile the CPP file present here and it is giving me the following error. I am new to this. Any help will be highly appreciated. Also, any other way to compile and run it will be helpful if I am making it wrong.
(base) ritika@ritika-HP-Pavilion-Laptop-15-cc1xx:~/Downloads/C4-Real-time-pedestrian-detecti... | The code is indeed broken; Show_Detection_Steps is used before it is declared.
Some compilers let you get away with it due to different methods of implementing templates, which is probably why the author missed it. But the code is, per the C++ language, broken.
You should report this as a bug to the author, using the G... |
61,975,901 | 61,977,704 | Why does printing the 'address of index n' of c style strings lead to output of substring | I'm rather new to C++ and while working with a pointer to a char array (C style string) I was confused by its behavior with the ostream object.
const char* items {"sox"};
cout << items << endl;
cout << items[0] << endl;
cout << *items << endl;
cout << &items << endl;
cout << &items[1] << endl;
Running this leads to:
s... | Back in the olden days, when C ran the world, there was no std::string, and programmers had to make do with arrays of char to manage text. When C++ brought enlightenment (and std::string), old habits persevered, and arrays of char are still used to manage text. Because of this heritage, you'll find many places where ar... |
61,976,023 | 61,976,151 | What's the advantage of binding a base class to a derived class as opposed to simply creating a derived class pointer? | Notice in this example I created a derived class pointer (Laser* pLaser = new Laser) instead of a base class pointer like (Boat* pLaser = new Laser). Is there an advantage creating a base class pointer instead? Thanks!
#include <iostream>
using namespace std;
class Boat
{
protected:
... | Each one have a different purpose.
Child pointer
Laser* pLaser = new Laser purpose is to simply use dynamic allocation for this type, sometimes for sharing this data with other threads/processes. Usually you don't have to use it in C++, and you usually allocate this type on the stack.
Parent pointer
Boat* pLaser = new ... |
61,976,738 | 61,976,837 | Why is std::filesystem::file_size on directories left to the implementaiton? | So I have the following problem: I need to summarise the byte size of all files in a specific directory, this includes the size of the sub-directories, as in my case they actually can increase in size.
But if we run this code on a directory that contains files and sub-directories and look like this:
#include <filesyste... | The size of a directory can mean different things on different platforms and even different filesystems on the same platform: maybe the size of the disk allocation that holds the file list, or the number of files contained in the directory, or something else. On some platforms/filesystems there may not be a readily-ac... |
61,976,819 | 61,976,928 | C++ multi-thread program: Segementation fault with variables defined as class members | I am new to concurrent programming and learning it in C++. While learning std::condition_variable, I implemented a simple class ManageTransaction given below. Defining _cv, _mutex, and _balance as private members of the class causes a segmentation fault. Defining them globally doesn't cause it.
#include <iostream>
#in... | Your shared_ptr is uninitialised and will have a null value. Therefore as soon as the function attempts to access the private member data you'll get an access violation of sorts. Consider assigning your pointer using std::make_shared before trying to use it. Or better yet, do away with the shared_ptr; declare the varia... |
61,977,183 | 61,983,199 | C++ silently assigns a wrong type to an array element via an alias pointer | Here's the reduced code with the problem:
#include <iostream>
using namespace std;
struct A {
virtual void foo() {
cout<<"A::foo()"<<endl;
}
};
struct B : A {
void foo() {
cout<<"B::foo()"<<endl;
}
};
struct C : A {
void foo() {
cout<<"C::foo()"<<endl;
}
};
int main() {... | a[1] = c;
There is object slicing in this line and undefined behavior.
Type of the a[1] is A, so object of type C sliced to the object of type A.
a[1].foo(); //prints B::foo() when virtual, and A::foo() when non-virtual
B::foo() printed because assignment operator don't change the type of object, so it will not copy p... |
61,977,209 | 61,977,305 | Why this structure takes 24 bytes | template<typename T>
struct OctreeNode {
std::variant<std::unique_ptr<OctreeNode<T>[]>, std::unique_ptr<T>> data;
bool isLeaf;
}
sizeof(OctreeNode<int>)
I'm using x64 clang 10.
I thought it would take 8 bytes for variant and 8 for aligned boolean.
| To distinguish between stored types std::variant contains an additional integral value that your calculation misses.
#include <variant>
#include <memory>
template<typename T>
struct OctreeNode {
std::variant<std::unique_ptr<OctreeNode<T>[]>, std::unique_ptr<T>> data;
bool isLeaf;
};
template<typename T>
struc... |
61,977,228 | 61,977,250 | How to display the values of a class? | I am almost new in c++. I have created a class of a student. First of all, when i returned the media of the marks, it isn't a float value. For example: if I enter 5 and 10, it returns 7 instead of 7.5.
Secondly, when I want to display the name and media with the function disp(), it doesn't work.
Could anyone help a bi... | In this expression:
(mark1 + mark2) / 2;
you are doing integer division, since both the variables and the literal are int types. You could simply do:
(mark1 + mark2) / 2.0;
instead, to get floating point division.
To get disp to work, note that it doesn't return anything, so you need to simply call it like this:
pete... |
61,977,275 | 61,977,330 | static variable instantiation outside class | So I have this file
template <typename T>
class TestStatic {
public:
static int staticVal;
};
//static member initialization
template<typename T> int TestStatic<T>::staticVal;
I don’t understand why I have to instantiate the Staticval isn’t it already instantiated in the class definition? Also does it generate a ... | This line:
static int staticVal;
inside the class is a declaration, not a definition. That's why you have to define it outside the class like this:
template<typename T>
int TestStatic<T>::staticVal = 0;
And yes, this will generate a definition of the member for all types T.
Alternatively, you could define the static... |
61,977,381 | 61,977,483 | how to use a rvalue reference in a switch's case | I want to use t(rvalue reference) in a case of switch(T), but I get an error the value of 't' is not usable in a constant expression. How to do it the right way.
#include <iostream>
using namespace std;
int main(){
int (&&t)=5;
int T{};
switch(T){
case t: // error in this case
cout<<t<... | Note that case labels in a switch statement need to be constant expressions.
You can't use an rvalue reference as a case label, since it is not a constant expression. You can however use a compile time initialized variable:
constexpr int t = 5;
switch(...)
{
case t : ... // ok
}
Note that trying to do something lik... |
61,977,755 | 61,978,475 | why rapidjson fails to get this integer value | I'm surprised that the following code doesn't work as intended , I remember I had similar json which contained a lot of numbers but I don't know when it stopped working !!!
std::string_view jsonStr = "{ \"num\": 1, \"str\": 's' }";
rapidjson::Document doc;
doc.Parse(jsonStr.data());
std::cout << "num : " << doc["num"].... | That is not valid JSON.
Strings are surrounded by double quotes, not single quotes.
Refer to https://json.org for the schema.
Then check for error codes in your JSON parsing library: somewhere it will be telling you this, and you're ignoring it.
GetUint() on a non-existent property of a broken document will be returnin... |
61,977,834 | 61,977,917 | Using enable_if to change function declaration between pass by value vs pass by reference | I am writing a templated hashmap.
For I want a function declarations to be pass by reference if the templated type is fundemental.
For example with the following declaration:
template<typename K,
typename V,
typename Hasher = DEFAULT_HASH_32<K>,
typename Allocator = DEFAULT_MMAP_ALLOC<K, V... | Don't use SFINAE for something as simple as changing a signature. Instead, use some basic call-traits that adjust the parameter type:
#include <type_traits>
template <typename K, typename V>
class my_table
{
template <typename T>
using param_type = std::conditional_t<std::is_fundamental_v<T>, T, const T&>;
pu... |
61,978,183 | 61,978,214 | C++: How to return a pointer to a non-static member function? | I want to do something like this:
typedef int(A::*f_ptr)(int);
class A
{
int f1(int a){ /*do something*/ }
int f2(int a){ /*do something else*/ }
f_ptr pick_f(int i)
{
if(i)
return this->f1;
return this->f2;
}
}
The reason is that I want instances of class A to hold ... | You need to return the address of the member functions, like this:
f_ptr pick_f(int i)
{
if(i)
return &A::f1;
return &A::f2;
}
Or the equivalent terser version:
f_ptr pick_f(int i)
{
return i ? &A::f1 : &A::f2;
}
|
61,978,558 | 61,978,611 | Error when make, C++ 'db.c:2127: error: expected ';' before '||' token' | if ((mob_index[ZCMD.arg1].virtual < 7999) &&
(mob_index[ZCMD.arg1].virtual > 7899) ) {
do {
to_room = number(0, top_of_world);
}
while( (IS_SET_AR(world[to_room].room_flags,ROOM_PRIVATE))
||(IS_SET_AR(world[to_room].room_flags,ROOM_GODROOM))
... | You need to count your brackets
|| (zone_table[world[to_room].zone].number == 36) )
should be
|| (zone_table[world[to_room].zone].number == 36)
etc. etc.
|
61,978,634 | 61,978,729 | How do i pass a char into find_child_by_attribute for pugixml | i'm trying to pass a value from a file into tileNode.find_child_by_attribute("tileset","firstgid",container[0]).attribute("source").as_string(). it should return a string for an image path.
#include <iostream>
#include <vector>
#include "SFML/Graphics.hpp"
#include "../hpp/pugixml.hpp"
int main()
{
std::vector <c... | So taking a wild guess at what you actually mean I'm going to plump for this
char attr_value[] = { container[0], '\0' };
cout << tileNode.find_child_by_attribute("tileset","firstgid",attr_value).attribute("source").as_string();
The first line converts the character in container[0] into the null terminated string that ... |
61,978,753 | 61,978,821 | C++ Class Abstract Coordinates | So my goal is simple,
I want to have an x and y in the base class,
and then have my other class own those values as well
class Skeleton
{
private:
float x, y;
public:
Skeleton(float x, float y);
};
class Object : Skeleton
{
float getX() const
{
return x;
}
};
By the way, I'm sort of new ... | You can use the protected access specifier instead of private to allow classes which derive from your base class to access certain member functions and variables.
Also you'll need your derived classes constructor to call the base classes constructor.
class Skeleton
{
protected:
float x, y;
public:
Skeleton(flo... |
61,979,094 | 61,979,191 | How can I initialize a python-like list and write to a file in c++ | I have this code in python that I have to translate in c++, but I'm stuck because I can't figure out how I cant initialize a list like that in python and how I can write in a file like the code below
def to_file(sy, ey, sx, ex, name, dor):
rBloc = ["LINE\n", "8\n", str(dor) + "\n",
"10\n" + str(sx) + "... | You can use a C++ vector to replace a list in python. The whole code will look like this.
int dor=5,ex=10,sx=20,sy=30,ey=50;
vector<std::string> rBloc{ "LINE\n", "8\n", std::to_string(dor) + "\n",
"10\n" + std::to_string(sx) + "\n" + "11\n" + std::to_string(ex) + "\n" +
"20\n" + std::to_string... |
61,979,312 | 61,979,383 | Value of const changed in the memory but not on the output | I'm trying to write a program that changes the value of a const variable. I know this shouldn't be done this in the first place and I'm doing this just to know how this happen.
I've already read other questions about this but I'm not trying to know how to do it but why it isn't happening in my program. This is the cod... | It is undefined behaviour to modify a value which is initially declared as const.
https://en.cppreference.com/w/cpp/language/const_cast:
const_cast makes it possible to form a reference or pointer to
non-const type that is actually referring to a const object. Modifying
a const object through a non-const access pa... |
61,979,425 | 61,981,603 | Can I resurect removed std::result_of in MSVC 16.6 with some macro? | MSVC 16.6 in C++20 mode removes the result_of that was removed in C++20 standard.
I am all for doing the morally correct thing, but many 3rd party libraries(example) I use fail.
Sometimes MSVC enables users to define a define so that removed features are still enabled.
Is there an option to do that for result_of?
I h... | Defining _HAS_DEPRECATED_RESULT_OF and _SILENCE_CXX17_RESULT_OF_DEPRECATION_WARNING should more granularly restore result_of and turn off its deprecation warning.
_HAS_FEATURES_REMOVED_IN_CXX20 and _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS should do the same for all C++17 features retired in C++20.
Given past history, th... |
61,980,083 | 61,980,118 | How to comprehend "Temporary objs are destroyed as the last step in evaluating the full-expression"?Could anyone make it clear by some simple example? | As per the documentation(), which says:
When an implementation introduces a temporary object of a class that
has a non-trivial constructor ([class.default.ctor],
[class.copy.ctor]), it shall ensure that a constructor is called for
the temporary object. Similarly, the destructor shall be called for a
temporary ... | Simple example. This expression produces a temporary object:
std::string("test")
Here, that expression is used as a subexpression:
function(std::string("test"));
// point A
At point A, the temporary object has been destroyed because the point is after the full-expression where the temporary object was created.
Here... |
61,980,099 | 61,980,786 | How can I make a linux background process (in c) that launches a Python script | I made a Linux background process (in c++) that monitors a directory and attempts to launch a Python script if a certain file appears in that directory. My issue is that the child process responsible for launching the Python script exits immediately after the execvp function is called and I can't understand why. All of... | The question is a little unclear, so I'll try to take a few different educated guesses at what the problem is and address each one individually.
TL;DR: Remove close(STDOUT_FILENO) and close(STDERR_FILENO) to get more debugging information which will hopefully point you in the right direction.
execvp(3) is returning -1
... |
61,980,479 | 61,980,529 | Trouble returning float value from fpatan assembler function back into c++ program | I have a small program written in AT&T assembler for the x64 processor in linux and compiled it using Gnu Assembler using the fpatan function. I know I can get the atan value other ways. I am not able to understand how to move floating point values created in the st0-st7 registers into a C++ program.
In this example,... | x86-64 returns float in XMM0, not legacy x87 st0. Build your code with
g++ -m32 asm.s main.cpp -o runme to build 32-bit code that uses the 32-bit calling convention if you want to use legacy x87 for FP math.
Note that your C++ code isn't reading result, it's reading the return value of the function which it expects in... |
61,980,526 | 61,983,806 | How can I solve this ? error: unable to find library -lmysqlclient | I want to compile for my program and I am stuck here , I am usig freebsd 12.1 and gcc++6.4 + gnu gmake -j20 comand
Curent path
# mysql
INCDIR += -I../../../extern/mysql
LIBDIR += -L/usr/local/lib/mysq
LIBS += -lmysqlclient -lz -pthread -lm -lssl -lcrypto
### END
Error in putty
root@vps:/usr/src/Sursa/Server/source... | You have a typo in LIBDIR += -L/usr/local/lib/mysq - missing l.
Make sure you have mysql57-client package installed. If not, run pkg install mysql57-client.
Also, /usr/src dir is usually used to store FreeBSD source code. It is not a best idea to use it to store your own code.
|
61,980,668 | 61,981,196 | Can anyone contribute to C++ STL? | I am using C++ for couple of years and I am wondered how it works. So, I felt interested to see how this project is managed, gone through some google search but found nothing. So, I just want to know that is C++ STL implementation is a open source project like GitHub open source projects or can anyone request for a lib... | There are two things here; and I'm not sure which of those you mean.
There is the C++ standard - this is a specification of both the language and the library, and this is developed by the ISO SC22/WG21 committee. See the link that @Berto99 posted above.
Then there are implementations of that standard. Compilers and st... |
61,980,742 | 61,980,896 | Is std::packaged_task<T> (Function Template) an std::async (FT) with an invoked function? | Trying to work with packaged_task<T>
std::async creates a thread executed asynchronously and process data which we can access into, using the class template std::future<T> and the get() method.
What should i know about how packaged_task<T> works, in difference with std::async ?
And was the thread related to packaged_ta... | std::async(ploicy, callable, args...)
launches a new thread (if the resources are available) if the policy is std::async::launch.
If the policy is not determined, it may launch or not.
If the policy is std::async::deferred, won't launch.
while std::packaged_task wraps your callable so that it can be invoked asynchrono... |
61,981,167 | 61,981,193 | C++ How can I call one constructor or the other depending on the parameters passed as input? | I have these two constructors:
MyClass(char* path);
MyClass(int n);
and I need to call the first if the user has passed the path as an argument, the other otherwise.
My problem is that I don't know how to do this since I can't define the class without initialising it first, nor can I define a reference and then create... | You can use a ternary expression. (Before C++17, this requires that your class is copyable or movable.)
MyClass c = argc == n ? MyClass(argv[n-1]) : MyClass(10);
|
61,981,364 | 61,981,594 | Overloading operator "<<" in C++ with template-dependent type | I'm trying to overload the "<<" operator in order to print a class that has been declared inside a template class. I've looked for a solution but I haven't really found any examples similar to my own. The following code illustrates my problem:
#include <iostream>
template<class T>
class main_class
{
public:
class ... | #include <iostream>
template<class T>
class main_class
{
public:
class dependent_class
{
public:
dependent_class() : val(0) { }
friend std::ostream& operator<<(std::ostream& out, const main_class<T>::dependent_class& v){
return out << v.val;
}
protected:
int... |
61,981,777 | 61,981,830 | How can assign values to a array after initialization | I am initializing an array
float verticesRect[] = {
// Positions // Normal Coords // Texture Coords
width, height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 0.0f, // Top Right
width, -height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 1.0f, // Bottom Right
-width, -height, 0.0f, ... | You can use std::vector for this.
std::vector<float> verticesRect = {
// Positions // Normal Coords // Texture Coords
width, height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 0.0f, // Top Right
width, -height, 0.0f, 0.0 , 0.0, 1.0 , 1.0f, 1.0f, // Bottom Right
-widt... |
61,982,033 | 61,993,274 | How I can merge two 2D arrays according to row in c++ | I am facing a problem where two 2-dimensional arrays need to merge according to the given condition, where n=5 and k=3.
1st array->
1 2
3 4
5 6
7 8
9 10
2nd array->
11 12 13
14 15 16
17 18 19
20 21 22
23 24 25
The resultant array->
1 2 11 12 13
3 4 14 15 16
5 6 17 18 19
7 8 20 21 22
9 10 23 24 25
My a... | There are three main issues in the posted code
a, b and ans are declared as variable length arrays (their sizes aren't known at compile time), a non-standard extension provided by some compilers. The OP could have used a standard container like std::vector or a user-defined class.
All the loops start at 1, while in C+... |
61,982,046 | 61,983,732 | Why is my for loop giving error : X does not name a type | Can anybody tell me that when I use for loop to get the number of nodes stored in level 'it', then why it doesn't work?
And please do tell me other ways I can access a vector with a range based for loop.
// A simple representation of graph using STL
#include<iostream>
#include<vector>
using namespace std;
// A utilit... | First of all, there are some things missing in your approach:
You are adding edges in the graph and there is no input for it, i have assumed that V is for vertices only.
Whenever you want to check for the number of nodes in a particular level you should always mention a starting point. Because different starting point... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.