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 |
|---|---|---|---|---|
64,819,797 | 65,391,430 | How to print "The key(element) is not present in your array" when I don't enter a key present in my array when asked for by the computer in my code | Let's say I enter {1,3,3,5} as my array and I input 6 when asked to enter the key whose index I want to know. How do I edit my code to print that "the key entered is not in your array"?
My code is given below:
#include <iostream>
using namespace std;
void linearsearch(int arr[], int n, int key) {
int i;
for (i =... | // You can use a boolean control variable in the void function and when you find the number you can set its value to true and insert an if statement at the end of the loop to check the value of the bool variable, if the, if statement in the loop wasn't executed, meant that the number was not found and the value of the ... |
64,819,837 | 64,820,473 | C++ code after a for loop doesn't execute | It's a bit weird to me that the code after a for loop doesn't execute but the compiler doesn't raise any warning:
#include <iostream>
#include <iterator>
bool isVowel(char ch)
{
char vowels[]{"aeiouAEIOU"};
char *p = std::find(std::begin(vowels), std::end(vowels), ch);
if (p != std::end(vowels))
... | Try to use the following:
int length { std::size(name) - 1 };
|
64,820,215 | 64,827,120 | compute number of seconds in cpp week to current datetime, | I am trying to find out the number of seconds of week to date and i tried following way please correct me if i am wrong:
//tp is time precision and dp is day precision.
auto tp = floor<seconds>(system_clock::now());
auto dp = floor<days>(tp);
dp -= weekday{dp} - Monday;
int WeekSeconds=tp - dp;
and er... | Your code is almost correct, but a little ahead of its time. :-)
You are using new C++20 facilities that are not yet shipping. But there exists a free, open-source preview of the new C++20 chrono library which works with C++11/14/17.
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using ... |
64,820,291 | 64,826,807 | Are there any real life situations where declaring all floating point literals as double causes real problems in C++? | Meaning, in a "normal" situation where the performance loss of type promotion is irrelevant, where nobody checks for equality on a float and where nobody declares anything funny like
void f(float x) {/*do something*/};
void f(double x) {/*do something completely different*/};
and so on.
I am aware that the general que... | I don't have a good "real-life" example at hand. Instead I want to try to convince you with a hopefully simple example.
Lets assume all function with overloads for float and double do "the right thing":
void f(float x) {/*do something*/};
void f(double x) {/*do the same thing*/};
Moreover, when only one of the overloa... |
64,820,375 | 64,866,047 | 24 Bit Unsigned Integer | I start working with HART (Highway Addressable Remote Transducer) Protocol and I found something, let's say different and I try to understand it, more precisely the uint24. I understand that this structure uses an UInt32 internally for storage and most other common expected integer functionality, so using a 24-bit inte... | Short answer
left << shifting is a padding of significant bits with zeros for future conjunction into single value;
right >> shifting is part of extracting of value's segment into smaller data type (goes after applying mask);
Abstract
Shift & sum is the way to pack/unpack values when reading/writing frame is less of ... |
64,820,455 | 64,820,580 | Makefile, Why is it recompiled every time? | My directory structure is: objFile/(cacheOp.o,fileOp.o) ,Header/(cacheOp.h,fileOp.h) ,Bodyer/(cacheOp.cpp,fileOp.cpp)
I wrote a Makefile document:
cc=g++
CXXFLAGS=-g -o0
libObjs = objFile/cacheOp.o objFile/fileOp.o
all : cacheOpObj testFunc.cpp fileOpObj
$(cc) testFunc.cpp objFile/cacheOp.o -o test $(CXXFLAGS)
ca... | You're lying to Make, look at this rule/recipe:
cacheOpObj : Header/cacheOp.h Bodyer/cacheOp.cpp
$(cc) -c Bodyer/cacheOp.cpp -o objFile/cacheOp.o $(CXXFLAGS)
This means "if cacheOpObj is missing or older than Header/cacheOp.h or Bodyer/cacheOp.cpp, this command will generate it". Except it doesn't, it creates a f... |
64,820,605 | 64,820,738 | Why can't I define a function within the main function in C++? | This program works fine if I implement function prototyping and define this after the main function.
Why is it like that?
#include <iostream>
using namespace std;
typedef unsigned short UShort;
main()
{
UShort length, breadth, TotalArea;
cout<<"Enter length and breadth";
cin>>length>>breadth;
UShort ... |
Why is it like that?
Because the standard says so.
And you don't need it, because you can define a type inside a function:
#include <iostream>
using namespace std;
typedef unsigned short UShort;
int main()
{
UShort length, breadth, TotalArea;
cout<<"Enter length and breadth";
cin>>length>>breadth;
... |
64,821,115 | 64,823,496 | How to find dynamically created QLineEdit when pressing QPushButton | I am trying to save the value is entered in a QLineEdit.
I am creating the layout using this function:
QHBoxLayout* MainWindow::CreateTbSettingLayout(QString title, QString desc, QString slot, QString unit){
QHBoxLayout * setting = new QHBoxLayout;
QLabel *titleLabel = new QLabel(title);
titleLabel->setMax... | You can use a lambda function to solve this.
QHBoxLayout * Gui::CreateTbSettingLayout(QString title, QString desc, QString unit) {
QHBoxLayout * setting = new QHBoxLayout;
QLabel *titleLabel = new QLabel(title);
titleLabel->setMaximumWidth(100);
QLineEdit *settingTb = new QLineEdit;
settingTb->setM... |
64,821,121 | 66,193,599 | Error in mocking for embedded unit testing "Address of overloaded function does not match required type 'void()' | I am working on an Embedded C project for which I am currently writing unit tests. I am using the fff mocking framework, which essentially creates fake function calls which should overload hardware specific calls.
When I create a 'fake function' I get an error stating that
Address of overloaded function does not match... | Since your error is related to overloading it means you are trying to use multiple definitions for the same function.
I would suggest you make sure that the original definitions of the problematic functions are not redefined by these mock declarations (which are also definitions).
So for example, if you were mocking a ... |
64,821,485 | 64,822,593 | Conversion from english to morse,and then to binary- code doesn't display anything | I have to translate online some sentences ( the commented ones), I am trying now with simpler one. I have to translate in morse and then in specific a binary code, I don't know why the code doesn't display anything! /here the url on c++ shell
(I have to do it online because I have to do some tasks with this binary code... | Overall, I think your approach and logic is flawed. I do not know what your code is trying to do so I can not explain where it is wrong, but I rewrote what I assumed you were trying to do.
As for advice for better code.
These are all my personal preference:
Get rid of using namespace std. There are lots of reasons you... |
64,821,702 | 64,821,749 | C++ understanding pointer with copy constructor | I have a simple LinkedList class with basic operations(add/delete etc.) and a copy constructor:
LinkedList::LinkedList(const LinkedList& other) {
data_ = other.data_;
if (other.next_ == nullptr) next_ = nullptr;
else next_ = new LinkedList(*other.next_);
}
I think the following behaviour is expected but I'... | list1 was created in automatic storage ("the stack"), so you must not call delete on its address. Doing so results in Undefined Behaviour, which means that anything can happen, including corruption of list2 or an outright crash of the program.
To test that your copy constructor is working, you could create both lists i... |
64,821,949 | 64,823,964 | Strange data from Wheatstone bridge via ADC and Arduino | I'm using a CS1237 ADC with an Arduino Mega to look at data from a Wheatstone bridge load cell.
I didn't build the load cell or wire it to the ADC, it's in a store scale and I just lifted the clock pins of the chip that was controlling the ADC and have been bit-banging the ADC clock from the Arduino.
The code I'm using... | The numbers on the left have 18 or 19 zeros; that's way more than fits in 24 bits, or in a long.
In the new code, the ADC value is printed twice, once in decimal, once in binary, which could well be throwing off the serial plotter.
|
64,822,014 | 64,822,781 | How to run compare_exchange_weak on an std::atomic<bool>? | I've tried running
std::atomic<bool> set(false);
Then later on in a function I try using:
Process::signalsDone.compare_exchange_weak(false, true, std::memory_order_release, std::memory_order_relaxed);
Why does this, when compiling, cause an error message?
error C2664: 'bool std::atomic<bool>::compare_exchange_wea... | The first argument to compare_exchange_weak is a T&.
You can't bind a literal like false to a T&; you've never been able to do that.
Instead, make a variable of type bool that can be passed to the function by reference. The variable's value will be altered to the actual value of the atomic_bool if the comparison fails.... |
64,822,112 | 64,822,251 | Require shared library with dependencies in cmake | I'm new to cmake, so I'm having trouble figuring out how to model the following:
My program requires a third party library that I only have access to in the form of headers and *.so files. It also ships many of its dependencies as *.so files. How do I make sure that everything compiles and links correctly, ideally in t... | You can use IMPORTED libraries:
add_library(externalLib SHARED IMPORTED GLOBAL)
set_property(TARGET externalLib PROPERTY IMPORTED_LOCATION "/path/to/lib.so")
target_include_directories(externalLib INTERFACE "/path/to/headers")
target_link_directories(externalLib INTERFACE /path/to/libs)
target_link_libraries(externalLi... |
64,822,294 | 64,822,502 | Implementation of the decorator class in C++ using a member reference to the decorated object not working as expected | I am trying to learn the decorator pattern implementation in C++. I have tried implementing the decorator class using both a reference and pointer to the decorated object as a member (composition). A single invocation of decorator works expectedly. However, when I try chaining together multiple decorator instances, it ... | You see the problem if you delete the copy constructors:
class Flower
{
public:
Flower() {}
Flower(const Flower&) = delete;
virtual string str() = 0;
};
error: use of deleted function ‘BlueRose::BlueRose(const BlueRose&)’
BlueRose blue_blue_rose{blue_rose};
BlueRose has a constructor taking Flower& a... |
64,823,073 | 64,823,194 | Universal Reference and constness | This C++ code doesn't compile, you get an error "candidate function template not viable: 1st argument ('const int32_t' (aka 'const int')) would lose const qualifier"
I know I can solve this by adding an overload for Func(const T& value), but I'm curious to learn why this doesn't compile?
template <typename T>
void Fun... | When you make this call:
Func<int32_t>(i.Id);
you are specifying the template arguments. This means the T&& in Func is not considered a forwarding reference at all. Instead, it's just an rvalue-reference, which is int32_t&&. As the compiler says, binding int32_t && to a int32_t const & would discard the const qualifie... |
64,823,154 | 64,825,660 | Proper method for opening files at a particular offset with Win32 api using c++ | Problem: Unsure of how to properly load data from a file starting at a given offset. The little snippet is a Win32 api wrapper for opening an xml file. The first method using SetFilePointer does not work. The issue being that it does not throw any warnings that it doesn't work either. The seekStatus doesn't return INVA... |
Why Doesn't SetFilePointer appear to work?
because you specify offset by setting the Offset and OffsetHigh members of the OVERLAPPED structure. in this case it and used instead FILE_OBJECT::CurrentByteOffset . all what doing SetFilePointer - set CurrentByteOffset in FILE_OBJECT
Is it possible to get the first method... |
64,823,191 | 64,835,397 | In Fast-DDS, Set IP From Localhost to Certain LAN | I am newbie in DDS and C++, and I used fastrtps to run dds code(dynamic example) in a raspberry(ubuntu server), which was successful. However, when I move subscribe part to another raspberry, two raspberries cannot find each other.
So far, I guess there are two reason:
My cellphone(android) has firewall. Should I chan... | Finally, I turn off firewall(command below) on both raspberries, not cellphone.
sudo ufw disable
Thanks every one trying to help me.
|
64,823,299 | 64,823,546 | Why doesn't ADL work with functions defined outside of a namespace? | I know that my compiler in the example below will execute the function First::fun(), because of Argument-Dependent name Lookup (ADL)/Koenig lookup and in order to execute Second::fun() this needs to be explicitly called in the main function.
#include <iostream>
using namespace std;
namespace First
{
enum Enum
... |
Why doesn't the compiler prefer the global fun() in the ambiguous call?
The global fun is found by unqualified name lookup, and First::fun is found by ADL, both are put in overload set and overload resolution can't select one.
These function names are looked up in the namespaces of their arguments in addition to the... |
64,823,409 | 64,823,567 | For loop only executes once. Other posts didn't help me | I'm trying to have the program out put either a color or a number at random.
Any help would be greatly appreciated.
Thank You in advance for not being evil.
I originally wasn't using a function so I created one and that didn't help. I also tried changing i from 0 to one. I thought a simple for loop would be easy
#incl... | You probably want this:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
const string color[6] = { "red", "blue", "green", "orange", "yellow", "brown" };
const int distance[5] = { 7,25,20,10,15 };
void random_function()
{
// you must assign your variables each time
int rand_num = ran... |
64,823,986 | 64,824,103 | How to convert string to integer using stoi()? |
If there are more than 3 letters together (i.e. next to each other) from the given Alphabet Set: {a,g,w,k,l}, then your string is “BAD”. If a number is repeated more than three times, then your string is “BAD”. Print "1” if string is GOOD, else print "0".
For the first condition, I am able to do it. But for the secon... | You can convert a single ASCII character representing a digit like this:
int num = s[i] - '0';
That works because inside the string, each character is represented by an ASCII code - they're listed in the table below. The character '0' has ASCII code 48 decimal and other digits increment from there. When you do s[i] ... |
64,824,028 | 64,824,412 | C++ range based for loop over vector of pointers. How to capture elements by const reference? | How can I capture the elements by const reference in a range-based for loop over a vector containing pointers?
#include <iostream>
#include <memory>
#include <vector>
class Foo {
public:
Foo(int a) : a{a} {}
int value() const { return a; }
private:
int a;
};
int main() {
std::unique_ptr<Foo> f1 = std:... | The vector contains pointers, so that's what you get. If you want something else you need to loop over a different object.
C++20 ranges offers a way to do that. It wouldn't be very hard to roll your own variant.
#include <iostream>
#include <memory>
#include <vector>
#include <ranges>
class Foo {
public:
Foo(int a... |
64,824,492 | 64,824,779 | How to call a renamed symbol in an external object file? | I am trying to fuzz a particular piece of code using LLVM libFuzzer that only exposes its main() function externally. I have access to the source of the target code, but cannot change it.
If I try to directly include the object file, it conflicts with the main definition provided by -fsanitize=fuzzer. I thought I mig... | You are not accounting for C++'s name mangling. The symbol for stub_main is likely a string containing main as well as some obfuscated info about arguments, type of function, and return type. In my platform it's __Z9stub_mainiPPc. The symbol for main would likely just be main or main_.
You can try looking how main and ... |
64,824,605 | 64,824,663 | Why am I getting an error in my main program that says: No instance of constructor matches argument list? | I am getting an error in my main program that is not recognizing my constructor. What am I doing wrong?
Passing of argument to constructor in Main function:
Vehicle aVehicle("VVV-111", 2010);
Constructor Defintion:
Vehicle::Vehicle(char p[], int y) {
strcpy(this->plateNum, p);
this->year = y;
this->Address[6... | You're passing in a string literal, which is of type const char[8] (8 for the size of the string literal), to a function receiving char [], which is equivalent to receiving a char * (because C arrays decay to pointers across function boundaries).
If you make the constructor receive a const char * (or const char[]), it ... |
64,824,739 | 64,825,387 | How to create a constructor of linked list for iterator class in c++? | When I try to run this code I get this error :
constructor for 'Linkedlist' must explicitly initialize the member
'point' which does not have a default constructor
Linkedlist::Linkedlist()
class Node {
public:
Node* next;
Node* prev;
Elem elem;
friend class Linkedlist;
Node... | There are a couple of things you could do. You could declare it as a pointer
class Linkedlist { //Missing a c on your class declaration
private:
Node *head;
Node *tail;
int N;
//Iterator point; (You have this declared twice)
public:
Iterator *point;
Linkedlist()... |
64,824,752 | 64,825,848 | Issues with RGB led and Servomotors | I'm on my first Arduino project... On this project, I use an RGB led and 2 Servomotors...
First off all, following OOP, I create a class to control my RGB led...
class StatusLED {
private:
int pinRed;
int pinGreen;
int pinBlue;
public:
StatusLED(int pinRed, int pinGreen, int pinBlue);
void RGB(... | Depending on the version of your arduino, servo.attach only works on Pin 9 and Pin 10, which conflicts with your RGB pins. See https://www.arduino.cc/en/Reference/ServoAttach
|
64,824,788 | 64,827,597 | Cmake building two projects | I want to build two projects using cmake (A library and sandbox application using that library).
I'm currently having the following folder structure:
-- yanthra_engine
|
-- CMakeLists.txt
-- lib
-- ...
-- sandbox
|
-- CMakeLists.txt
-- out
-- ...
The yantra_engine builds a library where as sandbox builds... | You should keep seperate CMakeLists.txt files. It's good practice to use one CMakeLists.txt file per unrelated target. (Unrelated in the sense of not being different builds of the same library, e.g. one shared one static.)
Whether to add both targets to the same project is basically up to you. If the library is properl... |
64,824,836 | 64,825,236 | OpenMesh: fast search of common neighbor vertices | I have a function which finds the common neighbors of two vertices v1 and v2, i.e. those vertices that are connected to both v1 and v2:
std::vector<MyMesh::VertexHandle> find_common_neighbors(MyMesh & mesh, MyMesh::VertexHandle & v1, MyMesh::VertexHandle & v2){
std::vector<MyMesh::VertexHandle> common_neighbors;
... | I'm not an expert on OpenMesh proper, but it looks like you are using a rather efficient Circulator to find these pairs of vertices.
The only obvious problem with your function is the fact you are allocating and returning the std::vector object.
The declaration
std::vector<MyMesh::VertexHandle> common_neighbors;
define... |
64,824,924 | 65,013,000 | C++, Android NDK: How to save my raw audio data to file properly and load it again | I'm working on an Android app that plays back audio. To minimize latency I'm using C++ via JNI to play the app using the C++ library oboe.
Currently, before playback, the app has to decode the given file (e.g. an mp3), and then plays back the decoded raw audio stream. This leads to waiting time before playback starts i... | I figured out how to do it thanks to @Michael's comments.
This is how I save my data now:
bool Converter::doConversion(const std::string& fullPath, const std::string& name) {
// here I'm setting up the extractor and necessary inputs. Omitted since not relevant
// this is where the decoder is called to decode ... |
64,826,188 | 64,826,322 | Mysterious memory leaks in preloader-based lock tracing tool | I'm working on a lock tracing tool designed to be attached to Pthreads-based applications using LD_PRELOAD, and I've encountered a weird issue. When a test application is run under valgrind with my tracer attached, it reports several memory leaks originating in libpthread's pthread_cond_signal()/wait() (my tool shadow... | I bet you that if you:
Change the name of your function to something else than pthread_cond_wait, say pthread_cond_wait_my,
Create a small test snippet that invokes the _my variant,
Create a minimal shared library that has a dummy implementation of pthread_cond_wait_my, and link the snippet with it (just as it would... |
64,826,336 | 64,826,770 | Sum the positive elements of an array using recursion | I'm learning recursion and trying to calculate the sum of the positive elements of an array but I don't know how to do it. Can anyone help me?
#include <iostream>
using namespace std;
int sum (int arr[],int n)
{
if(n==-1)
return 0;
/*else if(arr[n]<0)
return arr[n]+sum(arr,n+1) ;*/
else
re... | Some suggestions:
in C++ (specially starting from C++11) avoid, when possible, old C-style arrays; use std::vector, std::deque, std::array (starting from C++11) instead;
When possible, write generic code using templates; in this case, avoid a sum() function that works only with C-style arrays but write a template fun... |
64,826,453 | 64,826,891 | Setting a pointer to a new buffer of length n | I am trying to recreate a dumbed-down version of the STL string class. I am trying to implement a constructor that will take a c-string as an argument.
inline String::String(const char* s)
{
buffer = get_new_buffer(s);
size = strlen(s);
}
To set the pointer, I wrote a function, get_new_buffer(char* n) const to... | There are several problems with this code:
get_new_buffer() is declared to return a char* pointer, but is allocating a char*[] array, which decays to a char** pointer. That is the mismatch the compiler is complaining about. Drop the extra * on the array's element type. You want an array of chars, not an array of po... |
64,826,757 | 64,826,939 | No matching function for call to "..." Compiler errors involving templated functions | I am working on a project where I make various algorithms such as counting and sorting for integers and then I am turning them into template functions so they can be used with things such as vectors and lists.
For example, one templated function looks like this:
template<typename Iter>
int count(Iter* first, Iter* limi... | Yes, the * in your parameters is the problem. An iterator is not a pointer, but is designed to mimic a pointer (on the other hand, a pointer can be an valid iterator). Do not pass around iterators by pointer, pass them around by value instead, eg:
template<typename Iter>
int count(Iter first, Iter limit, int value)
{... |
64,827,060 | 64,827,137 | Efficient way to generate sorted vector of pairs in C++ | I am attempting to generate a sorted vector std::vector<std::pair<int,int>> from a set of integer. By iterating the integer set, the value of the integer will be set to the first value of the pair and the second value of the pair will be computed by another function. All pairs should be sorted according to the second v... | Generating the whole vector and sorting as the final step is almost certainly the way to go. Assuming the generated values are semi-random, attempting to insert to maintain sorted order would involve a continuously growing O(n) insertion cost (the O(log n) binary search cost is less of a problem in theory, but given th... |
64,827,356 | 64,827,749 | How to create a string from two vectors of strings in C++? | I have two separate vectors of strings:
std::vector<std::string> vectorA;
vectorA.push_back("a1");
vectorA.push_back("\na2");
std::vector<std::string> vectorB;
vectorB.push_back("b1");
vectorB.push_back("b2");
I want to create an std::string vectorOutput which shows the following:
a1 b1
a2 b2
Now, the elements in ve... | With the range-v3 library, you could write it like this:
namespace rs = ranges;
namespace rv = ranges::views;
auto outputVector = rv::transform(vectorA, vectorB, std::plus{})
| rv::cache1
| rv::join
| rs::to<std::string>;
This has no loops, and is quite rea... |
64,827,533 | 64,827,798 | How to avoid using new operator in C++? | I have a C++ program that creates Huffman codes for all characters in file. It works good, but I want to create nodes without using new operator because I know that you shouldn't use it. I tried using a vector global variable for saving nodes but that doesn't work.
std::vector<Node> nodes;
Node* create_node(unsigned c... | The general answer is of course to use smart pointers, like std::shared_ptr<Node>.
That said, using regular pointers is not that bad, especially if you hide all pointers from the outside. I wouldn't agree with "you shouldn't use new", more like "you should realize that you have to make sure not to create a memory leak ... |
64,827,630 | 64,827,735 | sorting by smallest digit using selection sort | my task is to sort an array by the smallest digit of a number using selection sort. for example: 61 < 35, because 1 < 3. in case of coincidence of digits, i have to print the smallest of 2.
so this is my code:
#include <iostream>
#include <time.h>
using namespace std;
int smallestOfTwo(int a, int b) {
if (a ... | 26 and 27 both have smallest digit 2, so they are equivalent and can be in any order in the result. To preserve original order, you can try looking up algorithms for "stable sort." To fall back on second smallest digit, third smallest digit, etc. you can count each digit and compare.
struct digit_counts {
int count... |
64,827,776 | 64,837,237 | C++: dll not working on Visual Studio 2017 but works with g++ | I am having this issue with more complex code, this is naturally a simplified example.
dll does not work with VS but does work with g++,
I have this code,
#include <stdio.h>
extern "C" __declspec(dllexport) void func(int a)
{
printf("a: %d\n", a);
}
This is the only file in my VS project. I compile it and V... | The error "not a valid Win32 application" often indicates a bitness mismatch where a 64-bit process attempts to load a 32-bit library, or the other way around. Given the posted screenshot shows the DLL being 32-bit (platform = x86) chances are the python module is 64-bit.
The "Win32 application" part of the error messa... |
64,828,198 | 64,828,225 | Array type int[] is not assignable | I am implementing an ADT Stack using an array. I want to doubling the size of the array when the stack is full.
const int MAX_SIZE = 6 // max size of array stack
template<class ItemType>
class ArrayStack: public StackInterface<ItemType>{
private:
ItemType items[MAX_SIZE]; // Array of stack items
int top; // in... | ItemType items[MAX_SIZE]; is a fixed array. You can't resize it, you can't reallocate it, and you certainly can't assign an ItemType* pointer to it.
For what you are attempting to do, items needs to be an ItemType* pointer instead of an ItemType[] array:
template<class ItemType>
class ArrayStack: public StackInterface... |
64,828,276 | 64,828,385 | Difference between these 2 initialization methods | Suppose I have a class here:
class Test
{
Test(int x, const char* y)
{
// Do something
}
}
and I wanted to initialize it. I have 2 methods:
Test test(100, "hello world!");
and
Test test = Test(100, "hello 2nd method!");
What are the differences between the 2 and which one is better ( as in faster... | It depends.
In old compilers, the statement Test test = Test(100, "hello 2nd method!"); would first create a temporary Test object using your converting constructor, and would then use the copy constructor to create the test object to make a copy of that temporary.
In modern compilers, there is no difference whatsoever... |
64,828,459 | 64,828,574 | Points have no color, even with a shader | I'm trying to set a different color to each point in an OpenGL application, for that i have constructed 2 float std::vectors called, vertex_position_data and vertex_color_data, respectively representing x,y,z and r,g,b.
coordinates: 0.9996775489540122 0.8108964808511072 0.9943463478468979
rgb: 0.317364987841259 0.62061... | You have to bind the ARRAY_BUFFER, before glVertexAttribPointer is called. Furthermore the 1st argument of glEnableVertexArrayAttrib is the Vertex Array Object rather than the Vertex Buffer Object:
glEnableVertexArrayAttrib(vertexArrayID, 0);
glBindBuffer(GL_ARRAY_BUFFER, vertex_bufferID);
glVertexAttribPointer(0, 3, G... |
64,828,795 | 64,945,373 | Qt QColorDialog - Escape Key not "eaten" (i.e. not remove from the event queue) | In my application, I have a QTableWidget with one column where the user may click to select a color. It work correctly with the following restriction: when the user type the Escape Key, the dialog is cancelled and close as expected, but the key event remains in the queue. This lead to a second effect of this key event... | Here is the solution I implemented. Not really beautiful but the best I was able to do so far and works as required. The definition is a bit verbose but the usage is really convenient.
First, a stack based object (Android and MacOS not yet implemented, only Windows):
// ==============================
// Used to disable... |
64,829,651 | 64,829,669 | How to rewrite this function into a pointer in c++? | void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
In my code all I did was add asteriks before the variables a, b in both the argument and in the body of the code. My teacher said it was wrong so now I don't get it.
| void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
the way you would call your original would be:
int one = 1;
int two = 2;
swap(one, two); // references
the modified function like
swap(&one, &two); // pointers
|
64,829,717 | 64,829,870 | How do I declare a working variable for minesweeper C++ program? | I am currently working on solving a minesweeper C++ program, and I am unable to receive the correct output when the program finishes. I know it's a logic error, most likely from the "currentCell" variable, but I cannot figure out how to make it work. My output ends up like this: ________________________________________... | Ok, you have at least two problems.
The biggest one:
You are setting the variable currentCell, but what you actually mean is to set a cell in the board!
Change all the assignments and references to this:
board[row][column]
Second problem:
The print function does not print the line feed. Just add cout << endl; to the e... |
64,829,850 | 64,830,071 | Visual Studio 2019 Cross Platform debugging doesn't work on remote system when C++ shared items project is used | Without C++ Shared project everything works fine.
Steps to reproduce:
create a blank solution
add a new C++ Shared Items project called SharedProject
add a new C++ Linux project MainProject
reference the SharedProject to the MainProject
add main.cpp (#include int main(){ std::cout << "Hello World" << std::endl; r... | solution:
add Remote post-build event with the following cmd
mv ~/projects/MainProject/MainProject/* ~/projects/MainProject/
|
64,830,088 | 64,848,391 | Exception on push_back to vector in method of class exposed to DLL | I've created a DLL library, then linked it in a different project, compiled with different VS.
There's just a simple class exposed to DLL with __declspec(dllexport) like this:
class TFLIBRARY_API MyClass
One of the fields of this class is a std::vector<std::string>, and part of the initialization of this class is fill... | That was a general failure of memory management in my code.
|
64,830,212 | 64,840,027 | Animation differences between my code and babylon, why? | I'm trying to render the glTF RiggedSimple sample model.
This is my code's result:
This is babylon's:
As you can see, in mine the model deforms, however in babylon it remains fairly rigid.
In my case I am not doing anything fancy, i shoving the skin matrices as defined in gltf directly to the GPU, so no quaternion sk... | This is the correct behavior of RiggedSimple, rendered in the Blender viewport.
The parent bone has its origin at the bottom center, and the child bone has its own origin halfway up the model (shown with an orange dot in this case). When the vertices at the top move, they move only due to rotation. The center of rota... |
64,830,239 | 64,830,457 | Taking Items of varying types from file and adding them to an array | I'm currently working on a lab that needs to keep inventory for a hardware store in a variety of ways. One of the ways is to put the information into an array. There is a list of tools that are given that each have a Record number, name, quantity, and cost. I figured that the best way to go about doing this is to put t... | I gather you would like to store values from a text file into an array. If so,
you would want to start by reading each line from the file. Next, split the line into each data field. Then append to the text file and repeat.
To read each line, I used a string to hold the line being read
Next, the line is split every time... |
64,830,540 | 64,830,599 | How to convert a std::string to L data type | Hello I start studying c++ and I'm trying to learn what data type is something that starts with a L, like
auto something = L"Monday";
What data type is auto?
And how do I convert a std::string to this data type?
std::string my_string = "Hello World"; to ? something = L"Hello World"
| auto is not a data-type. It is a placeholder that gets deduced depending on the initializer used.
In your case, the initializer is a wide string-literal of type const wchar_t[size], which decays to const wchar_t* when used to initialize the variable.
A wide string can be stored in a std::wstring.
How to convert a std::... |
64,830,579 | 64,830,611 | Which will be the best way to sort vector of unordered map by ascending order of the size of individual map c++ | Suppose, we have a vector of unordered map as vector<unordered_map<char,int>> recordset;;
my code looks like this,
std::vector<string> inputStrings;
for(int i =0;i<6;i++)
{
string tmp;
cin >> tmp;
inputStrings.push_back(tmp);
}
vector<unordered_map<char,int>> recordset;
for(int i=0;i<(int)inputStrings.size... | std::sort can take 3rd argument to specify how to order elements. Passing lambda function there should be good way. The function shold return true if 1st argument should be come before 2nd argument and false otherwise.
std::sort(recordset.begin(), recordset.end(),
[](const unordered_map<char,int>& a, const unordere... |
64,830,635 | 64,830,636 | Why does my native application compiled on Apple Silicon sometimes build as arm64 and sometimes build as x86_64? | I have a basic C program:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
}
When I compile this directly using cc on an Apple Silicon device, it produces an arm64 executable:
% cc hello.c -o hello
% file hello
hello: Mach-O 64-bit executable arm64
% ./hello
Hello, world!
However, when I build it throu... | When your build command doesn't include specific flags for which architecture to build for, the compiler tools provided by Apple, like cc, perform some kind of introspection based on the architecture of the calling process. That means that if your build system has yet to be natively compiled for arm64, you might see th... |
64,830,814 | 64,830,869 | #ifdef is returning different values inside the same header file | I have two C++ files main.cpp and client.cpp, and a header file action.h. I am trying to mimic a simple client-server scenario using preprocessor directives. The code is as follows:
//main.cpp
#include "action.h"
extern void connect();
static Action server;
int main()
{
server.init();
connect();
server... | This program exhibits undefined behavior. It violates the One Definition Rule (ODR). Specifically this part:
[basic.def.odr]/6 There can be more than one definition of a class type, ... inline function with external linkage ... in a program provided that each definition appears in a different translation unit, and pro... |
64,830,855 | 64,830,890 | 'optional': is not a member of 'std' in Visual Studio | The code I am writing is throwing this error:
'optional': is not a member of 'std'
I understand that the file <optional> is located in MSVC/tools and this external dependencies section is usually populated by Intellisense, but the file appears not to be included even though I confirmed that the file does indeed exist... | You must have your C++ Language Standard option in Project Settings set to C++17 or later:
Right-Click on the project in the Solution Explorer
Select Properties
Under Configuration Properties > General > C++ Language Standard
Select ISO C++17 Standard (/std:c++17) or Preview Latest (/std:latest)
Future readers: ISO C+... |
64,831,066 | 64,831,081 | Difficulty to understand linked list implementation in C++ | I found this C++ linked list implementation in Geeks for Geeks. For the code Click here
Here from line no. 16->22 it is written
Node *head = NULL;
Node *second = NULL;
Node *last = NULL;
head = new Node();
second = new Node();
last = new Node();
I understand
Three pointers are initialized with value NULL and th... |
Where the class objects are created
The allocating new-expression acquires the memory from the free store.
From where the pointers are getting the addresses to point to.
The new-expression returns the pointer to the object that it created.
how to access it later
By indirecting through the pointer using an indirec... |
64,831,186 | 64,831,198 | Why does this function give me a segmentation fault? | I am currently trying to create a linked list which has two elements, usernames and seconds. It is supposed to read from a file and save it into two vectors.
I'm not sure why, but when I attempt to collect the data and store it into a linked list, I get a segmentation fault.
I'm kind of in a rutt, I feel like this shou... | In this part
Player *ptr = new Player;
ptr = nullptr;
ptr->username = usernames[i];
ptr->seconds = second[i];
You are overwriting the pointer to newly created object by nullptr, then dereferencing the nullptr. This will lead to memory leak and Segmentation Fault.
The line
ptr = nullptr;
should be... |
64,831,200 | 64,831,328 | Why unordered_map is not giving correct answer every time while finding is there any duplicate value present in array or not? | I have given an array and I need to find is there any duplicate element present in array or not? (I have to take input from the user.)
This is my first code which is giving the wrong answer for some test cases:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;... | You used break; in the first code, but didn't use that in the second code.
Using break; will prevent the code from reading part of test case and treat that as next text case, and it will lead to Wrong Answer.
For example, using this input
2
5 5 5 1 2 3
2 2 2
Your first code will print
YES
NO
while the correct output ... |
64,831,279 | 64,831,857 | How to add up a die roll using user inputted number of die and sides of die in C++? | I'm having trouble with my die roller program not staying within its user-set parameters when it rolls a die. The program is to:
be able to take an input in for form nDx or ndx where the d is the letter d or D.
n may or not be present. If it is, it represents the number of dice. If not, assume it is a 1.
x may or ma... | You just need to output your roll, not cumulative sum:
int dice (int nrDice, int nrSides)
{
const char* sep = "";
int result = 0;
for (int i = 0; i < nrDice; i++)
{
int roll = ((rand()% nrSides) + 1);
result += roll;
std::cout << sep << roll;
sep = " + "
}
std::co... |
64,831,573 | 64,831,646 | How to define a function, parameters of which take variables from main() function? | I encountered a need to define a function, parameters of which take arguments from main() function. Here's the code:
#include <iostream>
using namespace std;
void unravel(char arr[][column], int field[][column], int x, int y) { //revealing adjoined cells
for (int minusrows = -1; minusrows < 2; minusrows++){
... | These lines in main():
int row, column;
cin >> row >> column;
char a[row][column];
int field[row][column];
results in attempting to declare an array using runtime values. This is not valid C++.
Arrays in C++ must have their sizes denoted by a compile-time expression, not a runtime value.
The simplest solution is to ... |
64,831,699 | 64,831,975 | How to save variable in for loop? | I have made a random password generator.In function void passwordGenerator(int sizeOfPassword)
The problem here is this I am trying to save the password generated by the program in sum but I don't know how to do it properly.
How do I save random digits password in sum.
#include <iostream>
#include <ctime>
#include <cst... | You might display letter by letter:
void passwordGenerator(int sizeOfPassword)
{
const char allChars[] = {"0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
for (int i = 0; i < sizeOfPassword; i++){
std::cout << allChars[rand() % sizeof (allChars)];
}
}
or building a string:... |
64,832,044 | 64,832,082 | Can I store subclass instances inside a superclass instance? | I want to create a tree structure with my classes so that I may update an object and then its children recursively.
My first idea was to add a variant list to the superclass so that every subsequent derived class can also store a list of children (thereby forming the tree structure). I tried implementing something like... | The problem is that the definition of updateChildren() appears too early, before subclasses are defined. As a result, incomplete types are used in a context that requires complete ones.
One possible solution is to put the definition of SuperClass::updateChildren() at the very end:
class SuperClass {
// ...
void... |
64,832,095 | 64,832,550 | How do I fix my selection sort? only returns "0" | Hello I'm fairly new to c++ coding as a first-year comp sci major and I am working on a lab in which I have to fill an array and do multiple types of sorting and searching, and I'm stuck on selection sort as my code will only return 0. any help is appreciated! <3 ^_^
HOW TO USE
FIRST DO OPTION "1" TO FILL IN ARRAY
ENT... | Ask yourself what the result of sorting an array should be. I hope you can see that it should be another array. If you sort the array {4, 8, 1, 3} (for instance) into ascending order the result is the sorted array {1, 3, 4, 8}.
But your code assumes that the result of a sorting an array is an integer.
result = selectio... |
64,832,120 | 64,832,335 | Shuffle 10% of an array | How can I shuffle just 10% of an array such that 90% is untouched and a random 10% is shuffled?
I apply a sorting algorithm to the array. I was thinking of using rand() but I'm not sure how to limit the shuffle to only 10%.
| Can probably be improved, but you might do something like:
template <typename Rnd, typename IT>
void partial_shuffle(Rnd&& rnd, IT begin, IT end, std::size_t k)
{
std::vector<std::size_t> indexes(std::distance(begin, end));
std::iota(indexes.begin(), indexes.end(), 0);
// Select subset to shuffle
std::... |
64,832,129 | 64,832,605 | CMake building library and executable once and linking it | I'm trying to build two projects using cmake at same-time.
My folder structure is as follows:
project
├── CMakeLists.txt
├── build
├── out
├── lib
├── yanthra_engine
│ ├── CMakeLists.txt
│ └── ...
└───sandbox
├── CMakeLists.txt
└── ...
main CmakeLists.txt
cmake_minimum_required(VERSION 3.4.1)
project... | You don't seem to link the link the yanthra target. You should do this though, since this will automatically choose the library compiled with the current configuration.
sandbox/CMakeLists.txt
...
target_link_libraries(yanthra_sandbox PRIVATE yanthra ${LIB})
...
As for importing the other libs: It would be preferrable ... |
64,832,299 | 64,832,333 | C++ constructor implicit type conversion | Let's assume that I have this code:
class A {
public:
A(int y) { cout << y; }
};
int main() {
A a(1.5);
return 0;
}
Even though 1.5 is a float, this code works and returns 1. The float was implicitly casted to int. Why didn't it throw an exception? Do constructors depend on amount of parameters or their ... | Because such implicit conversion (from double to int) is allowed.
Floating–integral conversions
A prvalue of floating-point type can be converted to a prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value cannot fit into the destination type, the behavi... |
64,833,124 | 64,833,406 | How to parse a JSON key nest using RapidJSON | I'm using RapidJSON to parse an incoming JSON file, I can iterate and get the value through the different nests. I mean the variable values (i.e.: protocolVersion = 2). But I cannot get the start of a nest { : }. Using the following JSON as an example:
{
"header":{
"protocolVersion":2,
"messageID":2,
... | There are 2 overloaded methods in source code of RapidJSON:
Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); }
ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); }
And all of them return object by value. You should try to define header like simple object (n... |
64,833,179 | 64,833,413 | Define subpackages for variadic templates in C++ | I have something like that based on variadic templates:
class MyClass {
public:
template <typename... OtherTs>
typename std::enable_if<sizeof...(OtherTs) == 0>::type Setup() {}
template <typename T, typename...OtherTs>
void Setup() {
DoSomeStuff(new T());
Setup<OtherTs>();
}
};
It's ... | You might use recursion when tuple or any specific type (tag here) is given:
template <typename...> struct tag{};
class MyClass {
private:
template <typename T>
void SetupImpl(tag<T>)
{
// Here, individual setup
DoSomeStuff(new T());
}
template <typename ...Ts>
void SetupImpl(ta... |
64,833,881 | 64,834,118 | Pass char* to function and overwrite it in memory | I want to pass a string (char *) to a function inside a dll to overwrite it with another string.
File dll.cpp
__declspec(dllexport) void getString(char *name, char *buffer, int len) {
std::string str = getString(); // buffer should be overwritten with this string
char *cstr = new char[str.length() + 1];
st... | It's pretty clear you're confused about pointers. It looks like your use of cstr is at attempt to give buffer some memory, but that won't work and cstr is unnecessary.
Here's the correct code, buffer is allocated in main, and cstr is eliminated.
char *buffer = new char[128];
getString("z", buffer, 128);
printf("%... |
64,834,160 | 64,834,363 | Get the RAM type detail description from WMI | I use the following command: wmic path Win32_PhysicalMemory get TypeDetail to get the type detail value. It returns: 16512. From the Microsoft docs: https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-physicalmemory
Only the following values are available:
Reserved (1) Other (2) Unknown (4) Fast-paged (... | Per Microsoft documentation it appears that the value comes from SMBIOS information. If we break down the value 16512 to bits, we'll see that bits 7 and 14 are set. From SMBIOS spec, section 7.18.3 Memory Device — Type Detail, we can see that bit 7 indicates Synchronous and bit 14 indicates Unbuffered (unregistered).
|
64,834,658 | 64,834,915 | Why does the following custom iterator implementation not play nice with `std::all_of`? | I am working on some iterator type that needs to wrap another iterator. For some reason, the custom iterator is not well defined. For example, it does not compile when used with std::all_of, complaining about a mismatching function call to std::iterator_category:
/opt/.../stl_algo.h:108:32: error: no matching function... | std::iterator_traits requires a reference member type, not reference_type. Fixing that allows it to compile successfully:
using reference/*_type*/ = value_type&;
...
reference/*_type*/ operator*() { return *it_; }
https://godbolt.org/z/PzK9fq
|
64,834,776 | 64,853,084 | Input facet components contain degenerate triangles | I'm calling IGL trim_with_solid like this:
#include <igl/copyleft/cgal/trim_with_solid.h>
// Input
Eigen::MatrixX3f m_VA;
Eigen::MatrixX3i m_FA;
Eigen::MatrixX3f m_VB;
Eigen::MatrixX3i m_FB;
// Output
Eigen::MatrixX3f m_V;
Eigen::MatrixX3i m_F;
Eigen::Matrix<bool, Eigen::Dynamic, 1> m_D;
Eigen::VectorXi m_J;
// Fill... | Actually, the input B mesh i.e. VB/FB was messed up and contained degenerate triangle polygons. After fixing B mesh, the errors got resolved.
|
64,835,369 | 64,838,275 | How to employ a variable as parameter inside template of the Eigen::Map class | I encountered the following issue in Eigen taking a set of elements uniformly spaced within a vector employing the class Map.
void func (int A, int B)
{
Eigen::Map<VectorXf,0,Eigen::InnerStride<B> > myMap(v.data() + B - 1, A);
}
The issue is in the 3rd argument of the template "Eigen::InnerStride". The compiler sa... | You can use dynamic stride, like this:
void func (int A, int B) {
Eigen::Map<VectorXf,0,Eigen::InnerStride<>> myMap(v.data() + B - 1, A, Eigen::InnerStride<>(B));
}
If this section is performance critical, and if the number of feasible B's is small (like - maybe the only valid values are B=2 and B=3), then you can... |
64,835,479 | 64,837,184 | QObjectPicker not receiving hovering QMouseEvent in Qt3DWidget | I've implemented a Qt3DWidget which works fairly well by letting Qt3D draw to an offscreen texture and using the texture's ID to draw on a quad in a QOpenGLWidget. The input source on the QInputSettings is set to this, i.e. the widget itself.
One issue that remains is that mouse hovering events (without clicking) are n... | Thanks to Scheff in the comments I was able to make it work by setting setMouseTracking in the QWidget class to true. This was blocking the hovering events.
|
64,836,123 | 64,844,302 | Why my HID keyboard doesn't work very well? | I've just started programming my AtMega8 with using V-USB link: https://www.obdev.at/products/vusb/index.html. I'm trying to make a keyboard witch will be pushing CTRL+ALT. To do this I modified one of the project "HID Keys" link: https://www.obdev.at/products/vusb/hidkeys.html. I added and modified:
//line 150, added ... | The report descriptor in the sample program defines a 2-byte report to represent a single keystroke. The first byte contains 8 bits each representing a key modifier (left ctrl, right alt, left shift etc) and the next byte is an index representing a key usage (key A, key B, key Delete, etc).
You need to logically OR the... |
64,836,448 | 64,844,705 | Good way to cast `dlib::matrix<T>` into `dlib::matrix<S>`? | What is a good way to cast dlib::matrix<T> into dlib::matrix<S>?
For example, dlib::matrix<float> into dlib::matrix<std::complex<float> >?
Edit:
I am looking for something more efficient than this:
template <class T> void toComplex(const dlib::matrix<T>& matr, dlib::matrix<std::complex<T> >& res) {
res = dlib::zeros_... | You want to call complex_matrix(your_real_matrix). See http://dlib.net/dlib/matrix/matrix_math_functions_abstract.h.html#complex_matrix. There are a variety of similar casting routines.
|
64,836,454 | 64,836,478 | How do I specify a parameter type by some quality of the parameter rather than its exact type? | So I have a function in C++ as follows:
void print_vec(std::vector<int> v) {
for (int i: v) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
Which works and all, but is only applicable to int vectors. I want something like
void print_iter(Iterable<CanDoCout> iterable) {
for (auto i: iterable) {
std... | What you are looking for are templates:
template <class T>
void print_iter(const T& iterable) {
for (const auto& i: iterable) {
std::cout << i << ' ';
}
std::cout << std::endl;
}
You can go one step further and use concepts or SFINAE to restrict your template to only types that accept the operations you appl... |
64,836,723 | 64,836,762 | I am trying to understand the difference between parallel and sequential code using MPI library with C++ language | This is the code "expl.cpp":
#include <iostream>
#include "mpi.h"
using namespace std;
int main (int argc,char **argv)
{
cout << "this line of code is executed in sequential mode " << endl ;
MPI::Init();
cout << "hello MPI world!" << endl ;
MPI::Finalize();
return 0;
}
After compiling the code above with
mpicc -o e... | If you read the doc you it says
This will run X copies of in your current run-time environment
Which is exactly what happens.
|
64,836,905 | 64,837,390 | Switch statement not taking input | This program manages student's scores. For some reason that is unknown to me, the switch statements are not working. I personally think it is reading the whitespaces which will hinder it from taking input. Or am I overlooking another problem? I have tried using (" %d", &choice), also cin >>. But it always exits the pro... | As commenters noted, the function calls should not have void before them. i.e.
switch (choice) {
case 1:
get_information();
break;
case 2:
search();
break;
case 3:
del_information();
break;
case 4:
display();
break;
case 5:
break;
default:... |
64,837,122 | 64,837,147 | Running Blocking Function in Background | I am trying to run a program that essentially runs forever. I need to start it with certain parameters that I load in so I am running it from within my c++ program. Say this is the program.
int main() {
while(true) {
// do something
}
}
It compiles to a shared library object: forever.so.
If I do the followi... | system uses /bin/sh, which is a POSIX shell. & after a command means to run it in the background, which means it won't block. Read here for more info.
|
64,837,196 | 64,837,291 | I cannot print the value of the pointer | I am working on the small program below in order to understand binary trees a bit better. I simply wanted to make sure that the pointer *padre is being assigned correctly, however nothing prints to the console and I think it has to do with me not understanding how pointers work. Please help.
#include <stdio.h>
#include... | You're invoking undefined behaviour by accessing a nullptr: you're passing NULL as the first argument to Agregar. Fixing up your code to get the expected printout of the node's value looks like this:
#include <cstdio>
class Nodo {
public:
Nodo(int valor) {
dato = valor;
izquierdo = 0;
derec... |
64,837,229 | 64,838,380 | C++ cant use respond string from GET requests retrieved by ExpressJS API for anything else than printing | Scenario:
Im writing a c++ program which should retrieve files and strings from an expressJS API..
Downloading txt.files with curlRequests works perfectly but as soon as i try to retrieve plain strings, they can only be used for printing..
Problem: When trying to do anything with the response from my GET request (from ... | Thank you @n.'pronouns'm.
I Updated my function and realised that res = curlRes was a nobrainer..
Also the checks for valid response is gone for now.
//those 2 lines and a write_to_string function were missing and `res = curlRes` should do their job
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
curl_e... |
64,837,323 | 64,837,387 | C++ template specialization without template<> | I have two versions of program. First:
template<class T>
void f(T i, T j) = delete;
template<>
void f(int i, int j) {
cout << i << j << endl;
};
int main()
{
f(1.5, 2);
return 0;
}
And second:
template<class T>
void f(T i, T j) = delete;
void f(int i, int j) {
cout << i << j << endl;
};
int main()... | For a (unqualified) function invocation as f(1.5, 2) in your code the compiler builds a set of candidate functions which contains regular functions and functions generated from templates. A function template is not a function until the template arguments have been resolved and substituted. See overload resolution for f... |
64,837,521 | 64,837,547 | Why #define UNICODE has no effect in windows | I have the following code:
#define UNICODE
// so strange??
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
But the compiler still report error like this:
error C2664: “DWORD K32GetModuleBaseNameA(HANDLE,HMODULE,LPSTR,DWORD)”: 无法将参数 3 从“wchar_t [260]”转换为“LPST... | You must put
#define UNICODE
#define _UNICODE
BEFORE
#include <Windows.h>
The Windows header uses #ifdef UNICODE (et al), so if you want to make the distinction count, the #defines must occur before the #include.
edit: Because these #defines are functionally global, the most reliable place to add them is in your com... |
64,837,886 | 64,837,969 | c++17 (c++20) unordered map and custom allocator | I have some issues with map/unordered_map and custom allocator
my allocator looks like this, according to documentation of visual studio.
I derived my allocator from base type to ensure all template types like allocator::value_type is set correctly.
template <class T>
class std_allocator : public std::allocator<T> {
... | The key detail:
class _Alloc = allocator<pair<const _Kty, _Ty>>>
The const part is the key. The key itself must be constant, which is not the same as a pointer to a constant object. There's a difference between a pointer to a constant object, and constant pointer to a (possibly const) object.
Your map definitely appea... |
64,838,456 | 64,838,567 | Concepts impose the 2nd argument is of type int | As the title suggest, I want foo to only accept int type as it's 2nd parameter.
#include <iostream>
#include <concepts>
#include <type_traits>
template <typename U, typename T> concept IS_INT =
requires (U u, T t) {
{ t + 0 } -> std::same_as<int>;
};
IS_INT {U, T}
void foo (U u, T t)
{
std::cout << ... | You can keep the binary form even in current core concepts version:
template <typename U, typename T> concept IS_INT =
requires (U u, T t) {
{ t + 0 } -> std::same_as<int>;
};
template<class T, IS_INT<T> U>
void foo (U u, T t)
{
std::cout << "IS INT!" << std::endl;
return;
}
(note the invers... |
64,838,606 | 64,838,821 | How to compile and run a C++ project with a Makefile? | I needed a library for my project that would cover CANFIS functionalities and Fuzzylitex does that. But the problem is, I don't know how to build this project? I am familiar with cmake files but this project has Makefile and I cannot work with it? I am using Visual Studio 2015.
| Thanks to the comments, I found out about the difference between Makefile and Cmake files. The tool that can be used to make a project with Makefile in Visual Studio, is NMAKE.EXE. It is built in for Visual Studio. All you need to do is to open the visual studio command prompt (tools -> Visual Studio Command Prompt) an... |
64,838,707 | 64,838,908 | How to build project with sdl2 library with make? | I am reading https://www.willusher.io/pages/sdl2/, I in the first chapter, I got this file tree:
Lessons
├── bin
├── include
│ ├── res_path.hpp
│ └── sdl_error.hpp
├── Lesson1
│ └── src
│ ├── hello_world.cpp
│ └── test.cpp
├── makefile
└── res
└── Lesson1
└── hello.bmp
Now from the Lesson... | -lSDL2 needs to come after test.o in the command.
According to the make manual, the implicit rule you're using looks like this:
$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)
Meaning your linker flags have to go to LDLIBS rather than LDFLAGS.
Also this looks wrong: test.o: res_path.hpp sdl_error.hpp -lSDL2. Remove the -... |
64,838,710 | 64,838,772 | Return a local reference from function | I'm trying to understand what's going on inside with this (weird?) g++ behavior.
#include <iostream>
using namespace std;
int& f(void) {
int a = 9;
int& b = a;
return a;
}
int main(void) {
int& l = f();
cout << ++l << '\n' << l << '\n';
}
When returning a itself and bind it to l, I get a warning (reference ... | Your main question is why gcc doesn't issue a warning in one of the alternatives. Both alternatives are undefined behavior and the only difference is that in one case the compiler can detect it and warn you about it.
The C++ standard does not require a diagnostic for undefined behavior. Any diagnostic to that effect, f... |
64,838,771 | 64,838,961 | How to overload assignment operator and create copy constructor for 2D Dynamic Arrays? | I have a flight class which has bool** property in it.
class Flight {
public:
int flightNumber;
int row;
int seat;
bool** seatReserv;
Flight();
Flight(int fly,int rw,int st);
~Flight();
Flight(const Flight& rightVal);
Flight& operator=(const Flight& rightVal);
};
I tried to write my overloaded assignment ope... | This would probably work as copy constructor:
Flight::Flight(const Flight &rightVal){
this->flightNumber = rightVal.flightNumber;
this->row = rightVal.row;
this->seat = rightVal.seat;
this->seatReserv = new bool*[row];
for (int i = 0; i < this->row; i++){
this->seatReserv[i] = new bool[seat]... |
64,839,011 | 64,839,227 | Unexpected sscanf Result | I have a sscanf statement that is behaving unexpectedly. This is somewhere around loop #8000 that it suddenly does this. This is the code, where str is a string parsed from a file:
char a1[6], a2[6], op[6], a3[6];
int success = sscanf(str.c_str(),"%*s %s %*s %s %s %s",a1, a2, op, a3);
And this is the gdb output on the... | Your arrays have length six:
char a1[6], a2[6], op[6], a3[6];
Yet, sscanf causes "po011;" to be written in a2, and this requires seven characters, since sscanf will add the null terminator. Hence, sscanf causes undefined behavior.
Pragmatically, in your implementation the null terminator was added to the beginning of ... |
64,839,216 | 64,839,297 | Which vtable does the object of subtype use in c++ | when I want to execute this line of code, it doesn't compile
baseArray[1]->function5();
But in vtable of Derived 3, function5 should points to function5 in Derived1. so I think it should output Derived1::function5(). But it seems to find function5() in the Base class
I just wondering that Derived3 inherited from ... | C++ is a statically typed language. That means references to types, members, variables, etc have to be known at compile-time.
The reason why baseArray[1]->function5(); and baseArray[1]->function6(); do not compile is because baseArray[1] is declared as a Base* but function5() and function6() are not members of Base. Si... |
64,839,622 | 64,843,379 | Why I receive error while compiling RapidJSON | Using RapidJSON for parsing a JSON file, I get these errors.
This is part of the JSON file:
{
"header":{
"protocolVersion":2,
"messageID":2,
"stationID":224
},
"cam":{
"generationDeltaTime":37909,
"camParameters":{
"basicContainer":{
"stationType":5,
This is ... | header is object of rapidjson::Value type and doesn't have protocolVersion, messageID and stationID members. You should provide your custom object type to store values from header. The same goes for other variables (cam and referencePosition). For example:
struct MessageHeader
{
int protocolVersion;
int message... |
64,839,738 | 64,845,099 | wxWidgets - Switch between different view on button click | I am making a music application, I have it show like a mini-view of the app as the default view, and I want it to switch to a big view on a button click. The default/mini view has a panel -> sizer -> sub-sizer -> widgets. And for the big view, I have a separate sizer and panel.
The default view looks like this
And whe... | For completely replacing the frame contents like this you may find wxSimplebook useful as you can then just call its ChangeSelection() method to switch pages. You will need to adjust the frame size, e.g. by calling frame->SetClientSize(book->GetBestSize()), after switching pages manually however.
|
64,840,039 | 64,840,058 | Why is 'i' an undeclared indentifier? (c++) | `image of code error
I am able to use 'i' for course, but not for grade. I looked at other examples, and they do the same thing, allowing the 'i' to be in the grade section.
#include <iostream>
using namespace std;
int main() {
float course1;
float grade1;
float totalhour =0;
float points;
float totalpoints... | It is because i is declared in the for loop and therefore it can be used only in the loop.
If you want to repeat multiple things, you should surround them by {}.
#include <iostream>
using namespace std;
int main() {
float course1;
float grade1;
float totalhour =0;
float points;
float totalpoints =0;
for(i... |
64,840,208 | 64,840,244 | Counting words in a text file, C++ | I am trying to count the number of words in a text file. My code seems correct but whenever I run the code, the word and line count seems to be a very large random number.
My file test.txt only has a couple words in a couple lines.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int mai... | int numlines;
int numWords;
These variables are declared and defined but not initialized. As such this is undefined behavior, manifesting itself as initial values of these counters being random garbage.
In this case you must explicitly set them to 0, here.
|
64,840,452 | 64,840,537 | C++: How to see if an element in an array is over a certain value? | New to C++, so I apologize in advance for my ineptitude.
I need to write a function outside of function Main that checks the elements of an array (that were entered by the user) to see if they are over 10. If they are, I need to print that number of elements as well as a list of the elements themselves. If they aren't,... | If you just need to count the matching elements, you can use a simple loop, eg:
void print_over_ten(const int list[], int length)
{
int amount = 0;
for (int i = 0; i < length; ++i)
{
if (list[i] > 10)
++amount;
}
if (amount > 0)
cout << "There are " << amount << " number... |
64,840,532 | 64,841,105 | C++ Template Parameter sizeof Returns Incorrect Result | That way I can find the number of elements in an array. However, when I put this int array as a template as a parameter, the result is not calculated correctly
int arr[] = {1,2,3,4,5};
int size_arr = sizeof(arr) / sizeof(arr[0]);
I add an INT Array to the List as a parameter with the type template.
template <typenam... | The main issue is that arrays decay to pointers, thus the values of sizeof() in your template function addList actually is attempting to get sizeof(int *).
If all that addList does is add items to the std::list, there are generic ways to do this without need to create another function.
One way is to use std::copy_n:
#i... |
64,840,566 | 64,840,598 | Have I found a bug in Clang and GCC? | main.cpp:
#include <iostream>
struct Cls {
static void some_method() {
std::cout << __FILE__ << ": " << __LINE__ << std::endl;
}
};
extern void call_some_method();
void never_caled() {
Cls::some_method(); // (1)
}
int main() {
call_some_method();
return 0;
}
cls.cpp:
#include <iostream... | __FILE__ and __LINE__ are macros that are expanded by the pre-processor. Since those macros are in different files, and depend on the files they are used in, they expand to different token sequences.
That means that your definition of Cls::some_method is different across different translation units. This violates the o... |
64,840,968 | 64,867,819 | Is there a type for 16 size data? | I heard that in 32bit computer(1990~2000?) had to use a 8 size data like below;
(that I heard of... there was no 8 size type, then... )
they used like this;
// 8 size
typedef union _LARGE_INTEGER {
struct {
DWORD LowPart;
LONG HighPart;
} DUMMYSTRUCTNAME;
struct {
DWORD LowPart;
... | I used another way to may a 16 size variable
__declspec(align(16)) struct aa {
long long a;
long long b;
char c;
}
this way you can make a 16 size padding in structs
|
64,841,045 | 64,841,120 | What is more efficient? vector.assign vs vector.erase | When a vector exists and tries to erase the back of that vector.
Is it efficient to use an 'vector.assign' in terms of time complexity? Or is it efficient to use 'vector.erase'?
Please let me know the time complexity in each case.
[For example]
vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// 1. use assign
v.ass... |
I would like to use vectors that consist only of elements from the beginning section of vectors to a certain index.
It's most efficient to use resize, because that's what that function is for.
For what its worth, self-assignment is not allowed for containers.
|
64,841,123 | 64,841,202 | C++ Xcode build failure, errno.h not fount | I am working on learning c++ and tried to build a simple hello world program in Xcode (MacOS Catalina). It is a Command line program. I followed the prompt on Xcode and accepted all the default parameters then created a cppfile with the following code
#include <stdio.h>
#include <iostream>
int main(){
std::cout<<... | My project was a framework instead of an Xcode project. I discovered this by looking under the products folder and seeing it was .framework instead of .app.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.