question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
61,548,611 | 61,549,466 | Speed : typedef vs #define in c++ | Recently I came across typedefs and #defines. Even though they have similar usage, one of them is a compiler token and the other is a preprocessor token.
This made me wonder about their speeds of operation, as one wants to be as fast as possible in competitive programming.
So, which one is relatively faster? An explana... | There is no difference in performance, but preprocessor macros are not recommended because they pollute the global scope since unlike typedef they can't be placed in a namespace.
But arguably, ll isn't very expressive; it may make the code less readable. Consider using int64_t from <cstdint>. It's nice because it's mor... |
61,548,621 | 61,548,844 | How can be that a destructor is called but no constuctor before that? | I am currently learning the object oriented feature of c++. I wrote a piece of code to test how inheritance and polymorphism works.
Here is a part of the code:
class Person
{
public:
Person()
{
cout << "Person constructed\n";
}
virtual void introduce()
{
cout << "hi from per... | void whoisthis3(Person object)
{
object.introduce();
}
This function accepts its object parameter by value. That means that a new Person object is created as a copy of the object that you pass to whoisthis3. Since you haven't explicitly defined Person's copy constructor, this uses the default copy constructor ge... |
61,548,836 | 61,549,463 | C++ Newton Raphson method is slower than bisection? |
My task is to find the root of a function with both the Newton Raphson and the bisection method within an error margin of 10E-7.
The point of all that is, that we learn that the Newton Raphson method is faster and more effective.
Now for some reason I come to the opposite result. Although I am aware that the initial g... | For the function
f(x) = A * (x - B) - C * (D / x - 1) / sqrt(x)
A = 0.00000000027
B = 10000000
C = 0.16460351745
D = 1000000000
the correct derivative is:
f'(x) = A - C (x - 3D) / (2 * x * x * sqrt(x))
Compare this with your expression:
g(x) = A - C (x - 3B) / (2 * x * x * sqrt(x))
After fixing the formula (by addi... |
61,548,932 | 61,549,172 | Force CMake to rebuild precompiled headers | How do I get CMake to rebuild all the precompiled headers? (Using g++ and Linux) And how do I get CMake to disable all precompiled headers?
I am getting some build errors that have sprung up and they refer to the .ch files. So want to investigate whether this is due to precompiled headers.
| In CMake, and assuming use of the target_precompile_headers() command, you can disable precompiled headers for a specific CMake target by setting the DISABLE_PRECOMPILE_HEADERS property:
set_target_properties(MyTarget PROPERTIES
DISABLE_PRECOMPILE_HEADERS ON
)
or you can disable precompiled headers for the entire... |
61,549,182 | 61,552,487 | boost::spirit::qi preserving white space | I am using this code to parse "k1=v1;k2=v2;k3=v3;kn=vn" string into a map.
qi::phrase_parse(
begin,end,
*(*~qi::char_('=') >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
qi::ascii::space, dict);
The above code would remove space chars, e.g. "some_key=1 2 3" becomes some_key -> 123
I can't figure o... | If you want no skipper, simply use qi::parse instead of qi::phrase_parse:
qi::parse(
begin,end,
*(*~qi::char_(";=") >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
dict);
However, you likely DO want to selectively skip whitespace. The easiest way is usually to have a general skipper, and then mark the lexeme areas... |
61,549,919 | 61,550,091 | inheritance in structs prototypes | Is it possible to represent this in C++:
struct foo {
int x;
int y;
struct A derived;
};
struct A {
int val;
};
struct B : A {
int baz[10];
};
struct C : A {
int baz[20];
};
Where derived can be any of the inherited structs of A (either B or C) but never A, without changing the prototype str... | struct A {
int val;
virtual ~A() = 0; // so nobody can instantiate A alone.
};
inline
A::~A() = default; // the destructor HAS to be defined.
struct foo {
int x;
int y;
std::unique_ptr<A> derived;
};
And then the rest being the same...and using:
foo foo_v; foo_v.derived = std::make_unique<B>();
... |
61,549,956 | 61,550,120 | How to check the strength of a password in C++ using bool functions | Working on an exercise for my class. My teacher wants us to work with C-string, not the string class. We must use bool functions and C-string commands to determine if a password is strong enough. I think I'm close to being done but I must have some error somewhere? Here's what I've got:
#include <iostream>
#include <cs... | All your loops are wrong, you're confusing the index of the character you are testing, with the count of the number of characters that have passed the test, you need separate variables for this. Plus you have an out by error on the length of the length of the string, you had len - 1 instead of len.
So this
bool checkle... |
61,550,307 | 61,550,486 | rand() function wont work when trying to randomizes between two floats | So I have to randomize between two postive floats and two negative floats, the negative floats being [-.010, -0.001] annd the postive floats being [0.05, 0.10]. I cant seem to figure out how to do this as I cant use the % operator like i usually do. This is what my current code looks like:
float randNeg = rand() %... | rand() returns an integer between 0 and RAND_MAX (inclusive), so you can totally map it using something like this:
float randFloat(float minVal, float maxVal)
{
return rand() / (float)RAND_MAX*(maxVal - minVal) + minVal;
}
But you should really think about what you actually want to do with this. And be careful wit... |
61,550,311 | 61,550,509 | Calling wrong template function prototype problem in c++ | I am currently making my custom vector container for understanding better the real STL containers. I am confront with the problem of "insert" function.
These are two prototypes of "insert" in my vector container.
// 1
template <typename T, typename Alloc>
void vector<T, Alloc>::insert(iterator position, size_type n, c... | You need to use some SFINAE to restrict the InputIterator overload to iterator types.
Assuming your iterator adheres to iterator_traits and/or has a nested type like iterator_category, you can check for its presence via SFINAE:
template <class Iter>
using iter_cat_t = typename iterator_traits<Iter>::iterator_category;
... |
61,550,414 | 61,550,489 | std::string::replace "no matching function for call" error | I really don't know how to make this program work correctly. The only problem at the moment is the replace. I can't get it to work. What am I doing wrong with it? We're only allowed to use if-else, and while statements.
#include <iostream>
#include <string>
using namespace std;
int main() {
/*i becomes !
a b... | You are not calling any of the overloads of std::string::replace. However, since you are only replacing a single character, instead of replace, you could simply do
passWord[chariIndex] = '!';
If you want to use replace then you could call it like this:
passWord.replace(chariIndex, 1, "!");
Note that the 3rd argument ... |
61,550,633 | 61,550,761 | C++ Print Destructor | I am using pointers for the first time, my code runs correctly but I need to print a destructor from another .cpp file and don't know how to do so.
After a node is dropped using these two functions:
bool LList::remove(node* r) {
if (r == NULL || search(r->key) == NULL) {
return false;
}
if (r == hea... | I'm assuming that by printing you mean executing the destructor. In this case whenever you call delete on an object the compiler sort of checks to make sure that
a destructor is present within the object and then executes it. So in this case you would call delete n; where n is your node. Also when you call the remove n... |
61,551,061 | 61,551,374 | Where should I put my random number generation to get random results? | I have a nested system as described in the pseudocode below (part of a random weighted majority algorithm):
function1() {
//for 100 iterations:
function2()
// grab logistics
}
function2() {
// create a random seed/generator
random_device rd;
mt19937 gen(rd);
//for 1000 iterations:
... | Although you have only shown pseudocode, it appears that you are creating a new random device and generator every time you call the function. This is needlessly expensive, and more importantly, every time you call the function, you'll get the same results from the random generator. The simplest modification to your pse... |
61,551,081 | 61,553,984 | DirectX Visual Studio templates don't Work | I installed a bunch of visual studio directx templates and none of them seems to work. They all throw an error like: "Error: this template attempted to load component assembly 'Microsoft.VisualStudio.Universal.TemplateWizards, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. For more information on ... | To use the DirectX-VS-Templates you need to have the "Universal Windows Platform" workload installed with VS 2017 or VS 2019. It provides the Microsoft.VisualStudio.Universal.TemplateWizards component.
This is true of both the UWP and Win32 templates in that GitHub project.
For the Direct3D UWP templates which use C++,... |
61,551,596 | 61,883,375 | can we convert one class data into another class by operator overloading in c++? | I have 2 classes Employee and Person. Employee class have three attributes name, age and salary. Person class have attributes name and age. I want to overload assignment operator to assign name and age of Employee class to name and age person class.
class Employee {
string name;
int age;
float salary;
publ... | This the answer of above Questions
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
int age;
float salary;
public:
// default constructor (meaning less)
Employee() {
name = "";
age = 0;
salary = 0.0;
}
/... |
61,551,687 | 61,554,166 | Using boost variant with std::functions containing a bool input | See the following code:
void stringPtrFunc(const std::string *s) {}
void boolFunc(const bool b) {}
int main() {
boost::variant<std::function<void(const std::string *)>, std::function<void(const bool)>> myVariant;
myVariant = &stringPtrFunc; // Compiles fine
myVariant = &boolFunc; // Error
}
I'm getting a... | The problem is that &boolFunc is not a std::function (of any type), it is a function pointer. As such, it can be converted to any std::function that it is compatible with, but no one of them is any better than any other. In particular, since any pointer type can be implicitly converted to bool, &boolFunc can convert ... |
61,552,044 | 61,552,153 | How to write a c++ operator overload for input/output without knowing the type when using it | I made an operator:
template <typename Container>
std::ostream& operator << (std::ostream& out, const Container& container) {
string result = "{";
out << result;
return out;
}
When I want to use it:
enum class space { empty, full, half };
using elements_t = vector<space>;
int main(int argc, char** argv)
{
eleme... | If I try your program, the compiler complains about the operator<<() inside your custom operator definition (better to copy the exact error message including the line number). I suppose you want to use std::operator<< here (recurring would result in an infinite recursion). To do that, you exactly write that:
template <... |
61,552,112 | 61,553,319 | Iterator to one past the last element in list | I'm working on implementing my own list. I see that std::list::end() returns iterator to one past the last element in the list container. I'm wondering how the position of this past-the-end element is estimated due to list elements are stored in non-contiguous memory locations.
std::list<int> ls;
ls.push_back(1);
ls.pu... |
How can it be known at which positions (in memory) the next elements will be stored?
It is not. Also, using that memory address as (part of) the past-the-end iterator would be incorrect.
Is not:
An iterator is not (necessarily) a pointer. An iterator is not required to store a memory address. What is required is that... |
61,552,286 | 61,552,455 | I have a text file with each line containing an integer. I want to open the text tile and count the number of integers in the file | void DataHousing::FileOpen() {
int count = 0;
// attempt to open the file with read permission
ifstream inputHandle("NumFile500.txt", ios::in);
if (inputHandle.is_open() == true) {
while (!inputHandle.eof()) {
count++;
}
inputHandle.close();
}
else {
... | A fairly easy way to do this would be to use std::cin instead. Assuming that you want to count the number of integers in a file you can just use a while loop like so:
int readInt;
int count = 0;
while(std::cin >> readInt){
count++;
}
Then you just pass in the file as an argument parameter to your executable as so... |
61,552,481 | 61,591,050 | vector<map<move-only type>> does not compile with MSVC | Making a vector of a map of move-only types doesn't seem to work properly on Windows.
See code here: https://godbolt.org/z/yAHmzh
#include <vector>
#include <map>
#include <memory>
// vector<vector<move-only>> works
void foo() {
std::vector<std::vector<std::unique_ptr<int>>> outer;
std::vector<std::unique_ptr<... | To enforce move semantics for vector, we need to inform C++ (specifically std::vector) that the move constructor and destructor does not throw, using noexcept. Then the move constructor will be called when the vector grows. See this note:
To make the strong exception guarantee possible, user-defined move constructors ... |
61,552,635 | 61,552,685 | Recursive C++ code goes into infinite loop | Why does the following code go into an infinite loop:
#include<iostream>
using namespace std;
void printarray(int arr[], int n, int i);
int main(){
int arr[] = {1,2,3,4,5};
int n = sizeof(arr)/sizeof(arr[0]);
printarray(arr,n,0);
return 0;
}
void printarray(int arr[], int n, int i){
if(i >=n)
... | i++ means "increment i after the comand finishes"
So you call the recursive function with always the same i. Only when the function returns iis incremented.
To achieve your goal use ++i instead.
Or better, as @dxiv pointed out, i+1
|
61,552,772 | 61,552,809 | cannot bind lvalue error in filling a multidimensional grid | int grid[2][2]{};
for(int i{};i<4;i++){
cin>>*(grid+i);
}
I am trying to input values in a 2x2 grid. How should I do it correctly and what was going wrong.
| Simple possible implementation for your problem:
int grid[2][2];
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
std::cin >> grid[i][j];
}
}
You could also use range-based for loops, if you plan on changing the dimensions of the grid frequently:
int grid[2][2];
for(auto& row : grid){
for(... |
61,552,793 | 61,553,342 | to_string().length() giving incorrect results in c++. Can anyone please explain me this behavior? | #include <iostream>
using namespace std;
int main()
{
int n,t;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>t;
cout<<to_string(t).length();
}
return 0;
}
Test Cases:
Input-123 //Correct
Output-3
Intput-111111111111111111111111 //Incorrect
Output-10
Input-11111 //Incorrect
Out... | This is most likely caused by cin reading as much of an int as it can when you assign 111111111111111111111111 to t, note that 111111111111111111111111 goes beyond the capacity size for int, it even goes beyond the capacity of long long int. Then as for fixing your output, chain an endl statement to the end of your out... |
61,552,997 | 61,553,207 | Is a derived class considered a member of the base class? | I was reading about the NVI Idiom and most examples follow this form
#include <iostream>
class Base {
public:
virtual ~Base() = default;
void do_something() {
do_something_impl();
}
private:
virtual void do_something_impl() = 0;
};
class Derived : public Base {
private:
void do_something... | From this [emphasis added]:
If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same
name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers
The... |
61,553,503 | 61,568,525 | Static variable link error in MSVC even though it is created in the cpp file | I am working on a cross-platform (Linux & Windows) library. One of my class has a static member defined in the header. And I created it in a CPP file like
namespace raisim {
std::function<void()> RaiSimMsg::fatalCallback_ = []() { exit(1); };
}
The header file
#ifndef RAISIM_MESSAGE_LOGGER_HPP
#define RAISIM_MESSAGE_L... | Jack Dingler's answer here
https://www.codeproject.com/Questions/585271/Aplusstaticplusmemberplusvariableplusexportpluserr
worked. So the issue is that the Windows linker needs to know that if it has to import or export the symbol. So we have to declare __declspec(dllexport) when we export (when we build the library) a... |
61,553,513 | 61,555,413 | Find the protection level of class member C++ | Is there a way to find out what the protection level of a member is?
I'm making a singleton base-class and I'd like to ensure that the child class declares its constructor/destructor as private/protected. How can I do this?
template<class c>
class singleton
{
static_assert(std::is_private<&c::c> // does this exist?... | There is a paper written that proposed this in 2018, (and later 2019). In fact, it appears it was circulated in June of 2019 as part of the Committee's proposal process. However, I'm not really sure what happened to it (other then I think I found another revision).
Some compilers might support it experimentally. If the... |
61,553,583 | 61,553,607 | Can someone help me to explain some lines of code for tic tac toe? | I'm totally new student for c++ and finished watching some c++ tutorials for 5 - 6 hours long.
I didn't know what to study, so decided to work watch one of the tutorials of c++ and kinda following what the youtuber is doing.
While I'm working on it, I didn't get few lines of code which are
int main( int argc, char *ar... | It gets char from the leftmost digit of number. It can be done shorter
to_string(number)[0]
Suppose number is 12, then to_string(number) is "12"s, finally to_string(number)[0] is '1'.
It can be done even more shorter assuming number is between 0 and 9.
number + '0'
|
61,553,750 | 61,554,055 | C++: stopping last increment in my Fizz Buzz program | So as part of a coding challenge I tried to make a Fizz Buzz program in C++ without looking at the solution. For those of you who don't know, it should be a loop that replaces any number divisible by 3 with Fizz, any number divisible by 5 with Buzz, and any number divisible by both with FizzBuzz:
1
2
Fizz
4
Buzz
6
7
8
... | So I fixed your code a little bit:
int main()
{
for (int i = 1; i < 101; ++i)
{
if (i % 3 == 0 && i % 5 == 0)
cout << "FizzBuzz\n";
else if (i % 3 == 0)
cout << "Fizz\n";
else if (i % 5 == 0)
cout << "Buzz\n";
else
cout << i << "\n";... |
61,553,766 | 61,582,717 | Read binary data, seek not working correctly | I have been having some issues with trying to read data out of a binary file that is structured so that the header is the first 1024, or 4069 bytes, and the payloads are all regular blocks after that. Below is a model of the code that I have been using:
Header:
#pragma once
#include <stdio.h>
#include <iostream>
#incl... | Turns out, what I needed to do was multiply the HeaderSize by CHAR_BIT so it would look something like this:
int Load_Payload_Into_Buffer(int payload_index, void* buffer)
{
buffer = malloc(PayloadSize);
size_t offset = HeaderSize*CHAR_BIT + static_cast<long long>(frame_index) * PayloadSize;
BinaryFileStream... |
61,553,990 | 61,554,175 | What are memory mapped files? | Recently, I've come across this video that shows how to use mmap() with file io. However, I can't find the video of his that documents the function. I don't have an understanding of what it is, why it exists, nor how it relates to files.
Too much of the jargon is flying over my head to make sense of it. I had the same ... | Files are arrays of bytes stored in a filesystem.
"Memory" in this case is an array of bytes stored in RAM.
Memory mapping is something that an operating system does. It means that some range of bytes in memory has some special meaning.
Memory mapped file is generally a file in the file system, which has been mapped by... |
61,554,320 | 61,554,386 | using nested for loops to make code more efficient c++ | I am currently stuck on trying to nest several for loops.
I will post the code and then explain it.
void IdeaBank::AND_searchQuery(string search_word1, string search_word2){
vector <int> match;
for (int i=0;i<newIdea.size();i++)
{
for (int j=0;j<newIdea[i].getKeyword().size();j++)
{
... | If you are searching for a case where both search terms are in the keyword list for a given item, you could just use std::find instead of the inner loop. For example:
for (auto&& idea : newIdea)
{
const auto& keywords = idea.getKeywords();
bool found1 = std::find(keywords.begin(), keywords.end(), search_word1)... |
61,554,770 | 61,555,090 | print a multidimensional array using range based for loop | I am trying to print a 2d array int arr[n][n] and here's what I tried:
for(int (*x)[n]:arr){
for(int k:x){
cout<<x<<" ";
}
cout<<endl;
}
I am getting the following error:
[Error] cannot convert 'int*' to 'int (*)[3]' in initialization.
It's a request to answer without using auto in the loop.
| Try to avoid global variables and pass the array to your functions by reference instead. You should also take the inner array by reference in the range based for-loop.
#include <iostream>
// a function to display a 2D int array of any sizes
template<size_t N, size_t NN>
void display_2d_array(int (&arr)[N][NN]) {
f... |
61,555,053 | 61,560,464 | Node js native module, triggering callback from objective-c block event listener doesn't work | I need to create a native node module that listens to an objective-c OSX event, and triggers a callback to javascript every time it happens:
nativeAddon.listen(() => {
console.log('It works!')
})
The callback works when immediately called in the setUpCallback function, but it doesn't fire from the objective-c obse... | Try changing the type of event_callback from Local<Function> to Persistent<Function>.
The lifetime of a Local is tied to that of the HandleScope it was created in. Once the HandleScope goes out of scope (in your case, at the end of function setUpCallback), all Locals created while it was active become invalid. If you n... |
61,555,284 | 61,555,361 | Making --std=C++17 default in Mac OS Catalina | I use g++ --std=c++17 sol.cpp very frequently so I want to make this as default. To do this I have gone through many of the answers here but none of them are working in my system.
I have tried alias,
alias g++='g++ --std=c++17'
in my .bash_profile but it is not working.
Please help me with this for which I will be tha... | Apple changed shell from bash to zsh due to licensing concerns.
Therefore configuration files are now .zshrc and .zprofile.
Add alias to ~/.zshrc
alias g++='g++ -std=c++17'
Don't forget to restart Terminal.
|
61,555,313 | 61,557,117 | Can't see the contents of vector or other containers (e.g map) while debugging (C++ program) in Visual Studio Code | I have written a simple C++(11) program to test the debugger in Visual studio code in Windows. I am using MinGW distributions for compiler options.
I have setup my tasks.json and launch.json as per the doc here:
https://code.visualstudio.com/docs/cpp/config-mingw
Here is the sample cpp code:
typedef std::vector<int> v... | I faced the same issue when I installed the MINGW from the site which you have mentioned. Then I installed MINGW from SourceForge mentioned in the wiki and it started working fine. Please have a try once.
|
61,555,376 | 61,555,606 | Get "The application called an interface that was marshalled for a different thread" error while getting content from Clipboard | Aim: Get content from the clipboard using C++/WinRT APIs.
Problem:
Since I'm just testing this API, I tried to code a simple console app with the blocking get() method on Clipboard's async text getter. However, I'm getting the "The application called an interface that was marshalled for a different thread" error when ... | The WinRT clipboard APIs can only be called from a UI thread with a CoreWindow. See notes In the documentation. You can just use the regular Win32 clipboard APIs in your console app.
|
61,555,398 | 61,555,432 | Struct variable is set but not used even though I use it immediately | I am working on a class project that involves simulating a level 1 cache. The project is being done in c++, which I am still not super comfortable with. For the simulator, we need to have a struct to represent the tag array, which I have created within a cache class. I also have a struct of type tag that has different ... | So the error is that you are assigning to a local variable but doing nothing with that variable. It's clear that you expect in
cache::tag_t entry = cache_tag_array.entries[i];
that entry is some sort of alias for cache_tag_array.entries[i] but it isn't. It's a completely separate variable and assigning to entry has no... |
61,556,039 | 61,733,024 | Visual Studio C++ compiler tries to compile CUDA C/C++ files | I am trying to make a project I've been working on use CUDA.
At the moment it has four build configs, two (release and debug) which define a compiler symbol so it compiles with CUDA, and two (release and debug) which instead directs it to CPU code.
This is a short version of main.cpp:
#ifdef CUDA
#include "CUDACode.cu"... | Robert Crovella answered my question in the comments, what I needed to do was have a header function that was included in main.cpp and CUDACode.cu and contained the function prototype for functionDefinedinBothHeaders but CUDACode.cu defined it
|
61,556,061 | 61,556,145 | How can I detect that a template is of pointer type? | I have a couple of problems in my code. The first is in the variable "Element" and it works well for me as long as the constructor of the class that sent the template its variables have default values, is there a way to skip the constructor without putting defaults values in the class? And the other problem is when it ... | namespace Linked{
template <class T>
struct Nodo{
T Element;
Nodo<T> *Next = nullptr;
~Nodo(){
if constexpr (std::is_pointer<T>::value)
delete Element;
}
};
You should also consider if T is pointer to array.
|
61,556,158 | 61,560,153 | Create widgets in panel of Main Frame | first. I created a Panel named DataViewPanel class into AGUIFrame class, i wanna use that Panel class in order to manage a part of GUI Frame.
file.h
class DataViewPanel : public wxPanel
{
public:
DataViewPanel(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPositi... | You need to associate your sizer with the panel, without SetSizer(topSizer) call the sizer is not used and hence all buttons remain superposed on each other in their default location instead of being correctly placed by it.
|
61,556,213 | 61,556,645 | How do I use getline in do-while loop? | #include <iostream>
#include<algorithm>
#include<string>
using namespace std;
struct student {
string name;
int number;
double score;
};
bool compare(const student& a, const student& b) {
return a.score > b.score;
}
int main()
{
// int x = 10;
struct student stu[x];
int i = 0;
/** f... | I suggest the following to make your code safer and use modern C++.
read all data into a temporary variable, so you don't end up with a student namend "quit".
check if each reading was successfull, if not, just exit the loop.
use std::vector and push_back each student instead of relying on a fixed size array.
std::... |
61,556,592 | 61,557,427 | How to get the length of array using strlen()? | I don't understand why I cannot use strlen() to get the length of array. How to debug it?
The main.cpp is:
char* vector_1 = q2_input_source();
The function.cpp is:
char* q2_input_source() {
static char* source = new char[10];
int index = 0;
cout << "enter (ESC) to escape the source-char-program!" << endl;... | while (_getch() != 27 && index < 9)
{
cout << "Input your source_char " << index << " elment: " << endl;
cin >> source[index];
index = index + 1;
cout << endl;
}
source[index] = '\0'; // You need to add a string terminator.
int length = strlen(source);
|
61,556,806 | 61,557,084 | unintended round up double variable c++ | The problem in the principal it is always round up 0.x and the answer is wrong
I'm using code:blocks mingw
please look at this image on transaction 2 it's 99855.7-145.022 but the answer is already rounded up
#include <iostream>
using namespace std;
int main()
{
double x,amort,principalminus,interest,amortbal,th... |
it's 99855.7-145.022 but the answer is already rounded up
you just need to print with more digits, for instance do :
cout << std::setprecision(15);
somewhere before the other print, for that you need
#include <iomanip>
and you will have
pi@raspberrypi:/tmp $ ./a.out
CMP Calculator
Base Principal:100000
MRI:41
Mo... |
61,556,872 | 61,557,059 | which template type to use in MSVC/C++: size_t or int | MSVC seems to be sensitive to the template type. I have a templated function
template<size_t size>
inline double squaredNormOfDiff(const Vec<size>& vec1, const Vec<size>& vec2){
double sum=0;
for(size_t i=0; i<size; i++) {
const double diff = vec1[i] - vec2[i];
sum += diff * diff;
}
return sum;
}
When... | You may need to modify Vec and try again:
template <size_t Size> // change to size_t from int to match the definition of Mat
using Vec = Mat<Size, 1>;
|
61,556,957 | 61,557,030 | C2065 's' undeclared identifier | im asking for help resolving an error :(
my line of code is as follows
// folder name
std::string folder = "logs";
CreateDirectoryA(folder.c_str(), nullptr);
// time format
auto t = std::time(nullptr);
std::ostringstream timefmt;
timefmt << std::put_time(std::localtime(&t), "%Y%m%d_%H%M%S");
... | Maybe your "client_"s raises the issue. Make sure you've used #include <string> and using std::string_literals::operator""s.
|
61,556,988 | 61,557,201 | How to create a variadic function that are recursive with the given pseudo code in C++? | I am trying to make a recursive variadic template function that works in the following example. The example shows no practicality and is only used to help better understand what I'm asking. So, basically I have a function that takes an infinite amount of parameters of the same type and it recursively calls itself with ... | We can forward the arguments in a tuple and decrement the index:
#include <cstddef>
#include <tuple>
#include <utility>
template <std::size_t I, typename Tuple>
void test_helper(Tuple&& tuple)
{
if constexpr (I != 0) {
test_helper<I - 1>(std::forward<Tuple>(tuple));
}
// for example
process(st... |
61,557,074 | 61,557,302 | Pulling data from a structure? | i currently have this code
struct Students {
int studentID;
char firstName[12];
char lastName[12];
char email[25];
};
void showStudentAddMenu()
{
int i;
cout << "How many students would you like to add? (Max 10) ";
cin >> addStudentNumber;
... | From my gesture, you've called all the 10 students struct, since not all of them are filled by the user, it shows some garbage. I've made a dynamic program which reads the limit by the user and defines the arrayed struct.
Look at the following code:
#include <iostream>
const int MAX = 10;
int limit = 0;
struct Studen... |
61,557,332 | 61,561,622 | How to link SDL2 manually in CMake | Recently I have started to learn CMake. To practice, I am trying to link SDL2 manually. I know that there is another way around using find_file which is easy. But I want to do it myself for practice.
I get an error when I try to link the libSDL2main.a file (running the Makefile using cmd mingw32-make)
[ 50%] Linking CX... | If you want to link to the SDL2 libraries directly in target_link_libraries() (without defining IMPORTED targets, or using find_library()), use the full path to each library. The CMAKE_SOURCE_DIR variable provides the full path to the root directory of the CMake project:
target_link_libraries(exe0 PRIVATE
mingw32 ... |
61,557,531 | 61,557,601 | Arduino Code Error for blinking LED with user Input | I am stuck in some compile time error and not getting the solution for it.
This is the code I have made:
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT);
}
void loop() {
Serial.println("How many times you wanna blink the LED?");
String myString;
while(myString.equals("")) {
myString = Serial.readString();... | You can have only one condition in a while loop
Your syntax looks like you wanted to do a for loop:
for (int i = 0; i < mystring; i++) { … }
|
61,557,594 | 61,557,680 | Should I have two headers for both a) all the forward declarations AND b) the public functions | Lets say I have file_a.cpp file where function_a() will be used in file_b.cpp, and function_b(), which will be only used in file_a.cpp. So what I thought of was making file_a_public.h where I declare function_a(), so I can include that in file_b.cpp. And then having file_a_private.h where I forward declare all the func... | You say you wouldn't need the file_a_private.h if you could just define the functions in the right order. But then you could just declare those functions in the right order in file_a.cpp (possibly inside an unnamed namespace) before defining these later on. No need to include the file_a_private.h then.
|
61,558,504 | 61,558,552 | Memeber variable as class variable in C++ how does it happen? |
I have a problem. I am currently working on a small example in c++ and can't figure out the explanation. Here is my problem:
#include <iostream>
using namespace std;
class X{
int& i ; /* int i; */
public :
X(int k=100):i(k){ }
X(`const` X& x):i(x.i){}
void setI(int k){i=k;}
int getI(){cout <<"adresse: "<< &i <<... | Your code has undefined behaviour, it doesn't have to work in any way at all.
Here's the problem
class X {
int& i;
public:
X(int k = 100) : i(k) {}
...
};
k is a local variable, a parameter to the constructor. It no longer exists once the constructor has exitted.
But your code takes a reference to that loc... |
61,558,609 | 61,573,206 | ESP8266 http GET request don't show any value in serial monitor | I have a table in MySQL database inside my local server and I managed to echo that value using a PHP script. Here is the PHP script (I have named it get.php and it is directly inside my htdocs folder in xammp).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
// Create connection
... | I reworked your code to use char arrays instead of String class and changed the decoding logic. It might have flaws though, cause i could not test the logic for your script.If its not doing what you want, uncomment getDebug() and comment getData() upload and post result (starting with ==== DEBUG ====) as edit to your q... |
61,558,875 | 61,561,533 | How do I compare two IloNumArrays in Cplex C++ API? | I want to add constraints to my Cplex model, that ensures that a bunch of arrays are pairwise different. That is, at least one entry should differ in the two.
(To clarify: The IloNumVarArray h represents an n x m matrix and the constraints should ensure that no two rows are identical)
My code below has two errors (at... | you could use logical constraints.
Let me give you an example in OPL CPLEX that you could adapt to C++
int n=3;
int m=2;
range N=1..n;
range M=1..m;
float epsilon=0.0001;
dvar float temp1[N][M] in 0..10;
dvar float temp2[N][M] in 0..10;
minimize sum(i in N,j in M) (temp1[i][j]+temp2[i][j]);
subject to
{
// at lea... |
61,558,931 | 61,560,833 | How dose base pointer address in derived class? | As I know that we could use base class pointer to address and call virtual functions in derived classes, because base class pointer has a more limited pointer scope. But I just want to know, how does base class pointer know where to start in derived class?
For example, for the record A, B and C all HAS there own data m... | The compiler knows the layout, so it will emit code, which will calculate the address of the B subobject in C.
Let's see a simple actual example:
class A { int x; };
class B { int y; };
class C: public A, public B { };
B *get(C &c) {
return &c;
}
In get, the compiler must calculate where B resides in C. Here's an... |
61,558,935 | 61,686,884 | DirectX 12 SDK LNK2001 | I keep getting this link error:
error LNK2001: unresolved external symbol D3D12SerializeRootSignature
even though i have the SDK linked and added to C/C++ and VC++
| I use this line...
#pragma comment(lib,"d3d12.lib")
… in the include file to make sure that the d3d12.lib is visible to the linker.
|
61,559,668 | 61,559,700 | Why program cannot reach proper return instruction after stack unwinding? | Compiler: g++ 9.2.0
Operating system: Windows 10
g++ call:
g++ -E main.cpp -v -o main.i
g++ -c main.cpp -v -o main.o
g++ main.o -v -o main.exe
main.exe
main.cpp:
#include <chrono>
#include <iostream>
#include <string>
#include <exception>
#include <iostream>
//#include <thread>
#include "mingw.thread.h"
struct... |
Why program cannot reach proper return instruction after stack unwinding c++?
Because your code creates multiple threads and you are not catching the exception in the thread which is actually throwing the exception. The exceptions won't be propagated across threads even if you call join() member function of std::thre... |
61,559,765 | 61,559,854 | Checking presence of an element in a list using 2 params and a lambda function in C++ | I'm trying to check the presence of 8 in a list of 1,2,3,4,5 using the any_of
list<int> mylist{ 1,2,3,4,5 };
int arg = 8;
bool is_present = any_of(mylist.begin(), mylist.end(), [&arg,&elt](auto& arg,auto& elt) {return arg == elt; });
cout << "Is 8 present? " << is_present << endl;
But I get error in the lambda... | You are using arg and elt both as capture and parameters of the lambda, using the lamda inside any_of the argument of lambda is implictly a reference to the content of the container so you have to modify your lambda like so:
bool is_present = std::any_of(mylist.begin(), mylist.end(), [&arg](int& elt) {return arg ==... |
61,559,796 | 61,560,107 | custom std::distance implementation | I made "distance" template function for calculating the distance between two iterators. In the function, I divide the cases, one for random access iterator and the other. It detect well the type of iterator with iterator_traits, but I can't use this function with bidirectional iterator.
Here is my distance function
te... | Your problem is that if (typeid(type) == typeid(std::random_access_iterator_tag)) needs to be if constexpr, so that you don't try to compile last - first for non-random access iterators, but if constexpr (typeid(type) == typeid(std::random_access_iterator_tag)) does not compile.
There is, however, an example at cpprefe... |
61,559,941 | 61,561,228 | How to read in values from specific columns in a CSV file to perform calculations - C++ | so I'm trying to read in some data from a csv file into my program, but I only want some specific columns. I know there is a lot of stuff online regarding this but I can't seem to fit any of them to my requirements.
Firstly, I have created a struct that takes in Date and Time (class objects) and a Speed value from a fi... | What you can do here is write a stream extraction operator for your struct WindLogType that you use to read the file one line at a time, extracting the information you need from the line and populating the struct.
std::getline can be used to not only read a whole line, but also tokenise your string using a delimiter.
H... |
61,559,974 | 61,560,170 | Is there a way to combine two variables? | I have been trying to get my code to dynamically allocate class objects to file to later read but having trouble with getting user input to save into each different object.
I'm trying to have the user input their names, ages and phone numbers and have it save to file where it can be read later hopefully using the same ... | You can make use of std::vector in the following manner:
std::vector<Student> my_students;
for (std::size_t i = 0; i < 3; i++) {
Student tmp;
in >> tmp;
my_students.push_back(tmp);
}
|
61,560,211 | 61,560,333 | PostMessage Not working with allocated console in winform app | SO I got a c++/cli form app which has a checkbox(debug in chinese) with the name of checkBox3 inside my app:
This is the code of the checkbox:
private: System::Void checkBox3_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
//set the debug flag
g.debug = !g.debug;
HWND allocatedC... | Try sending a WM_SYSCOMMAND message with wParam = SC_CLOSE. This more closely mimics selecting 'Close' from the system menu.
|
61,560,227 | 61,561,469 | macOS Catalina 10.15 xcode openGL not running window? | I am working on a c++ project with openGL on Xcode, my code is build successful. But there is no display window?
My Xcode settings here;
My first post - > Here
I need help, and my codes;
#include"GL/glew.h"
#include"GL/freeglut.h"
#include<iostream>
#define GLEW_STATIC
void display(void) {
}
int main(int argc, char ... | I research and find it. You need the XQuartz for running windows.
Visit this web site : https://www.xquartz.org
Download and install it.
It's working for me.
|
61,560,361 | 61,560,508 | ("vector subscript out of range") for Binary search problem | I am trying to implement binary search function in C++, in this function I have sorted vector of integers, then I enter vector of integers to check the index of the value I am searching for, If value is not found -1 should be returned
The problem is I receive message _DEBUG_ERROR("vector subscript out of range"); while... | There are 2 problems with this code:
In the binary search function, you start with assigning your parameters with new values, which will lead to infinite recursion. Just remove this assignment.
Your mid is assigned like this int mid = (left + ((left - right) / 2)); but should be this: int mid = (left + ((right - left) ... |
61,560,855 | 61,578,690 | Unable to Gain input when loop terminates | Hi All ham trying to count the number of words and characters etc.. for a project, however, in the line where I input ^D to terminate input, that line is not counted in the words characters etc..
Any line where the input terminates it does not count. Furthermore, for some reason it does not print the statements at the... | the following proposed code:
performs the desired functionality
cleanly compiles
implements a state machine with 2 states
on LINUX, recognizes <ctrl-d> as end of input, which must be the first character on a new line
incorporates a switch statement to keep each 'activity' clearly recognizable
uses appropriate horizont... |
61,561,306 | 61,561,481 | C++20 support in Visual Studio | I'm wanting to use std::format but Visual Studio says the std namespace has no member format.
It appears this is new for C++20. Is there a way to make it available?
| As of the time of writing, no C++ standard library implements std::format.
There are various implementations available on the web, like https://github.com/fmtlib/fmt (presumably the original source of the proposal, in fmt::) and https://github.com/mknejp/std-format (which puts everything in std::experimental::).
I woul... |
61,561,991 | 61,565,306 | 919B | nth Numbers having digit sum as 10 | Codeforces | Here is the link to the question. Essentially, it asks to find the kth number having digit sum as 10. I have tried multiple solutions and also looked upon solutions online. Specifically this one (also shared below). The one with constant time talks about outliers in Arithmetic Progression and uses it to find the nth nu... | Here is a Python solution that you can translate into C++.
cached_count_ds_l = {}
def count_digit_sum_length (s, l):
k = (s, l)
if k not in cached_count_ds_l:
if l < 2:
if s == 0:
return 1
elif l == 1 and s < 10:
return 1
else:
... |
61,562,051 | 61,562,655 | C++ SFINAE for array/vector | I want to make an overloaded operator << which is only used by containers (array/vector).
I have the following template:
namespace reachability {
template <typename Container>
ostream& operator<<(ostream& out, const is_container<Container>(&container)) {
string result = "{";
for (values_t elem ... | If you want to get compile-time error at declaration of your function, not when the body of that function template is being instantiated, you make SFINAE by adding another template parameter whose syntax is checked and if it doesn't make any sense, compiler will tell you about it by saying no matching function for call... |
61,562,094 | 61,562,711 | Threading in member of a singleton C++ | I have been checking on how to work with threads and I have found some answers here and basically you need to pass to the calling thread the object and the function to thread, but in a simple singleton I havent been able to make this simple piece of code to work.
class TestManager {
private:
TestManager() { /*con... | Thanks to @Alex F
ThreadTestAllRelays is static, no need to use instance parameter for thread. – Alex F
Fixed!, so that line would be:
std::thread testManagerThread(&TestManager::ThreadTestAllRelays,mSecsPerRelay);
|
61,562,344 | 61,562,451 | Why do I get a SIGABRT error while using bitset in stl? | The following code is running perfectly well with my g++ compiler. But on submitting it on an online judge, gives SIGABRT error. I read that stl elements can generate this error if they try to access too much memory. I cannot see any such use of memory. Is it the count? I have implemented my own count, but it still giv... | Just skimming the source code, this is what I see:
#define M 100
...
bitset<100> houses;
Seems like you want to use M instead of 100 for safety.
Then here:
if(upper > 100) upper = 99;
This is going to break at upper = 100 Suggest:
if(upper >= M) upper = M - 1;
|
61,562,820 | 61,562,954 | How do I move-append one std::vector to another? | Suppose I have an std::vector<T> from and std::vector<T> to where T is a non-copyable but moveable type and to may or may not be empty. I want all elements in from to be appended after to.
If I use the std::vector<T>::insert(const_iterator pos, InputIt first, InputIt last) overload (4) with pos = to.end(), it will atte... | insert will work fine with std::move_iterator and std::make_move_iterator helper fucntion:
to.insert(to.end(),std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
|
61,563,013 | 61,563,263 | making second argument of std::pair a custom class | I am implementing a Node class in C++ as an assignment.
The class :
#pragma once
#include <iostream>
class Node {
size_t id;
std::pair<size_t, Node> dist;
public:
//Node();
//Node(const size_t);
Node(const size_t, const std::pair<size_t, Node>);
Node(const Node&);
//std::pair<const bool, co... | std::pair<size_t, Node> dist;
This member declaration requires that Node is fully defined at the point of declaration, which it isn't. This is what the error is telling you.
Also, what you are trying to do is impossible. What should the memory layout of an instance of Node look like? An instance of Node has a dist mem... |
61,563,235 | 61,563,504 | "Use of deleted function" when calling `std::unique_ptr` move constructor? | I'm facing a compilation issue when defining a function that takes a move reference to a std::unique_ptr object.
#include <memory>
class foo {
public:
foo() { /* */ };
};
void function(foo&& arg) {
foo bar(arg);
}
void function2(std::unique_ptr<foo>&& arg){
std::unique_ptr<foo> foo(arg);
}
int main(i... | For safety reasons, some restrictions are imposed. A named variable will never be considered to be an rvalue even if it is declared as such. To get an rvalue, the function template std::move() should be used. Rvalue references can also be modified only under certain circumstances, being intended to be used primarily wi... |
61,563,364 | 61,563,962 | I'm having problems looping a function | funtion
I have been trying too loop the "1 + 1/3 + 1/5 + ... + 1/n" part in the screenshot inside my code but could not do it all.
The compiler calculates 'x' which is the factorial correctly the only problem for me now is looping the fractions in the function.
int main()
{
int i=1,n,x=1; //x : factorial
double f;
co... | Here is your answer
#include <iostream>
using namespace std;
int main()
{
int n;
double f = 1;
cout<<"Enter an odd number : "<<endl;
cin >> n;
if ( n%2 == 1)
{
double temp = n;
while ( temp > 1 ) // this one calculates factorial,
{
f *= temp;
... |
61,563,398 | 61,563,478 | Value behind a pointer changes by printing it | I want to build up a simple binary-tree in C++ using pointers for each node pointing to the left child and to the right child. I set the root of the tree manually, then I add one number to the tree, but by printing its value in the main() the value of the variable behind the pointer changes its value.
#include <stdlib.... | You are assigning pointers to non-static local variables.
Non-static local variables will be invalid on returning from the function.
You should dinamically allocate the nodes instead.
In the other words, you should use
Node* newNode = new Node;
newNode -> data = newData;
node -> rightNode = newNode;
instead of
Node ne... |
61,563,455 | 61,568,765 | Defining custom MPI type based on preprocessor directive | Just a quick question regarding MPI datatypes, I want to offer both single and double precision support which I do through preprocessor directives. For my sequential program I do
#if defined(USE_SINGLE_PRECISION)
using floatT = float;
#elif defined(USE_DOUBLE_PRECISION)
using floatT = double;
#endif
Naively I thou... | MPI_FLOAT and MPI_DOUBLE are not types (like float or double), but "variables" of type MPI_Datatype, so the C++ using syntax cannot be using here.
FWIW, MPI_Datatype is an opaque type that is implemented as
an int in MPICH and its derivatives (and MPI_FLOAT is a hardcoded integer)
an opaque pointer in Open MPI
A port... |
61,563,731 | 61,564,240 | Getting a string from QGraphicsSimpleTextItem from QGraphicsItem foreach loop? | I am making an image annotation system Using qrect and Simple text items.
I am trying to store the string values from the QGraphicssimpletext items into a JSON file to save and load the annotation boxes. The rectangles work fine but I cannot understand how to get a string value. This is the foreach I am trying to loop ... | You have to cast and verify that the pointer is not null:
// ...
arrayPosY.push_back(item->y());
if(QGraphicsSimpleTextItem* text_item = qgraphicsitem_cast<QGraphicsSimpleTextItem *>(item)){
arrayAnnotation.push_back(text_item->text());
}
|
61,563,766 | 61,563,987 | C++ threads. Why always executes last thread? | Why only last threads executes every time? I'm trying to divide grid into N workers, half of grid always not touchable and other part always proceed by 1 last created thread. Should I use an array instead of vector? Locks also do not help to resolve this problem.
#include <iostream>
#include <unistd.h>
#include <vecto... | [&start, &end, &x, &grid, &t, &nwork, &threads]
This line is the root of the problem. You are capturing all the variables by reference, which is not what you want to do.
As a consequence, each thread uses the same variables, which is also not what you want.
You should only capture grid and threads by reference, the o... |
61,563,950 | 61,564,050 | out_of_bounds: basic_string C++ | I have to do a program, that takes parameters from the command line and makes the sum of N elements using the formula A(i)*x^(i). The Parameters from the command line are in the following sequence: x, n, A0....An. Function polynom() works, but function PrettyPrint() doesn't. It's purpose is to put a thousand separator ... | This part
while(i>=0){
i -= 2;
numString = numString.insert(i,",");
}
is wrong because you are using i after subtracting and before checking.
Adding checking will eliminate the problem.
while(i>=0){
i -= 2;
if (i > 0) numString = numString.insert(i,",");
}
|
61,563,961 | 61,566,452 | Move constructor not inherited nor default generated | I tried extending std::ifstream with one function to make it easier to read binary variables, and to my surprise, with using std::ifstream::ifstream; the move constructor is not inherited. Worse yet, it is explicitly deleted.
#include <fstream>
class BinFile: public std::ifstream
{
public:
using std::ifstream::ifs... | The issue is that basic_istream (a base of basic_ifstream, of which template ifstream is an instantiation) virtually inherits from basic_ios, and basic_ios has a deleted move constructor (in addition to a protected default constructor).
(The reason for virtual inheritance is that there is a diamond in the inheritance t... |
61,564,006 | 61,564,829 | Compilation error while using reduce() and std::execution in C++ | I am trying to implement a simple use-case reduce() and std:: execution. I am using C++ 17 standard for the following code. However, the following code still does not get compiled.
#include <iostream>
#include <numeric>
#include <vector>
#include <algorithm>
#include <execution>
int main() {
std:: vector<int> vec(... | You need to link against TBB, as it is a dependence of the parallel STD (see
C++17 STL Parallel Algorithms - with GCC 9.1 and Intel TBB on Linux and macOS):
g++ --std=c++17 a.cpp -ltbb
And make sure you have at least GCC 9.1 installed.
|
61,564,027 | 61,564,104 | Why is this working? I cannot understand the logic of this swapping | int main() {
// Complete the program
string a,b;
getline(cin,a);
getline(cin,b);
cout<<a.size()<<" ";
cout<<b.size();
string c=a+b;
cout<<endl<<c;
swap(a[0],b[0]);
cout<<endl<<a<<" "<<b;
return 0;
}
void swap(string s1,string s2){
string temp=s1;
s1=s2;
s2=temp;... | This is almost certainly due to the fact that, somewhere in code that you have not shown us, you have this line (or something very similar):
using namespace std;
With this line included, then that very namespace std defines a function as follows:
void swap(_Ty& _Left, _Ty& _Right);
Where the _Ty template is replaced ... |
61,564,067 | 61,564,244 | Contain templated data without using templated class | I have the following basic structure:
template<typename T>
class A {
T data;
};
class B {
A data; // no template parameters
};
The data in class B can have any template parameters, but I do not want to template B, which would be one way to fix the fact that the declaration of A data has no parameters.
Is ther... | Not a straight forward way, but you can do it using std::any(which required c++17 or later support) as the member of B class.
#include <any>
#include <type_traits>
template<typename T>
class A {
T data;
};
// traits for checking template class instance of A
template <typename T> struct is_class_A : public std::fa... |
61,564,273 | 61,564,852 | The difference between adding a char to a string vs a string to char | What is the performance difference between:
string s="";
//stk is std::stack<char>
while(!stk.empty()){
s+=stk.top();
stk.pop();
}
reverse(s.begin(),s.end());
and
while(!stk.empty()){
s=stk.top()+s;
stk.pop();
}
Why is t... | s+=stk.top(), which in this case is equivalent to s.push_back(stk.top()), has amortized constant time complexity. s=stk.top()+s, is essentially equivalent to s.insert(s.begin(), 1, stk.top()), which is linear in the length of s.
|
61,564,384 | 61,564,761 | How to parse in this file in c++ dealing with spaces and new lines? | Credit 1 2 150 12345678 10-10-2020 123
Cash 2 3 199 200 1
Check 1 3 100 111000614 124356499
Credit 2 1 50 987654321 10-10-2021 321
I am trying to read in this file in c++ but I can't figure out a proper way to do it. I need to read in each individual data point into different vectors. For example in a vector called tr... | Spaces and newlines are classified as (white)space in C++, see std::isspace. std::istream& operator>>(std::istream&, T&) skips all whitespace, so that no special handling for spaces or newlines is required.
One example:
#include <iostream>
#include <string>
#include <vector>
struct Date {
unsigned yyyymmdd;
};
st... |
61,564,481 | 61,579,366 | vkQueueSubmit blocks when using timeline semaphores | I need to run a function on CPU between two GPU batches. For this I use timeline semaphores. As far as I know, vkQueueSubmit does not block. However, it blocks when I submit these GPU batches:
uint64_t host_wait = timeline;
uint64_t host_signal = ++timeline;
uint64_t wait0 = timeline;
uint64_t signal0 = ++timeline;
ui... |
Doing something odd like submitting a batch with no work is far more likely to be the cause.
The spec doesn’t have performance requirements. The fact that something is legal does not make it a good idea. Broadly speaking, if there are two ways to do a thing, do it the obvious way. And sending an empty batch isn’t exac... |
61,564,623 | 61,565,726 | boost::static_visitor as Map Value | I'm trying to create a lookup table for ints to a boost::static_visitor
using VariableValue = boost::variant<int, double, std::string>;
struct low_priority {};
struct high_priority : low_priority {};
struct Mul : boost::static_visitor < VariableValue>{
template <typename T, typename U>
auto operator() (high_p... | You'd be slicing. You need dynamic allocation. The quickest way is to use type-erasure.
The trick is to come up with a fixed statically known prototype. In this case, a binary function would be it, and you can add the apply_visitor dispatch to the Mul object:
Live On Coliru
#include <boost/variant.hpp>
#include <functi... |
61,565,074 | 65,471,238 | Is it safe to use a boost::signals2::scoped_connection object as member of a class for automatic connection lifetime? | I wondered whether the following code is safe with respect to the fact that the signal might be triggered by a different thread:
using IntSignal = boost::signals2::signal<void(int)>;
class Foo
{
public:
Foo(IntSignal& signal)
: some_resource(new int(0))
{
scoped_connection = signal.connect([this](int i) {... | You are right, there is a possible race if Foo's destructor is invoked while the signal is running and accessing some_resource.
A safe solution would be to extend the life of Foo while the slots are running:
class Foo : public std::enable_shared_from_this<Foo>
{
public:
Foo(IntSignal& signal)
: some_resource(new... |
61,565,536 | 61,565,669 | How to apply alignment to colored text in c++ output | I am trying to align my output with setw and left in c++ as follows:
string s[] = {"S1", "S2", "S10", "S4", "S5", "S11", "S3", "S7"};
for (int i=4; i<=11; i++) {
for (int j=0; j<8; j++) {
if (j%2==0) {
cout << setw(8) << left << s[i-4];
} else {
cout << setw(8) << l... | If you have strings that you both, want to format, as well as add color codes, then you can do this easily by streaming the color code sequences before you stream the formatted text. This way, the color codes and the alignment won't interfere with each other:
std::cout << "\033[1;31m" << std::setw(8) << std::left << s... |
61,565,796 | 61,566,037 | How to iterate through list of derived function objects and accessing derived objects member variables | I have a function object definition:
struct BaseFunctor
{
std::string desc = "Not this one!";
virtual double operator()(double a, double (*func) (double)) = 0;
};
and a set of derived function object definitions:
struct DerivedFunctor1 : public BaseFunctor
{
std::string desc = "Yes this!";
virtual doub... | Your derived classes define another member named desc in addition to existing BaseFunctor::desc.
What you rather need is to initialize BaseFunctor::desc with the correct string. Example:
#include <iostream>
#include <memory>
#include <vector>
struct BaseFunctor {
std::string const desc;
virtual double operator... |
61,565,896 | 61,565,993 | How to move stack object into std::shared_pointer without instantiation | Question
Hi there. I have a bit weird question. Suppose you have a non-copiable stack object, which you have gotten from an external library. How is it possible to move the content into a heap object allocated by std::make_shared without actually instantiating the class?
class my_class {
private:
my_class(my_class co... | It can be done. No tricks needed. Just move the object:
shared_pointers_container.insert(std::make_shared<my_class>(getMyClassObject()));
// or if you need to start from `obj`:
my_class obj = getMyClassObject();
// work with obj
shared_pointers_container.insert(std::make_shared<my_class>(std::move(obj)););
On your ... |
61,566,007 | 61,566,189 | A case od the most vexing parse | My code keeps giving me error Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'const bus') Is this a case of the most vexing parse? if so how to fix it. I am trying to print out objects stored in vector. std::vector<bus> v = {} is my vector to contain the object whereas bus is... | There is no vexing parse here. You simply need to overload the stream insertion operator for the bus type. Since bus only has public data members, this can be a non-friend function:
std::ostream& operator<<(std::ostream& stream, bus const& b)
{
stream << "#" << b.carNum << " Year" << b.releaseYear;
return stream;... |
61,566,032 | 61,566,198 | Error message type int is unexpected while I initialized the variables | I am new in C++.
I searched for some similar questions on Web,
Unfortunately, I have not found an answer to my question yet.
I used Visual Studio Code as my compiler,
and earlier I thought maybe something is outdated,
but I ran this code on an online-coding test editor,
it did not work either.
So I guess the issue may... | This
int i2 = 0 , i3 = 0 , i5 = 0; //initialize to 0
or this
int i2 = 0 ; int i3 = 0 ; int i5 = 0; //initialize to 0
Your version is half way between, but not legal.
|
61,566,077 | 63,022,737 | std::arg returns an incorrect value for real inputs (using MSVC compiler) | I'm trying to do some simple phase calculations in C++ and discovered that I was sometimes getting the wrong results from std::arg when using real values as input.
According to the documentation on cppreference:
Additional overloads are provided for float, double, long double, and all integer types, which are treated ... | I created a bug report and it turns out there was a bug in the MSVC standard library. It has been resolved now as of VS 2019 16.7 Preview 2!
|
61,566,205 | 61,566,463 | Is there another way to prevent a derived method from superclass being called instead of the base class one, like with a keyword or something? | As I am practicing C++ with some of my colleagues, one of them "experienced a bug" within a derived class. Long story short, he was calling the base method (callFoo) and he was expecting to be calling A::Foo(), but he got B::Foo() instead.
Here's a complete example of what I am actually asking. I don't really know how ... | It is clear that you are creating an object of Derived class and trying to invoke callFoo() function present in the base Class.
I will try to visualize this step by step :
B mB ---> Since we are creating an object of Derived class , the VPtr will point the to the Vtable of Derived Class.
mB.callFoo(); ---> the Vptr ... |
61,566,864 | 61,566,899 | How do I loop my program to continuously ask for a letter until the user enters a Q to end the program | I realized after I was done that I needed to loop it until they type q, Im not sure how to do it though. What I'm looking for is until the last option (‘q’ or ‘Q’) is selected, the main program comes back at
the beginning, asking the user to insert a letter.
#include <ctime> // For time()
#include <cstdlib> // For ... | You can put your code in a while loop like this:
int array[5];
int i, num, x;
char c = '\0';
float average = 0;
srand(time(0)); //This makes the set of numbers differnet every time
for (i = 1; i <= 5; i++)
{
array[i] = (rand() % 5) + 15;
}
while (c != 'q')
{
cout ... |
61,566,936 | 61,567,313 | Constructing std::pair of integers with a variable using post-increment | I tried constructing pairs of integers where the second integer is greater than the first by 1:
1 2
2 3
3 4
Using both std::make_pair and the constructor like so:
std::make_pair(n, n++);
However, this results in the pairs being in reverse:
2 1
3 2
4 3
If I was to put the post-increment on the first parameter or use ... | From cppreference:
When calling a function (whether or not the function is inline, and whether or not explicit function call syntax is used), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of... |
61,567,249 | 61,567,362 | temporarily cast a unique_ptr to a raw pointer | I have a question regarding smart pointers.
Is it possible to temporarily cast a smart pointer to a raw pointer?
For example:
std::vector<std::unique_ptr<monster>> all_monsters to std::vector <monster*> all_monsters;?
I have been looking everywhere on the internet but can't find a method
I have a std::vector <monster*>... | You can certainly get a single raw pointer from a single std::unique_ptr, using the get() member function.
But you cannot safely cast a std::vector of one type to a std::vector of a different type.
So if the other function's interface can't be changed, you'll unfortunately need an extra step to build its vector argumen... |
61,567,338 | 61,567,449 | how to use a setter for vector of an object | std::vector<Game*> games;
I have the following setter:
void Instructor::setGames(const std::vector<Game *> &value)
{
games = value;
}
And I am trying to use it like this:
Game g1, g2, g3;
std::vector <Game> gameSet;
gameSet.push_back(g1);
gameSet.push_back(g2);
gameSet.push_back(g3);
i.setGames(&... | Given that you have a vector of Game pointers, that is the type of object it will accept, therefore g1, g2 and g3 must be pointers:
Game *g1, *g2, *g3;
std::vector <Game*> gameSet;
g1 = new Game(); //intialize pointers
g2 = new Game();
g3 = new Game();
//...
i.setGames(gameSet);
Live demo
Note that using raw pointers... |
61,567,367 | 61,567,455 | C++ : Allocate a big variable-sized 2d-vector on the heap | (If my question is stupid,it is because i am a student)
In my program when i declare my big vector i get "stack overflow"
cin >> big_number;
vector<int> my_vector[big_number];
** stack-overflow** ...
(note: in the example above the big_number can take values up to 1.000.000)
In my understanding,this happens beca... | You should use vector<vector<int>>
Code would look like
std::cin >> big_number;
std::vector<std::vector<int>> my_vector(big_number);
This will create a vector containing big_number of empty vector<int>
|
61,567,439 | 61,567,759 | Why is my simple `main` program's ELF header say it's a `DYN (Shared object file)` instead of an executable? | Here's a very simple C++ program:
// main.cpp
int main() {}
My Makefile generates the following command to compile the program.
❯ make
g++ -O0 -fverbose-asm -o main main.cpp
I check with the command file to see it's an ELF executable:
❯ file main
main: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamic... | Executables that are as compiled as "position independent executables" (with -pie/-fPIE) should be relocated to a random address at runtime. To achieve this, they use the DYN type.
Your version of g++ was configured with --enable-default-pie, so it sets -pie and -fPIE by default. You can disable this, and generate a no... |
61,567,585 | 61,567,622 | How can I modify a char* in DLL? | When I pass a char* as a parameter to a DLL, I can get a new char* when I "return" a char* from DLL, but I can't get it done when I just use that char* parameter and return nothing.
This DLL function is OK, seems I can pass a char* to DLL.
void getStr(char *str){
print("%s\n", str);
}
This is OK, too. It seems I ca... | To modify given string buffer, modify given string buffer.
void setStr(char* str) {
char tmp[] = "From DLL";
int len = strlen(tmp) + 1;
memcpy(str, tmp, len);
}
int main()
{
char tmp[] = "Hello World!";
setStr(tmp); // I hope I can get "From DLL" here.
std::cout << tmp;
}
To modify the pointe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.