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 |
|---|---|---|---|---|
65,562,776 | 65,562,995 | Meaning of _Get_unwrapped? | I've been reading MS STL std::inner_product source and there seems to be a bit of usage of _Get_unwrapped, also on other places in the file. I managed to find the source of that thing but couldn't really decipher what does it do. What problem do I need to have to use such a thing? Is there maybe some kind of material t... |
but couldn't really decipher what does it do.
It does this:
If the class of the iterator argument is "unwrappable" (determined by the type trait _Unwrappable_v), then the function calls _Unwrapped member function of the iterator, and casts the result to rvalue reference to the iterator type and returns that.
Otherwi... |
65,562,986 | 65,563,714 | C++ best practice: Pass use-only (not stored) lambda argument to function by const-reference or by forwarding-reference (a.k.a. universal-reference) | What is the best (i.e. most performant, most versatile) way to pass a lambda function as a parameter to a function which only uses (but does not store or forward) the lambda function?
Option 1: Is passing it by const-reference the way to go?
template <typename F>
void just_invoke_func(const F& func) {
int i = 1;
... | If you try the different ways of taking different lambdas, you can see, that const references cannot take mutable lambdas and mutable reference cannot take temporaries (so you cannot define the lambda on the spot).
Both taking by value and taking by universal reference work for all types of lambdas. But the universal r... |
65,564,582 | 65,566,872 | How can I customize the child items in a TreeView of QML? | QML:
import QtQuick 2.2
import QtQuick.Controls 1.5
import QtQml.Models 2.2
import filesystem_browser 1.0
ApplicationWindow
{
visible: true
width: 640
height: 480
ItemSelectionModel
{
id: sel
// This model is comming from C++' class DisplayFileSystemModel.
model: treeViewMo... | My previous comment about using the row or column value was close, but incorrect. A quick look at the docs shows us that there is another property that gives us the depth of an item. So I think you can achieve what you want by simply doing something like this:
color: styleData.depth ? "blue" : "pink"
|
65,564,677 | 65,573,285 | clang-tidy parsing error at spaceship operator | Using clang++-11 with libstdc++-11 and clang-tidy-11, I run into failures when linting the code with clang-tidy - namely parsing error when dealing with the well-known sleeper std::this_thread::sleep_for(std::chrono::seconds(1));.
clang-tidy-11 -header-filter=include/ -p=/tmp/dev/build/bin/aggregation/ -quiet /tmp/de
v... | You can use the std::this_thread::sleep_until method with (now() + 1s) as argument.
|
65,564,700 | 65,564,858 | How to output a variable stored in another variable | So here's my code at the moment:
#include <iostream>
using namespace std;
int main() {
string x = "_one";
int sound_one = 7;
int sound_two = 8;
cout << ("sound") + x;
}
However when I run the code, it outputs 'sound_one' instead of '7'. How do I get it to output the variable sound_one instead of just... | C++ is not a reflective language in the sense that you can acquire a variable name at runtime (variable names are normally compiled out of the program). You can use std::map though to achieve your immediate aim:
#include <iostream>
#include <string>
#include <map>
int main() {
using std::literals::string_literals... |
65,564,824 | 65,564,894 | Can we use symbol in if statement in C++? | The user is asked to enter one of the following mathematical symbols:
+, -, *, or /
Can someone tell me how I can use these symbols in an if statement? If not, how can I do this without using an if statement, like 1 for addition, 2 for multiplication, etc?
if(z==+){
std::cout<<x<<"+"<<y<<" is "<<x+y;
}
| The user inputting a value will typically be inputted as a char or string(depending on how you are reading it in. You cannot just compare a variable to a + sign on its own, it instead do something like this:
if("+" == z) {
//do operation
}
else if("*" == z) {
//do operation
}
else {
//etc.
}
or use switches.
|
65,564,828 | 65,564,987 | could someone help me? OOP in C++ | could someone help me with my code, in line 44 I get an error when passing to the compiler since it tells me that the initializer is not declared and none of the arguments is valid. The function of my program is object-oriented in C ++, what I want to do is put information into the class adding values to those of Priva... | Here's your fixed program (notice added/edited comments):
#include <iostream>
#include <string>
#include <vector> // added - required header
using namespace std;
class Zoo {
private:
string esp;
int id;
string nom;
public:
Zoo() {} // added - a default constructor
Zoo(string, int, string);... |
65,564,890 | 65,565,061 | why can not p = itv?(vector problem from c++) | This is my code:
vector<int>::iterator itv = vec.begin();
int *p;
p = itv; // ERROR!
I have a simple question:
Why p can not get the value of itv, since p is an address and itv is also an address.
thanks. :D
| In general an iterator is not defined as a raw pointer.
In old versions of some compilers the iterator of the class template std::vector was indeed defined as just a pointer.
But in modern compilers iterators of standard containers are usually defined as objects of some classes.
You could rewrite your code snippet the ... |
65,565,049 | 65,575,246 | Using FindWindows multiple times in a C++ Program? | I use the following code(C++) to get the handle of a window (another application) and send message to one of the buttons to simulate a click and it works without any problem.
BOOL CALLBACK EnumChildProc(HWND hwnd, LPARAM lParam) {
mdv.test_list[mdv.counter] = hwnd;
mdv.counter++;
return TRUE;
}
void MDV:... | As the Comment pointed out, you could use UI Automation instead of sending click message to the button.
Take the dialog of messagebox as an example:
#include <Windows.h>
#include <iostream>
#include <thread>
#include <tchar.h>
#include <oleacc.h>
#include <UIAutomation.h>
using namespace std;
HWINEVENTHOOK EventHook ... |
65,565,506 | 65,565,602 | Segmentation Fault wrt NULL pointers C++ | I am trying to use a circular linked list to solve the Josephus problem. But in the create function I got a segmentation error regarding NULL pointer to the linked list node. Can anyone explain why there is a segmentation error? Thank You!
#include <iostream>
using namespace std;
struct llnode
{
int data;
bool ... | Your issue is right here:
llptr L, F;
What are L and F pointing to? As of now, they're both Wild Pointers. That is, you have no guarantee. So when you pass them to create() and check if(!L), it'll be false, since L is not nullptr.
So you'll then try to dereference L with L->ptr = F;. But again, L is pointing to some g... |
65,565,934 | 65,566,312 | Changing sprintf to an array of characters C++ | I have a 2d array of words.
void main() {
const int rowsCount = 2;
const int colsCount = 5;
char*** szData = new char** [rowsCount];
//Allocate memory for each row
for (int i = 0; i < rowsCount; i++)
{
szData[i] = new char* [colsCount]; //how many words in every row
for (int j ... | If you trace back the assignment of this pointer:
char s[] = "Williams";
You'll find you are attempting to free its memory here:
delete[] szData[i][j];
However, you can't do that -- the string "Williams" was never allocated with new, so it can't be freed with delete. In fact, it's statically allocated, in your binary.... |
65,565,994 | 65,574,799 | Create a gtest filter without wildcard | It's possible to create a GoogleTest filter without wildcard in it ?
I have a test suite TestSuiteA
TEST_P(TestSuiteA, Blabla) {
// ...
}
INSTANTIATE_TEST_CASE_P(Apple, TestSuiteA, testing::Combine(...));
INSTANTIATE_TEST_CASE_P(Ananas, TestSuiteA, testing::Combine(...));
And a second test suite TestSuiteB
TEST_P... | Each tests needs to have a unique name, and you haven't provided the exact correct name. That's why no tests were run. Make sure you know how exactly the tests are named - you can use --gtest_list_tests to list all the test cases defined in a given test executable. Then use the exact names with --gtest_filter separated... |
65,566,279 | 65,566,308 | How can function return a cstring larger than char array it is filling? | I want to start off and explain that this is just a curiosity question to help me better understand c++.
I am working with the cstring library in C++ to generate a long cstring from multiple variables. I was running a test program to see what the largest char array I would need to hold the cstring. To do this I defin... |
my hypothesis is that the cstring gets written to the memory and strcat keeps writing past the bounds set when buffer or gbuffer are defined and std::cout just reads until it hits the null char, so as long as nothing else reserves that space or is written there, the program still works out, though there is no guarante... |
65,566,294 | 65,566,315 | Can I safely get a c_str out of std::stringstream in c++? | I am working with a C function that takes a string (i.e. a pointer to a null terminated array of char) and does stuff with it internally. It does not, however, keep a reference to the string after the function returns.
I want to pass it some formatted input, so I am using a std::stringstream. In order to keep my code c... | Yes that's fine, and ss.str().c_str() crops up quite often when working with C-style APIs.
Informally speaking, the anonymous temporary std::string returned from ss.str() survives the puts() function call. This means that the const char* pointer returned by c_str() remains valid for the duration of puts().
What you can... |
65,566,387 | 65,567,607 | Cpp: parse string snippets to tuple | I want to parse string snippets to a tuple:
example string: "Dolly Davenell,8809903417,1 Toban Circle,Luozhou"
tuple<string, unsigned int, string, string>
i read the strings from a file and store them with getline in a vector (myPersVec), where each vector element is a string as dscribed above.
Now my problem is that i... | There are many ways to parse the data. You can use std::stringstream or find or whatever. I believe the question you are asking is how to store the values directly into a tuple. For that, use std::get which returns a reference to the value in the tuple.
// Parameter s is the line to parse. Ex: "Dolly Davenell,880990341... |
65,566,460 | 65,566,801 | C++ code returning multiple duplicate characters | This is my code to print duplicate character in C++.
#include <iostream>
#include<string.h>
using namespace std;
int main()
{
char string[80];
cin.getline(string,80);
for(int i=0;i<strlen(string);i++){
for(int j=i+1;j<strlen(string);j++){
if(string[i]==string[j]){
... | Analyzing your codes, your code check the only characters rear to any character.
That is, if you input malayalam and i is 1 while for operates, your code check if a exists in layalam.
Then, there are three as. However, your code doesn't print these as all.
Your code will print a only once.
Therefore,
i=0 → string[0]='m... |
65,566,561 | 65,566,839 | Detect if inherited function is overridden | I came up with the following code detecting at compile time if inherited functions are overridden in the derived class. It works with all major compilers - gcc/clang/msvc.
But is this approach actually backed by the standard?
#include <type_traits>
struct B {
virtual void f1() {}
virtual void f2() {}
void ... | Found it, this is covered by by section 20.15.9 Member relationships, point 5 of the standard:
Note: The type of a pointer-to-member expression &C::b is not always a
pointer to member of C, leading to potentially surprising results when
using these functions in conjunction with inheritance.
Given example:
struct A { ... |
65,566,843 | 65,566,885 | Fractional Knapsack Algorithm segmentation fault | I am trying to solve the fractional knapsack problem by writing a function get_optimal_value which returns the total optimal value given the capacity of knapsack and weights and values of items. Over here in the function get_optimal_value, i am running into a segmentation fault problem on v_per_w[i] = values[i]/weights... | vector<double> v_per_w = {};
This creates a new vector, which is completely empty. It has no values. Immediately afterwards:
v_per_w[i] = values[i]/weights[i]; //calculate v/w for the vector
This attempts to change the existing values of v_per_w. However, since v_per_w is completely empty it has no values; this is a ... |
65,566,990 | 65,567,159 | How Modern OpenGL ID's works? | i don't understand how OpenGL ID works. Example:
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_... | glGenBuffers reserves numbers (names) for Buffer Objects. glBindBuffer creates the buffer object with the specified number (name) if it does not already exist.
glGenVertexArrays creates respectively reserves numbers (names) that can be used for Vertex Array Objects. glBindVertexArray creates the Vertex Array Object wit... |
65,567,088 | 65,567,151 | WM_DESTROY message confusion | Having such a simple Win application:
bool continueRunning = true;
...
int APIENTRY wWinMain(...) {
while (continueRunning) {
PeekMessage(&msg, 0, 0, 0, PM_REMOVE);
TranslateMessage(&msg);
DispatchMessage(&msg);
if (WM_DESTROY == msg.message) {
... | PeekMessage (or GetMessage) dispatches sent messages (from other threads) on its own without returning them. Only posted messages are returned by it. If a message is sent by the same thread, it does not even go via PeekMessages, it is effectively a direct window procedure call. WM_DESTROY is sent.
By the way, avoid not... |
65,567,411 | 65,571,656 | How can I influence the the source directory of an executable or library? | I recently noticed something odd when compiling the following C++ program:
int main() { return 0; }
using g++ on linux. Specifically, I compiled the program (located in /a/directory ) twice using the following two commands:
g++ -g -o main main.cc and
g++ -g -o /a/directory/main /a/directory/main.cc.
For each program... | CMake will always use absolute paths when compiling, reason is described here.
However, you can use the GCC option -fdebug-prefix-map to change the debugging paths that are embedded in the binary. Its documentation is located here.
I tried this:
g++ -g -o `pwd`/main `pwd`/main.cc -fdebug-prefix-map=`pwd`=.
and the gdb... |
65,567,955 | 65,568,038 | How do I output the first, the last, the second, the second to last etc elements in an array? | If I say I want 10 elements, for example 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, I want the output to be 1, 10, 2, 9, 3, 8, 4, 7, 5, 6.
And I can't figure out a way to do it.
#include <iostream>
using namespace std;
int main()
{
int n, v[1000], j=0;
cin >> n;
for(int i=0; i<n; i++){
cin >> v[i];
}... | You can do this like this way : at first let's think the n is even, so we can divide the length of the array in two equal part, now we will go to the first part and with every element of the first half of the array we will print the respective element from the last. Anf if n is odd then at the end we need to print the... |
65,568,323 | 65,578,990 | To share an exported C++ DLL event, within an external C++ Win32 Application | Have a good day!
For portability reasons, i have created a C++ DLL with almost novice C++ knowledge just by searching thousands of pages, hundreds of compiling error corrections and couple of stackoverflow questions.
It is far beyond being stable but it is working most of the time :)
Just for curiosity and modularity r... | Once again, thanks to @dxiv's comment; helped me a lot, to sort things out! Even, when someone tells you that it should work, you resolve 90% of the problem.
At the DLL side
DLL void evntReceived(const char *received)
{
s_pCallback(received);
}
The DLL is calling the above function all the time as soon as it rece... |
65,568,579 | 65,570,241 | Multiple cross-compilation targets for drivers with CMake | I am developing a driver for a hardware module and I want to make it as portable as possible while using CMake. Are there best practices to achieve this?
There is common code that should be used in all platforms and platform-dependent code.
What directory structure fits this use case?
How do I structure the CMakeLists.... | I would propose to have common implementation in the root your source directory while having dedicated architecture specifics in arch directory. Then you can select appropirate architecture dependent code in root CMakeLists.txt using
add_subdirectory( ${PROJECT_SOURCE_DIR}/arch/${CMAKE_TARGET_PROCESSOR} )
Samle projec... |
65,568,827 | 65,568,948 | Why the Note 3 in [class.temporary]/2? Shouldn't paragraphs (2.1) thru (2.6) have normative status? | [class.temporary]/2
The materialization of a temporary object is generally delayed as long as possible in order to avoid creating unnecessary temporary objects.
[Note 3: Temporary objects are materialized:
(2.1) when binding a reference to a prvalue ([dcl.init.ref], [expr.type.conv], [expr.dynamic.cast], [expr.static.... | The referenced sections ([dcl.init.ref] etc.) have normative wording that specifies exactly when temporary materialization occurs. This note exists only as a quick reference so you don't have to look through the whole standard to find all the situations where temporary materialization happens. If it were normative, the... |
65,569,245 | 65,570,148 | Clang-format: How to avoid new line breaks | Using clang-format I often encounter issues like:
// I want this
umbra_map_ops.flags = UMBRA_MAP_CREATE_SHADOW_ON_TOUCH |
UMBRA_MAP_SHADOW_SHARED_READONLY;
// Formatting gives me this
umbra_map_ops.flags =
UMBRA_MAP_CREATE_SHADOW_ON_TOUCH | UMBRA_MAP_SHADOW_SHARED_READONLY;
// I want this
... | For the first case, you need:
AlignOperands: Align
PenaltyBreakAssignment: 6
The first should be straightforward; it is exactly for what you want. The second is needed to tweak clang-format to not prefer breaking the assignment and having the right hand operand on single line. You may need to experiment with different... |
65,569,626 | 65,570,045 | Variadic template function specialization in a template class | I am trying to implement an own SmartPointer class and after an initial working version I have started to refine the code and now facing an issue, that I am unable to resolve.
Here is the first version:
template<class T>
class SmartPointer
{
private:
T* ptr;
public:
explicit SmartPointer(T* p = nullptr):ptr(p){... | I suppose your problem (with a single constructor) is caused from "vexing parse" (here a description of the "most vexing parse problem", a more spectacular version of the problem).
I mean... if you write
SmartPointer<int> intSP();
the compiler interpret it as a function declaration.
If you want initialize a variable w... |
65,570,033 | 65,570,082 | C++ - using base class as template parameter | I'd like my template function to accept as an argument only a class that inherits from a base class. I think a code snippet explains it better.
class Base
{
// Some magic
}
class Derived : public Base
{
// Even more magic
}
class Foo
{}
// Is it possible to tell template to accept only classes derived from B... | Pre-C++20 you can use enable_if coupled with checking is_base_of:
template<class T, std::enable_if_t<std::is_base_of_v<Base, T> && !std::is_same_v<Base, T>, int> = 0>
void do_something(T obj)
{
// Perform some dark magic incantations on obj
}
Note that I've explicitly disallowed the type to be an instance of Base ... |
65,570,336 | 65,571,598 | What actually happens in asynchronous IO | I keep reading about why asynchronous IO is better than synchronous IO, which is because in a-sync IO, your program can keep running, while in sync IO you're blocked until operation is finished.
I do not understand this saying because using sync IO (such as write()) the kernel writes the data to the disk - it doesn't h... |
I do not understand this saying because using sync IO (such as write()) the kernel writes the data to the disk - it doesn't happen by itself. The kernel do need CPU time in order to do it.
No. Most modern devices are able to transfer data to/from RAM by themselves (using DMA or bus mastering).
For an example; the CPU... |
65,570,442 | 65,570,520 | Is it possible in C++ to type multiple lines of string outputs without have to continually add the prefix "cout"? | I just started learning C++. I have seen examples of coders typing code like this...
int main() {
cout << "hello";
<< "world";
return 0;
}
but when I tried that it seemed to me that I have to write it like this...
int main() {
cout << "hello";
cout << "world";
return 0;
}
How can I do th... | You might mean:
int main() {
cout << "hello" // <- no trailing `;`
<< "world";
return 0;
}
That will print:
helloworld
If you wanted then on separated rows, you can write:
int main() {
cout << "hello\n"
<< "world\n";
return 0;
}
That will produce:
hello
world
But, there is anoth... |
65,570,492 | 65,570,528 | C++ parent object loses the internal data of the child object, something wrong related to copy constructor or passing by reference? | My question is explained in the example below. It is weird that the parent object loses the internal data of its child object, if the parent object is instantiated before the child object populates its internal data.
The code has a TicketService, which internally holds a TicketStore instance. The store is populated wit... | The TicketService constructor is making a copy of the TicketStore object that is passed in to it. In your second example, that object is empty when the service object is created. Any changes made to the store object in main() after the service object is created will not be reflected in that copy.
For what you are att... |
65,570,766 | 65,570,854 | Issues with Ascii Control Characters in .txt files, XOR encryption, C++ | C++, I want to be able to "encrypt" and decrypt a .txt file using a character by character XOR with a key of
"1".
I am able to successfully encrypt and decrypt "Hello World" but larger text files seem to have some XORs mapping to Ascii control characters that cause the decryption to not fully decrypt the entire file.
H... | When you create a std::ofstream or std::istream object you use 2 parameters ctor, but second parameter has default value (std::ios::in and std::ios::out respectevely) and that opens the file in the "text" mode by default, which on Windows will enable control character handling and mapping \r to "\r\n" and vice versa.
S... |
65,570,784 | 65,571,361 | How to find the pairs that are relatively prime in an array? | I need to put numbers in an array and take the ones that are at equal distances from the end of the interval
Example: 6 numbers, {3, 4, 6, 36, 45, 97} -> 3 and 97, 4 and 45, 6 36;
Then I need to check if they are relatively prime.
Example: 3 and 97 are relatively prime, because they have no common divisors, 4 and 45 as... | Two integers are relatively prime if and only if their greatest common divisor is 1. Therefore, to check whether x and y are relatively prime, do std::gcd(x, y) == 1 (std::gcd requires C++17, GCC has __gcd, or implement it yourself).
other observations:
ceil(n/2) is equal to n/2. Use (n+1)/2 if you want to round up.
Y... |
65,570,816 | 65,570,861 | std::unique_ptr takes too much space when we add any data type | #include <iostream>
#include <memory>
int main() {
int i = 0;
float f = 0.0f;
double d1 = 0.0, d2 = 0.0, d3 = 0.0, d4 = 0.0;
auto a = [i,f,d1,d2,d3,d4](){};
std::cout << sizeof(std::unique_ptr<decltype(a)>) << std::endl; // 8
std::cout << sizeof(std::unique_ptr<char, decltype(a)>) << s... |
Why the output of this program is 48 when I add just one char?
Because you specify a deleter that contains an int a float and 4 doubles. That deleter is stored as a sub object of the unique pointer.
Note that such unique pointer wouldn't work in the first place since the deleter doesn't satisfy the necessary requirem... |
65,570,879 | 65,571,578 | Reading Point Cloud .bin file using C++ | I'm trying to read .bin point cloud files. I found this link suggesting a python code that I can convert to C++.
I came up with the following code, but the precision of the floating point numbers are different compared to the results that I got from running the python code in the above link. I noticed that some coordin... | Here's a code that produces exactly the same output as the Python version:
#include <iostream>
#include <fstream>
#include <cmath>
int main()
{
std::ifstream file("1.pcd.bin", std::ios::in | std::ios::binary);
if (!file) return EXIT_FAILURE;
float item;
while (file.read((char*)&item, 4))
{
std::cout << ... |
65,570,909 | 65,571,168 | SDL2 SDL_GetRenderDrawColor only able to display black | I am able to make a window with SDL2 and C++ that has a black background, as soon as I change one of the arguments from SDL_GetRenderDrawColor from 0 to anything else I get this error:
Error (active) E0167 argument of type "int" is incompatible with
parameter of type "Uint8 *"
this is my code:
#include <stdio.h>... | If you want to set the render draw color, you should use SDL_SetRenderDrawColor. SDL_GetRenderDrawColor is used to get the render draw color.
|
65,570,935 | 65,571,491 | Is it possible to initialize a vector of strings from an array? If so, how? | So for example, on GeeksForGeeks.org, contributing user "Kartik" offers the following example for initializing a vector of integers:
// CPP program to initialize a vector from
// an array.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 10, 20, 30 };
int n = sizeof(arr) / sizeof... | sizeof(arr)
sizeof gets the size of an object in bytes. The size of an object is the total number of bytes required by the object. Note that I'm using "object" in the C++ context, not the OOP context (an instance of a class).
The size of an object of a given type is always the same. A std::string containing "a" is the ... |
65,571,194 | 65,571,231 | C++: How call a function with type parameter on variadic template arguments? | So I have a function with variadic template arguments and I'm trying to invoke a method (with a type parameter) for every argument, pack every result value in a std::tuple and return it. However variadic templates are pretty hard for me and I haven't fully understood them yet.
Is it even possible to realize this in C++... | First of all, you forgot the
#include <tuple>
And the syntax you're probably looking for is:
return std::make_tuple(get<Ts>(stream)...);
|
65,571,318 | 65,571,346 | C++ project: Where to define global variable with function | I'm writing a C++ project where, at some point, I need to generate a list of random numbers, which I call "Zobrist" numbers. I tried to do something like this:
File "zobrist.h":
#ifndef ZOBRIST_H
#define ZOBRIST_H
namespace Zobrist
{
int ZOBRIST_NUMBERS[64];
bool ZOBRIST_NUMBERS_GENERATED;
void GENERATE_ZOBRIST_NUMBER... | Your header file contains definitions of several variables, and that header is included in multiple source file, so multiple source files have their own copy of those variables. When you then attempt to link the compiled object files, it results in a multiple definition error.
You need to declare the variables in the ... |
65,571,762 | 65,572,321 | C++ template metaprogramming nested switch statement | Let's assume I have an union type (variant type) like this one (simplified just for demonstration purposes)
enum class Type : uint32_t
{
Unknown = 0,
Int64 = 1,
UInt64 = 2,
Double = 3
};
struct Value
{
Type dtype;
union
{
int64_t i;
uint64_t u;
double d;
};
}
And I intend to dispatch this ... | You could make a variadic templated function that does the switch on the first argument and calls itself with the rest and a lambda that saves the first argument's type:
template<typename F, typename... T>
// decltype(auto) is used to deduce the return type from F, throughout
decltype(auto) apply_func(F f, const Value&... |
65,571,811 | 65,571,848 | How to use move constructor with deleted default consturctor | I have an existing piece of code like this:
struct Base {
Base() = default;
};
struct Derive: public Base
{
Derive() = default;
Derive(const Derive&) = delete;
Derive(Derive&& p) { *this = std::move(p); }
Derive& operator = (const Derive& p) = delete;
Derive& operator = (Derive&& p) {
r... | The problem with
Derive(Derive&& p) xxx { *this = std::move(p); }
is that in the xxx part you have an empty member initialization list. That means the compiler will insert one for you for the base class since all members get initialized in the member initialization list before the constructor body is executed. That ... |
65,571,822 | 65,573,694 | Visual Studio C++ how to add header files in a prefix folder | I cloned a github C++ repository. The repository is not a VS project. So I manually created a VS C++ blank project and added the files from the repo to the project. The files are not copied. This is not the problem.
The repo directory looks like this:
include\NTL\*.h
src\*.cpp
*.h means a bunch of header files and *.c... | All previous No such file or directory errors were the result of some combination of:
Mismatching project properties Configuration and Platform
Some .h files were actually missing from NTL github repo, e.g. mach_desc.h.
The solution to the problem consists of the following:
Under project Properties > C/C++, add the ... |
65,571,936 | 65,572,100 | c++ for every string in vector check if it contains a substring | I need to write a program that gives the results of arithmetic operations for large positive integers. There are 4 basic operations to consider: addition (+), subtraction (-), multiplication (*) and division of integers (/). The first line of the standard input contains a single integer Z that determines the number of... | Do it like this
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector <string> operacje;
operacje.push_back("124/5");
operacje.push_back("678-7");
operacje.push_back("8/454545");
for (const string& str: operacje)
{
... |
65,572,371 | 65,572,495 | Draw button on top of ImageList videos in C++ with winapi | I'm having trouble drawing a button on top of a video with WinAPI. I am grabbing frames from the webcam and drawing those frames as soon as I get them. The problem is that whenever I draw an image the button disappears under it.
I tried using SetWindowPos(button, HWND_TOPMOST, 50, 50, 50, 50, SWP_SHOWWINDOW); to place ... | You can add WS_CLIPSIBLINGS style to the button ,
Clips child windows relative to each other; that is, when a particular
child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style
clips all other overlapping child windows out of the region of the
child window to be updated. If WS_CLIPSIBLINGS is not specified... |
65,572,464 | 65,572,489 | How to initialize a character or string array using for loop in c++? | I want to make a 2 dimensional array of 13 rows and 6 columns all initialized with character X. to do so I'm doing this.
char myseats[13][5];
for (int i; i < 13; i++)
{
myseats[i] = { 'X' };
for (int j; j < 5; j++)
{
myseats[j] = {'X'};
}
}
}
however this gives me a error and th... | Try this:
char myseats[13][5];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 5; j++)
{
myseats[i][j] = 'X';
}
}
First, the i and j where not initialized in the loop. You need to define at what index you want them to start.
Second, the correct way to access a two dimensional array is with the syntax... |
65,572,498 | 65,572,745 | Stuck in pointers, printing the vector of class objects with vector of pointers to the output console | I am new to programming and stuck with an example.
I have created a class ptr_generator that creates an array of pointers through its constructor. Here these pointers point to a vector of doubles.
Then a vector myvec of class ptr_generator type is created.
I am having problems printing out the initial vector of doubl... | You need to overload the operator<< function for ptr_generator.
The std::array is not stored outside of the constructor, so we'll add that as a member of the ptr_generator class. Then we will do two loops; One to loop over the array and one to loop over the vectors. As the array holds vector pointers, we need to derefe... |
65,572,567 | 65,572,816 | std::make_unique with placement new | I'm trying to define a Data object that contains its size, followed by size bytes of data.
Something like:
struct Data {
size_t size;
char data[1];
static void* operator new( std::size_t size, size_t dataSize ) {
return ::operator new( size+dataSize-1 );
}
static void operator delete( v... | There is no standard way to do this, because standard C++ doesn't provide any real support for VLAs/flexible array members. make_unique was written solely for either:
A single object of fixed size (it has no mechanism to provide information about the "real" size, it just uses new, which assumes sizeof T is correct and... |
65,572,667 | 65,572,993 | C++ Change a word to another | I want to write a tool to change the word to another one, as I give! It matches that already some day and all the time there is a problem that my word is cut off or something is wrong. then I want a better program with the use of std :: regex but I can't cope with this problem anymore ..
#include <iostream>
#include <f... | Try something more like this instead:
#include <iostream>
#include <fstream>
void display_members()
{
std::string oldWord, newWord, tmp;
std::string::size_type pos;
std::cin >> oldWord;
std::cin >> newWord;
std::ifstream openfile("test");
while (getline(openfile, tmp))
{
pos = 0;
... |
65,572,727 | 65,572,762 | How can a pointer be an rvalue? | #include <iostream>
void func(int*&& ptr)
{
int j = 0;
ptr = &j;
}
int main()
{
int i = 0;
std::cout << &i << std::endl;
func(&i);
std::cout << &i;
}
Pointless program I know, but I am just trying to learn.
Expected output: First cout to print the memory location to i and the second cout woul... | Let's put aside that "definitely stored somewhere in memory" doesn't strictly apply to any object in C++ (which is an abstraction over computer programming, not actual computer programming!), as that's not really the point here.
Though the int refered to by the name i is an object that "exists in memory somewhere", the... |
65,572,873 | 65,576,536 | How can I unpack multidimensional c-style array type and declare std::array instance? | I'm writing a template that can convert a c style multidimensional array to a std array and declare it.
get c-style array matrix
template <typename, typename IS = std::index_sequence<>>
struct unpacked_array_type_impl
{
using type = IS;
};
template <typename T, std::size_t ... I>
struct unpacked_array_type_impl<... | First template return std::index_sequence, whereas the second take a list of number.
You might use std::index_sequence for both:
template<typename T, typename Seq>
struct myArray_impl;
template<typename T, size_t size, size_t... more>
struct myArray_impl<T, std::index_sequence<size, more...>>
{
using type = std::... |
65,572,929 | 65,575,166 | How to read the txt files (unknown names) from a directory but C++17? | I was trying to do this with the header <experimental/filesystem> but in c++17 it is deprectaed. I don't put the code here because i dont even sure what i was doing.
Basically, i want to see all txt files that are in the same directory as the executable, but we don't know the names of that txt files or how many txt fil... | With C++ 17 this is really easy.
Try the program below:
#include <iostream>
#include <filesystem>
#include <vector>
#include <iterator>
#include <algorithm>
namespace fs = std::filesystem;
int main(int argc, char* argv[]) {
// The start path. Use Program path
const fs::path startPath{ fs::path(argv[0]).paren... |
65,573,094 | 65,582,863 | Stl iterators with Eigen matrices | I have some functions that involves stl iterators and works with types like std::vector<Eigen::Vector2d>.
For example:
template<typename T>
bool isLeftOf(const Eigen::Vector2<T>& a,
const Eigen::Vector2<T>& b) {
return (a.x() < b.x() || (a.x() == b.x() && a.y() < b.y()));
}
int main()
{
std::vector<E... | Using the master version of Eigen, you can use STL-like iterators which access rows or columns of matrices:
Assuming myVec is a matrix you can write this to get the "left-most" column:
Eigen::Vector2i element = *std::min_element(
myVec.colwise().begin(), myVec.colwise().end(),
[](auto const& a, auto cons... |
65,573,418 | 65,573,502 | Decrementable requirements of general end iterators vs container `end()` | I am working on a ReversibleContainer and its associated LegacyRandomAccessIterators. They wrap a pre-existing data structure that represents a directly-indexable collection of objects. I decided to allow the iterators to exist standalone, and to make default-constructed iterators represent the "end":
// constructs an ... | As a frame challenge, what you have here is a sentinal. A sentinal is something you can compare iterators to, but is not an iterator.
The motivating example is a type that when compared with a char pointer just checks if the dereference of the char pointer is null. You can use this to write C-level "read string until... |
65,573,514 | 65,593,078 | Postgres C extended data type definition | When dealing with the following problems, Postgres is a bit tricky to deal with more complex structures. I want to set up a two-dimensional array of structure, but I don't know how to make Postgres C support me to do so? Do anyone have any ideas?
Table
id contents(text) num(double)
1 I lo... | I'm not sure why you need C extended data type, but the following will give you what you want and can be implemented as plpgsql function.
WITH t1 AS (
SELECT id, contents, unnest (num) AS n FROM table
),
t2 AS (
SELECT id, contents, n,
row_number () OVER (PARTITION BY id ORDER BY id) AS o
FROM t1 ... |
65,573,570 | 65,573,769 | Create event handler at runtime without using WndProc win32 c++ | While using C#, it was easy before to create an event handler at runtime like:
Button button1 = new button1();
button1.click += Button_Click(); //Create handler
button1.click -= Button_Click(); //Remove handler
public void Button_Click()
{
//Button clicked
}
But in win32 I am stuck with WndProc callback where ... | The message ID is just an unsigned integer, so there's not really anything special about it. Although the giant switch statement is one common way to handle messages, you can do things quite differently if you choose. To support dynamic insertion/deletion of handlers, one possibility would be to use an std::unordered_m... |
65,573,932 | 65,574,429 | How to read data in file that contain diffrent size in c++ |
file_name = file_name_out_of_class;
ifstream file(file_name);
if (file.is_open()) {
string line;
int temp_sap;
int temp_sem;
int temp_cours;
int temp_cred;
while (getline(file, line)) {
cout << sizeof(info) << endl;
//????????
}
}
C++
This pic contains data of the... | Since the most important information, I mean, the column header, or field names, or student attribute is missing, I can only give a general answer.
You should abstract the data in one line into a corresponding data structure. I give you an artificial example. A line, as you did show above, could be structured like this... |
65,574,258 | 65,575,354 | Overflow error when using C++ std::cin, has strange value inside variable (C++11) | For a C++ program, I've implemented 2 functions:
Make1DArray that takes array size as input and creates a 1D array of that size
Make2DArray that takes size of row and column and creates a 2D array of the given row and column sizes
The main function looks like this:
int main()
{
cout << "enter 1d array length: ";
... | The problem
THe problem is that the first overflow sets the failbit due to the value overflow. The subsequent readings are not performed, leaving nrows and ncols in an undefined state. If you'd initialize theses variables, you'll notice that they wouldn't change.
Solution
Do not use int for holding the size but size_... |
65,574,696 | 65,583,511 | Unable to do tail recursion in C++ using clang with -O3 option | I am unable to tell the clang compiler to perform tail-recursive optimisation in my C++ code. I saw this post Which, if any, C++ compilers do tail-recursion optimization?, where the advice is to use the -O3 flag with clang and it would do it. But in spite of that, I am having stack overflow for large inputs to the belo... | Something is odd about mpz_is_divisible. For one, you forget to free the memory held by rem. Even if you add the mpz_clear(rem) call, you don't get TCO in smallest_divisor. What you have to do is mark it __attribute__((noinline)) to get Clang to do the optimization (though GCC does it without it). Very strange, and als... |
65,575,286 | 65,619,761 | How to fix the segmentation fault(core dumped) error on c++ while reading the file? | When I tried to run this code on c++ 17 it worked but then on c++ it doesn't. While running the first time it just gives me the string value of the last entered elements but when I run it the second time it shows the segmentation fault(core dumped) error. Can someone help me with this?
Here is my code:
#include<iostrea... | f.read((char*)&obj, sizeof(obj));
This cast is nonsensical. There are two ways to see why this can't possibly work:
Say obj is a std::string. This code must read a fixed number of bytes (otherwise, what is it passing to read?). But what number of bytes is sufficient for any possible contents of a string? Clearly, thi... |
65,575,846 | 65,576,860 | Generate functions with a function in C++ | I am working with C++ and need to generate a matrix whose elements are the monomials of a power series, evaluated at various coordinates. For example, suppose each row of my matrix is generated by evaluating the monomials 1, x, y, x*x, x*y, y*y, at coordinates (x,y) = (-1,-1), (0,0), (1,1), then it is written as:
1 -1 ... | You can return std::array/std::vector from functions/lambdas:
std::vector<int> createRow(int x, int y)
{
return {1, x, y, x * x, x * y, y * y};
}
template <typename RowGenerator>
std::vector<std::vector<int>>
createMatrix(RowGenerator gen, const std::vector<std::pair<int, int>>& input)
{
std::vector<std::vecto... |
65,576,084 | 65,576,126 | Why the same statement doesn't work for Class member in C++? | I'm very new to C++ and below is my program. It defines a nested vector.
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
vector<vector<int>> grid(10, vector<int>(10, 10000));
return 0;
}
When I define the same vector as a class member, it reports syntax error:
#include <vector>
usi... | You can use braced initializer or equal-sign initializer for default member initializer (since C++11), which doesn't support parentheses initializer; as the error message said, it attempts to be interpreted as function.
E.g.
class Test {
public:
vector<vector<int>> grid{10, vector<int>(10, 10000)};
};
or
class Tes... |
65,576,266 | 65,576,299 | Why this C++ lambda funtion returns 1? | I have a lambda function as below, it explicitly declares int as its return type, but in its realization, it does nothing. Besides, it prints out its return value. To my surprise, it compiles without error and returns 1. Who knows the reason?
auto lambda = [](int a) -> int{};
cout << lambda << endl;
|
I print out its return value
No. You're printing out the lambda itself. For this case it converts to function pointer, then converts to bool implicitly. For non-null pointer the converted result is true (i.e. 1 in this case. You can use std::boolalpha to get the print result as true or false like cout << boolalpha<< ... |
65,576,911 | 65,577,578 | When 2D array is read by program pointer to array outputs incorrect values, but vector outputs correct values | I'm doing homework where my program needs to read 2D array from file. I have to use pointer to array, that's the point of homework. For testing purposes i also included vector. When matrix is outputed ponter to array outputs incorrect values but vector outputs correct ones. When tested on bigger arrays (100 by 50) poin... | Okey, I have solved it using malloc. Here is the working part of code:
Matrix (std::istream &is)
{
is >> n_ >> m_;
int counter = 0;
mat_ = (int*)malloc((n_* m_)*sizeof(int));
while(counter < (n_ * m_))
{
int x = 0;
is >> x;
mat_[counter] ... |
65,577,126 | 65,577,185 | How can I access unistd write from another scope? | I am trying to use unistd.h write from inside a class where another "write" function has been declared, but I don't know which is the scope resolutor I should use, as unistd is not a library, so unistd::write() won't work.
How can I call it from inside the function?
// this won't compile
#include <stdio.h> // printf
#... | So use the unnamed scope write. The
write(fd, msg, len);
is equal to
this->write(fd, msg, len);
write resolved to Fifo::write inside Fifo function. Do:
::write(fd, msg, len);
to use global scope. like:
#include <cstdio> // use cstdio in C++
extern "C" { // C libraries need to be around extern "C"
#include <fc... |
65,577,450 | 65,577,506 | runtime error: member access within null pointer of type 'TreeNode' | Its a leetcode question in which I have to find out the right side view of the binary-tree;
the code is as follows
ERROR:Line 22: Char 37: runtime error: member access within null pointer of type 'TreeNode' ;
(solution.CPP)
I am unable to find out in which case I am trying to access members of a NULL
class Solution {
p... | I think in this problem the root can be null also, so when the root is null then it will give this error. This is the case I think.
use this
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> v;
if(root == null) return v;
queue<TreeNode*> q;
q.push(root);
while(!q.em... |
65,577,661 | 65,578,878 | Handle the Sliders Control with Edit Box in MFC | I have a problem with appropriate using Slider Control and good understanding of mechanism of UpdatingData of values.
This is a very simple program which should help me get understood of problem.
Take a look on my code:
// TestDialog.cpp : implementation file
//
#include "stdafx.h"
#include "ControlsandVariables.h"
#i... | You have to create two control type variables for CEdit and CSliderCtrl. example:
m_cedit
m_slider
Remarques :
CSliderCtrl send a WM_HSCROLL message
Assure that CEdit Number property is set to True
Add the following functions to the Dlg header class:
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pSc... |
65,578,267 | 65,592,885 | qspinbox64 in QT5.15.2 | I tried to create a qspinbox64 as suggested in
64bit int Spin Box in QT
qspinbox64.h
#define QSPINBOX64_H
#include <QtGui>
#include <QtWidgets>
namespace Ui {
class QSpinBox64;
}
class QSpinBox64Private;
class Q_WIDGETS_EXPORT QSpinBox64 : public QAbstractSpinBox//QSpinBox
{
Q_OBJECT
Q_PROPERTY(int64_t mini... | The culprit is Q_WIDGETS_EXPORT, defined in qtwidgetsglobal.h
# if defined(QT_BUILD_WIDGETS_LIB)
# define Q_WIDGETS_EXPORT Q_DECL_EXPORT
# else
# define Q_WIDGETS_EXPORT Q_DECL_IMPORT
# endif
You should declare QT_BUILD_WIDGETS_LIB in your project by adding this line to the .pro file
DEFINES += QT_BUILD_WIDGE... |
65,578,282 | 65,578,617 | is it possible do a template with 3 different variables without overloading | In class, we learned templates and their usage but we took the example of max3:
template <typename T>
T max3(T x, T y, T z){
if (x>y && x>z) return x;
if (y>x && y>z) return y;
return z;
}
and for 3 different types or two same one different type parameter we did this:
template <typename T1, typename T2, typename... | You can use std::common_type to get a type for the return value.
#include <type_traits>
template <typename T1, typename T2, typename T3>
std::common_type_t<T1, T2, T3> max3(T1 x, T2 y, T3 z){
if (x>y && x>z) return x;
if (y>x && y>z) return y;
return z;
}
If you pass in for example ints and floats you will alwa... |
65,578,682 | 65,578,890 | How to find the lenght of the word in C++? | We have some word, that we should identify the length of. How can I do that?
Example INPUT: "hello" - without quotes;
Example OUTPUT: 5
| If input is contained in a std::string you can find the length as stated by Ravi.
If it's a C string you find the length with
int len = strlen(INPUT);
In C/C++ upper case is normally used for constants so it's better to name the string input, not INPUT.
|
65,579,216 | 65,579,422 | How to accumulate using a Lambda function in C++? | I'm trying to accumulate the numbers in a vector using a multiplication lambda.
What is my error? I get 1 as the result, instead of 24 (= 123*4). My approach is as follows:
std::function<float(float a, int x)> func;
std::vector<int> m{ 1, 2, 3, 4 }; // <-- Multiply: 1*2*3*4 = 24
float accumulation = 1.0f;
func = [&acc... | The idiomatic way would be:
auto accumulation = std::accumulate(m.begin(), m.end(), 1, std::multiplies{});
Your func does a lot of odd stuff and I have no idea what you hope for with accumulation = a * *m.begin()++; or why you leave i unused. This would be more like it:
auto func = [](int lhs, int rhs) { return lhs * ... |
65,579,260 | 65,579,303 | How to convert const uint8_t [] to std::string? | The below code yields an error,
void emitData(const uint8_t data[], size_t size)
{
std::string encodedMessage(data, size);
}
Error,
no instance of constructor "std::__2::basic_string<_CharT, _Traits, _Allocator>::basic_string [with _CharT=char, _Traits=std::__2::char_traits<char>, _Allocator=std::_... | Use the overloaded constructor that takes two iterators as parameters: the beginning and ending iterator values. Simple pointers will do the trick:
std::string encodedMessage{data, data+size};
|
65,579,518 | 65,579,661 | the memory is released when passing to unordered_map by rvalue | I bulit it with -std=c++17 and tried both g++ and clang++ such as clang++ -std=c++17 <file>. It showed the same results.
unordered_map
Pass an unordered_map to rvalue parameter in a function and assign it to another reference. And the memory is not allowed out of the function.
#include <iostream>
#include <string>
#inc... |
Why can the second one work but the first not?
In both cases, behaviour of the program is undefined. So, it "can" or "may" or "is allowed to" appear to work (for whatever you perceive as "woking"). Or to not "work". Or to have any other behaviour.
To clarify, the lifetime of the temporary object to which the referenc... |
65,579,529 | 65,579,707 | How to create dictionary of set size and append to vector value in loop in c++ | I have a video and for each frame, I am dividing into equally sized squares. Each video will have fixed frame dimensions, so the number of squares per video will not change (but different videos with different frame size will change, so the code must be dynamic).
I am trying to loop through each frame, and then loop th... | You don't need to do anything, and you don't need the insert call at all. The following will do everything you need:
for (size_t i = 0; i < list_of_squares.size(); ++i) {
fixedSquaredict[i].push_back(list_of_squares[i]);
}
std::unordered_map::operator[] will default-construct a new value if none with that key exi... |
65,579,562 | 65,591,118 | 'BeginDraw' in conjunction with D2D1 causes an error | I'm trying to clear the background of a window created with CreateWindowEx with the code separated into separate classes, with the use of D2D1. Here's the code.
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
switch (msg) {
case WM_PAINT:
graphics->BeginDraw();
grap... | The problem is the graphics object being used for BeginDraw is a different object to the one which was initialised. It needs to be the same object.
|
65,579,755 | 65,579,878 | How avoid error on not evaluated code C++? | Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?
class A {
//..implementation
int id() { return 1; }
};
class B {
//..implementation
int id() { return 2; }
... |
Can someone give a workaround please?
Read the declaration of someFunction to see what it returns. In the case it doesn't return B, then don't write obj.hasSmth(). Problem solved.
Now, let's change the question a bit. Let's say that you want to make this work without knowing the return type. Perhaps because rather th... |
65,579,821 | 65,580,268 | c++20 infinite ranges/views compiler error | So I watched a video (14:30) about the new c++ 20 features and wanted to try out infinite ranges.
I wrote this code:
#include <iostream>
#include <cmath>
#include <ranges>
using std::cout;
using std::endl;
bool primeCheck(const int&);
int main()
{
auto ints = std::ranges::view::ints(0);
auto primes {
... | Use
auto ints = std::ranges::views::iota(0);
For some reason the video listed it as view::ints and the pdf source as view::iota, both of which are wrong.
|
65,579,911 | 65,579,983 | Inputting char and int in int variable using cin in C++ | I am writing a code to take an integer ID from the user which is later validated from a file.
Now when I don't enter a valid input in the cin it doesn't work (obviously). I have attached a sample code below like this:
std::cout << "Enter ID : " << std::endl;
std::cin >> id;
It's simple as that.
Now if I enter an input... | Welcome to Stack firstly. Try this
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << s... |
65,579,994 | 65,580,117 | Is there a reason to forward declare main in C++ | I'm going through some code from someone who has left the company and there are forward declarations of main() in many of the application source files. I have never seen this in C, which is my main language.
Is there a reason in C++, or C for that matter, to forward declare main()?
| Calling main() directly in C++ is not allowed so there is no real need to forward declare it. A forward declaration allows us to tell the compiler about the existence of an identifier before actually defining the identifier.
In the case of functions, this allows us to tell the compiler about the existence of a function... |
65,580,357 | 65,584,355 | How do I remove repeated words from a string and only show it once with their wordcount | Basically, I have to show each word with their count but repeated words show up again in my program.
How do I remove them by using loops or should I use 2d arrays to store both the word and count?
#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <cstring>
#include <conio.h>
#include <time.h>
using nam... | This post gives an example to save each word from your 'strtok' function into a vector of string. Then, use string.compare to have each word compared with word[0]. Those indexes match with word[0] are marked in an int array 'used'. The count of match equals to the number marks in the array used ('nused'). Those words ... |
65,580,683 | 65,580,773 | Structured Bindings Order and Evaluation | Sorry for the bad title to this question, but I really couldn't think of a better way to title it. My question involves structured bindings and maps, but couldn't really find anything in the standard that could give me a cast-iron guarantee. Consider the following:-
struct Obj {};
std::map<int, Obj> data;
if (const... |
Does the key get checked for its existence BEFORE the evaluation of the make_pair()?
No, that is not how C++ evaluates expressions. std::make_pair(0, Obj()) is fully evaluated, the pair is constructed before it is passed to insert method, or any other callable for that matter. So Obj always exists before the functio... |
65,580,725 | 65,580,895 | Aggregate initialization by-passes private class constructor | I always thought that aggregate initialization was to save coders from writing custom constructors. However, this seems to have "sneaked in" a "security by-pass" for private constructors.
Say I have class A which I only want to be created by class B.
struct A
{
friend class B;
const int i, k;
private:
A () = defa... |
I always thought that aggregate initialization was to save coders from writing custom constructors.
That's something that aggregate initialisation achieves, but defining that as the purpose of aggregate initialisation is overly reductive.
However, this seems to have "sneaked in" a "security by-pass" for private cons... |
65,580,922 | 65,580,988 | How to write a pow() function to handle pow(2, 48) without getting infinity (overflow) in C++? | #include <iostream>
long double abs(long double num){
if (num>=0)
return num;
else
return -num;
}
long double pow(long double val, long double given_exp){
long double res = val;
long double exp = abs(given_exp);
for (; exp > 1; exp--){
... | The line
res *= res;
is wrong. It will calculate res times res in each iteration and make the number very big.
It should be
res *= val;
|
65,580,986 | 65,581,113 | Is using C++20's std::popcount with vector optimization is equivalent to popcnt intristic? | C++20 introduces many new functions such as std::popcount, I use the same functionality using an Intel Intrinsic.
I compiled both options - can be seen in Compiler Explorer code:
Using Intel's AVX2 intrinsic
Using std::popcount and GCC compiler flag "-mavx2"
It looks like the generated assembly code is the same, bes... | Technically No. (But practically, yes). The C++ standard only specifies the behavior of popcount, and not the implementation (Refer to [bit.count]).
Implementors are allowed to do whatever they want to achieve this behavior, including using the popcnt intrinsic, but they could also write a while loop:
int set_bits = 0;... |
65,581,727 | 65,581,795 | Type inferred by C++ auto | How does C++'s auto infer data types in case of for loops - from initialization, or from condition?
long long n;
cin>>n;
for(auto i=1; i<=n; i++)
cout << ((i * i) * ((i * i) - 1)) / 2 - 2 * (2 * (i - 1) * (i - 2)) << "\n";
Here, will i be an integer of long long? My code failed (probably due to overflow - negative... | For the simpler statement
auto i = 1;
it's obvious that i is an int type, since 1 is a literal of type int. That carries over to the declaration inside the for loop. C++ is remarkably self-consistent.
The type of the stopping conditional i <= n is a bool so that wouldn't be
much use to you.
If you want the index type ... |
65,581,825 | 65,581,948 | How do I get the mirror of the first element of an array? | I need to input numbers into an array, get the first number, mirror it, and then see if any other numbers in said array are the same as the mirror.
Example: 4 numbers, 123 321 111 and 200; the mirror of 123 is 321, so it should tell me "Yes", since there is 1 more element in the array that is the same as the mirror.
#i... | There are two major problems in your code. First, you are attempting to allocate your v array before you know the user's input value of n; this can be fixed by moving the declaration/allocation of v to after the cin >> n; line.
Second, you never give the mirror variable an initial (zero) value, so it could start out as... |
65,582,097 | 65,582,930 | Why do we use char* as a buffer, why not a string in boost::asio? | Recently I have been reading a book about network programming with boost::asio, and from what I have understood, buffer is like any other memory space in address space of the program and we assign that to the socket so that we can do I/O operations.
The first thing I don't understand is, why do we need a separate thing... |
why not just write the content in a string, and then when we receive it put in the string.
Because Boost ASIO is a library for binary IO; not for textual IO. And std::string is for representing text. Technically, you could use a std::string as a buffer for binary data, but doing so would be unconventional and confusi... |
65,582,533 | 65,614,297 | Obtain Kerberos ticket in C/C++ | Does anyone know how to get a ticket from the Key Distribution Center (KDC) using the MIT krb5 API in C/C++?
I already have a working Java Client which uses GSS-API to obtain a ticket from the KDC (using a local TGT) and forwards it to a Java Server.
The server accepts the security context using the following logic:
pr... | After some further reading it appears that my approach was not correct for my use case. I should have used GSS-API directly.
The following snippet works:
gss_name_t get_spn(char *spn)
{
OM_uint32 maj_stat;
OM_uint32 min_stat;
gss_buffer_desc name_buf = GSS_C_EMPTY_BUFFER;
gss_name_t spn_gss_name = GSS_C... |
65,582,786 | 65,583,354 | "<<" Operator overloading error when defined outside main file | I tried to overload the << operator and wanted to use it in the main function. However, I get the following compiler error:
main.cpp:14:19: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const Point’)
std::cout << point;
~~~~~~~~~~^~~~~~~~
Inter... | main() has no idea about your operator<< because you did not declare it in data.hpp in a scope where main() can find it. It needs to be declared as a free-floating function, not as a friend of the Data class, eg:
#ifndef DATA_H
#define DATA_H
#include <ostream>
#include <vector>
struct Point {
double x;
doub... |
65,582,789 | 65,583,064 | I am getting bad_alloc error in c++ program | I wrote a c++ program but I am getting an error.
I am not understanding the reason why I am getting the error.
Please help me with how to fix this.
This is my code :
#include <bits/stdc++.h>
#define endl "\n"
#define int long long
using namespace std;
void solve() {
int n, x;
cin >> n >> x;
cout << n << x;... | The problem is in the treatment of the variable x. Don't ask me what the solution is but I can describe the problem.
while (x--) {
vect.push_back(vect[i] / 2);
l++;
}
The first time this loop runs x equals two. So two items are added to the vector and x takes the value -1.
The n... |
65,582,803 | 65,584,055 | How to fix not printing any character and just count vowels and characters and read every character in a file | I just want to read every character in a file where I put characters from A TO Z but the program prints A every time and count vowels 4 and character 25 but expectation was to printing vowels 5 and characters 26 how to fix this program fixing from last 4 hours but nothing progress?
Code:
#include<iostream>
#include<fst... | You have some really minor erros in the code, which I fixed for you.
Additionally, I added a check, if the file could be opened or not. That is the problem in most cases.
Please see below:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
int count = 0, vowel_count = 0;
s... |
65,583,576 | 65,583,783 | c++20 concept check for function being declared const | I want to test out the new concepts feature in c++20 and I was wondering if I can create a concept that checks for the existence of a function that is declared const.
I want the check to fail if the function exists with the right type but isn't const. I couldn't find anything relevant here: https://en.cppreference.com/... | You can make the parameter const:
template <typename T>
concept hasToString = requires (T const val) {
{ val.toString() } -> std::same_as<std::string>;
};
Concepts check usage patterns, and so if what you want to check is calling a member function on a const object, you need to construct that scenario.
Note that ... |
65,583,652 | 65,584,169 | Problems with returning references to local variables...? | There is a complaint that the following function doesn't work because it returns "pointers/iterators to local variables". Is this complaint correct? I can't see this problem...
const Range dummy::foo() const
{
std::vector<Handle> _handles;
_handles.reserve(_collection.size());
for (const auto& pair: _colle... |
Is this complaint correct?
Yes it is. _handles is an automatic variable, and you return a range referring to it. Ranges are basically abstractions over pairs of iterator + sentinel. The returned range will be invalid outside the function.
And how can I solve this
A correct implementation would be to return a transf... |
65,584,153 | 65,584,297 | Why does my code return 0 after entering in username and password for login | So now whenever i press A or a, it shows the login function however when i type in the correct username or password it returns 0 and i am very lost as to why it happens. It works in python but in c++ i cant get it to work. This is my code... sorry if the code is very hard to understand.
// login system with login and r... | You need to add a newline to separate your username and password like this:
new_file << username << '\n';
new_file << password;
instead of:
new_file << username; // it will concatenate username and password without
new_file << password; // any whitespace or newline in the file
Also, you need to accept the Confirm p... |
65,584,333 | 65,589,202 | Why can't I use two .h file? | When I do #include "George.h" above #include "Anna.h" and then using namespace Anna;, it gives me an error 'expected namespace name' and 'unknown type Human, you mean Anna::Human?', but if I type #include "Anna.h" above #include "George.h", everything is fine.
So I guess my problem is that I can't include two header fi... | In Anna, change HUMAN_H to ANNA_HUMAN_H and in George change HUMAN_H to GEORGE_HUMAN_H
I haven't tested this but from the look of the comments (and my own reasoning) it is what's wrong
|
65,584,466 | 65,584,621 | C++ Initialize struct with mutex field | I'm trying to figure out how to initialize a struct with a mutex field, since the mutex type is not copyable or movable in C++.
I have the struct:
typedef struct sample {
int field1;
std::mutex mtx;
} sample_t;
I'm trying to initialize it in the following way, but I keep getting error: use of deleted function. I'm... | Mutex is not copyable and not moveable. But you don't need either of these operatons, you only need to create sample_t object - std::mutex inside will be initilized by the compiler.
sample_t new_sample;
new_sample.mtx.lock();
new_sample.field1 = 2;
new_sample.mtx.unlock();
Or, if you really need a pointer for some re... |
65,584,740 | 65,584,949 | How do I find the number with the most divisors in an array? | I have to input numbers into an array and at the end get the number that has the most divisors, or if there are more numbers with the same amount, print out the first one.
Example: 4 numbers, 6 12 48 108. 108 has the most divisors, so this one needs to show up. if there were numbers after 108 with the same amount of di... | Here is the algorithm of what you have to do:
Count the number of divisors of the first element in array. Save this value in mostDivisors. Set number_with_most_divisors as the first element in the array.
Start from the second element in array (position 1) and for each element, count how many divisors it has, save it ... |
65,584,904 | 65,585,094 | Warning C4267 in Visual Studio: 'argument': conversion from 'size_t' to 'const _Elem', possible loss of data | I am getting the warning from this function:
std::pair<size_t, size_t> GetSection(const string& s1, const string& s2) {
size_t top_section = s1.find(s2 + ":");
size_t bottom_section = s1.find(s1.length() - top_section);
return std::make_pair(top_section, bottom_section);
}
I don't understand w... | The problem is in this function call:
s1.find(s1.length() - top_section);
The argument s1.length() - top_section is a number of type size_t, but the find method is supposed to take in a string or character to search for.
(Specifically, because C++ always assumes you mean what you say, it's trying to convert the size_t... |
65,585,332 | 65,585,366 | copy precedent value 2d dynamic array | Hi I want to create a 2d growing dynamic array with use of char. The problem is that my function put all word in the same row. The dynamic allocation is not good but I don't know how to correct this.
void display(char** data, int length)
{
for (int i = 0; i < length; i++)
for (int j = 0; j < data[i][j] ... | I'm pretty sure that instead of
if (length = 1)
you meant to write
if (length == 1)
In C++ = means assignment and == means equality.
Seems your code has other bugs though. You never grow the size of data. Do it the easy way and use std::vector<std::string>
#include <vector>
#include <string>
int main()
{
std::ve... |
65,585,667 | 65,586,490 | Can I read a given variable of a windows application (c++) with python? | I have a c++ application. I need to read a variable of this. I have a source code as well, so I know the name of the variable. Can I read this variable of the program or I have to add something to source code?
| The answer, as they wrote, in this form is not possible.
A suggested solution in an earlier post:
Communication between C++ and Python
|
65,585,952 | 65,586,405 | Seperating this class into a header and cpp file | I have difficulties with separating this class into a header and .cpp file because c++ is relatively new for me. This class is an example my teacher programmed with us in class. It isn't homework, but it will help me understand my homework.
#include <iostream>
#include <AstUtils.h>
#include <vector>
#include <cassert>
... | You don't necessarily need to move all implementations into the .cpp file. When it is sufficiently short and doesn't make use of any object external to the class, you could keep the implementation in the .hpp file as an inline function. This is especially true for members like getPosX or getPosY. Inlining a member like... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.