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 |
|---|---|---|---|---|
62,530,959 | 62,531,367 | Trying to concatenate array of c-strings with delimiter | Here is my code
int main(int argc, char *argv[]) {
char const *strings[10] = {"dhh", "aci", "cdh"};
join_def(strings, 'l');
return EXIT_SUCCESS;
}
// part 1 read lines
void join_def(char const **strings, char delim) {
char *t = new char[100];
//int length = 0;
t[0] = '\0';
int x = sizeof... | First, you cannot determine the number of elements in an array passed to a function, as that array will decay to a simple pointer. So, your sizeof(strings) expression will evaluate (at compile time) to the (fixed) size, in bytes, of a pointer. For the function to be 'aware' of how many elements there are in an array, i... |
62,531,124 | 62,533,723 | Error: "reference to non static member function must be called" not getting resolved when using classes | I am trying to solve a question, where I have a 2d array of n x 2 . I want to sort the array by second column. I don't want to use manual sorting, and rather I am trying to use STL.
My issue: I am getting the error: "reference to non static member function must be called"
I tried declaring the function, structure outsi... | The sort algorithm in your case needs "function object" (instance of object having operator() or pointer to function), which accepts references to 2 comparing vectors and returns bool, for example:
// function out of class scope
bool compVectorBySecondElt(const vector<int>& first, const vector<int>& second) {
retu... |
62,531,555 | 62,535,374 | Is it a defect in basic.def.odr section | struct S { static const int x = 0; };
int main(){
S obj;
int v = obj.x;
}
Consider the above code, Is obj.x an odr-use? According to look at the section of basic.def.odr#3
A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion to... | You can’t rely on a compiler to tell you whether it’s an odr-use; if it is, and you haven’t defined the variable, the program is ill-formed, no diagnostic required. That said, it seems like this was a defect in C++17 in that the possibility of referring to a static member variable with a class member access (as oppose... |
62,531,591 | 62,532,201 | C++ syntax difference: 2D- and 1D-arrays (pointer arithmetic) | Problem
I am learning C++, and am writing code to transpose a 2D array and to reverse a 1D-array.
Please look at the invocations. Why do I have to use reverse(arr, 4) for reverse, whereas I have to use transpose(*in_matrix, *out_matrix) for transpose?
There are two ways of writing each function signature. Both seem to ... | In C, arrays and pointers are a bit intricately mixed up. An array can be considered as a pointer with some 'size' information attached to it (that is not stored anywhere, but the compiler knows). Hence, sizeof when used on an array gives you the size of the contents of the entire array, while on a pointer, it gives th... |
62,531,719 | 62,540,760 | Is there a way to generate a sequence that includes squares which sum up to an integer square? | decompose(11) must return [1,2,4,10].
Note that there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10².
For decompose(50) don't return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn't form a strictly increasing sequence.
I created a function but in only some ... | Here is a simple recursive approach, basically exploring all the possibilities.
It stops once a solution is found.
Output:
11 : 1 2 4 10
50 : 1 3 5 8 49
And the code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
bool decompose_dp (long long int sum, long long int k, std::vec... |
62,531,882 | 62,539,047 | is there a way to detect chinese characters in c++ ? (using boost) | In a data processing project, i need to detect split words in chinese ( words in chinese dont contain spaces).
Is there a way to detect chinese characters using a native c++ feature or boost.locale library ?
| Here is my attempt using only boost and standard library:
#include <iostream>
#include <boost/regex/pending/unicode_iterator.hpp>
#include <functional>
#include <algorithm>
using Iter = boost::u8_to_u32_iterator<std::string::const_iterator>;
template <::boost::uint32_t a, ::boost::uint32_t b>
class UnicodeRange
{
... |
62,532,575 | 62,550,680 | Make /usr/bin/ld: cannot find local library | In my project I got a local library I am shipping with the project.
For that reason I included in the cmake file
LINK_DIRECTORIES(bls/build/src)
INCLUDE_DIRECTORIES(bls/src)
LINK_DIRECTORIES(bls/build/contrib/relic/lib)
INCLUDE_DIRECTORIES(bls/build/contrib/relic/include)
INCLUDE_DIRECTORIES(bls/contrib/relic/include)... | Thanks to the helpful comments leading me into the right direction I was able to get this to run:
INCLUDE_DIRECTORIES(bls/src)
INCLUDE_DIRECTORIES(bls/build/contrib/relic/include)
INCLUDE_DIRECTORIES(bls/contrib/relic/include)
add_library( blstmp STATIC IMPORTED )
set_target_properties( blstmp PROPERTIES IMPORTED_LOCA... |
62,532,676 | 62,532,841 | Is sprintf(b, "%") defined? | I have encountered some code doing this:
double a(30.0);
char buff[30];
sprintf(buff , "%.4f%", a);
std::cout << std::string(buff) << "!\n";
Basically I was wondering about the trailing %, is sprintf() defining what would happen if nothing follows a % ?
| I believe it leads to undefined behaviour.
C11 Section 7.21.6.1 paragraph 4 says:
After the %, the following appear in sequence:
[...]
— A conversion specifier character that specifies the type of conversion to be applied.
Later, paragraph 9 says:
If a conversion specification is invalid, the behavior is undefined.
... |
62,532,735 | 62,535,699 | Convert const char* to const char_type* at compile time | Consider the following code:
using char_type = /*implementation defined*/;
void foo(const char_type*);
int main()
{
foo("Hello World!");
}
The string literal "Hello World!" is a const char* that, depending on the implementation, may not be convertible to const char_type*. I want my code to be portable between di... | This conversion is possible through a two-step process: first, by declaring a class that can convert a const char * to a char_type array within a compile-time constructor; second, by using that class within a user-defined literal:
#include <algorithm>
template<std::size_t N>
struct string_convert {
char_type str[N... |
62,532,956 | 62,541,767 | Writefile() fails to write data depending on length of data | I have created a function to write raw data to a USB drive: write(int size,wchar_t data[]). data is the data to be written and size is the length of the data.
bool write(int size, wchar_t data[])
{
HANDLE hDevice = INVALID_HANDLE_VALUE; // handle to the drive to be written
hDevice = CreateFile(
G... | You have to write whole sectors at a time. That means writing to an offset that is an even multiple of the drive's sector size, and writing blocks of data to that offset which are multiples of the sector size.
If your data is not an even multiple of a complete sector, you still have to write a whole sector. Calculate ... |
62,533,265 | 62,534,300 | I have made recurrence relation which finds the longest contiguous common string between two strings how can i skip one char in my one of the string | int lcs(int i, int j, int count)
{
if (i == 0 || j == 0)
return count;
if (X[i-1] == Y[j-1]) {
count = lcs(i - 1, j - 1, count + 1);
}
count = max(count, max(lcs( i, j - 1, 0), lcs( i - 1, j, 0)));
return count;
}
For example:
The X contains AABB a... | Assuming you use std::string, you can remove a character from a string via its erase:
std::string A{"AACB"};
std::string copy = A; // make a copy to keep the original
copy.erase(2); // erase character at pos 2
std::cout << copy; // prints AAB
If you don't know which character to remove in advance, you can... |
62,533,438 | 62,571,237 | Unit testing of custom Assert function using Google Test | I am using Boost.Assert library, and have this custom assert code, which needs to be unit tested using Google Test framework:
#include <boost/assert.hpp>
#define ASSERT(expr) BOOST_ASSERT(expr)
#define ASSERT_MSG(expr, msg) BOOST_ASSERT_MSG(expr, msg)
namespace boost {
inli... | The problem is solved with the following line:
EXPECT_DEATH(assert_death_test(), "Expression '.*");
My main issue was not creating a vaild regex string, as pointed out by @Quarra.
EXPECT_DEATH is also more appropriate, as ASSERT(...) kills the program.
|
62,533,577 | 62,551,015 | Triggering event of C++ dll in unreal engine | I am trying to use dll which reads incoming messages with a thread.Importing into unreal engine with Blueprint class, As I can't get the incoming messages. I am planning to have a event in the dll for which I'll put event handler in unreal engine code.
Can you please help me, Is this possible If it is how to work with ... | In dll code
EventCallback OnEvent = NULL;
DLL_EXPORT void WINAPI SetEventCallback(EventCallback func)
{
OnEvent = func;
}
DLL_EXPORT void WINAPI FireEvent()
{
if (OnEvent)
OnEvent();
}
In Unreal engine code
typedef void(*_getSetEventCallback)(EventCallback);
_getSetEventCallback m_getSetEventCallbac... |
62,533,672 | 62,533,749 | Why can I use printf() when including iostream? | This piece of codes works fine even with minGW compiler under C++11 standards:
#include <iostream>
int main(int argc, char const *argv[])
{
printf("haha");
return 0;
}
Why should this work? I didn't include stdio.h but I can use functions like printf() and rand(). Are they included in iostream? At least I did... | It's implementation defined if that works or not.
The implementation may include additional headers it needs, but you as a developer should not rely on that and include cstdio too which is the guaranteed way to get access to std::printf.
Including stdio.h puts printf in the global namespace and that is usually not what... |
62,533,677 | 62,545,492 | How to debug an external process under C++ Builder? | I have a DLL that is written in C++ Builder. The DLL is built with "debug info" on.
I cannot run and debug this DLL from the IDE because it is loaded dynamically as a plugin in another process (main exe). My DLL needs to be copied into the main exe's folder first.
So, I attached the IDE to that process but I don't know... |
I have a DLL that is written in C++ Builder. The DLL is built with "debug info" on.
I cannot run and debug this DLL from the IDE because it is loaded as a plugin in another process.
Yes, you can.
Open the DLL project in the IDE, go into the project's Run parameters and set the desired EXE as the project's Host. This... |
62,534,011 | 62,534,192 | A weird question for Tmax(0x7fffffff), why (!x) == x? | #include <stdio.h>
void show_case(int x) {
printf("x + x + 2 = %d\n", x + x + 2);
printf("!(x + x + 2) = %d\n", !(x + x + 2));
}
int main(){
show_case(-1); // the output is 0 & 1
show_case(0x7fffffff); // the output is 0 & 0;
return 0;
}
hi friends, recently I come across a very weird question whe... | Assuming an int is 32 bits, 0x7fffffff is the largest value an int can store. When you then add that value to itself it results in integer overflow which is undefined behavior.
When I run this code, I get 0 and 1 for the second case. This is an example of how undefined behavior can manifest: it works differently on t... |
62,534,801 | 62,535,392 | C++ generate large amounts of random floats(10,000+ numbers) fast | For a project I am currently working on I need to generate a large amount of pseudorandom floating-point numbers, between 0 and 1, in the range of thousands to hundreds of thousands as fast as possible.
What would the best method for this be?
The options I can think of currently are:
C rand(), Quite fast from my exper... |
What would the best method for this be?
Depends on other requirements besides the speed. Does the sequence need to be reproducible? Does the statistical quality of randomness matter? Does the distribution need to be uniform? What processor will you be using to execute the program?
If the speed is the only considerati... |
62,535,058 | 62,535,836 | In which cases does std::optional operator == cause undefined behavior? | Cppreference has the following description of mixed (optional and some other non-optional type) comparison operators for std::optional:
Compares opt with a value. The values are compared (using the
corresponding operator of T) only if opt contains a value. Otherwise,
opt is considered less than value. If the correspon... | This stems from imprecise specification, which has since been rectified.
In C++17, these comparisons were specified as:
Requires: The expression *x == *y shall be well-formed and its result shall be convertible to bool.
Requires was a precondition, so failing to meet these conditions would be undefined behavior. But ... |
62,535,218 | 62,535,279 | Template template parameter and template alias: compiler bug? | I have got problem with the following representative sample code:
template<int I>
struct X {};
template<int I>
struct Y {};
template<int I>
struct XX: X<I> {};
template<int I>
struct YY: Y<I> {};
template<template<int> class TP>
struct traits;
template<>
struct traits<X> {
template<int I>
using Tpl=XX<I>;
... | You need to tell the compiler that Tpl is a template:
template<template<int> class TP>
struct W: Z<traits<TP>::template Tpl> {};
// ^^
Afaik, nothing changed about that, I could be that some compilers are / have been more lax about it and let you get away without it.
The reason it is needed is... |
62,535,564 | 62,535,608 | How to set the boolean value for a c++ class? | I want to know how can I set the boolean value for a class. Ive seen this in other peoples code but I cant figure out how to do it myself.The format will be like this:
class myClass{
//...
};
myClass getClass(){
myClass myclass;
//...
return myclass;
}
int main(int argc, char **argv){
myClass myclass;
myc... | You need to provide a conversion function to bool for your class, like this:
class myClass{
public:
explicit operator bool() const { /* ... */ }
};
It's better to make the conversion explicit to avoid accidental conversions. Using it in an if statement is fine, since that is considered an explicit context.
|
62,535,618 | 62,539,098 | Using a `constexpr` function on a variable passed as lvalue in a non-constexpr function | I am using std::array as the base for representing vectors that have fixed length at compile time, and want to use std::array::size as a constexpr function to disable the calculation of cross product for 1D and 2D vectors.
When I use std::array::size in a non-constexpr function, that takes on my vectors as lvalue argum... | Below, I answer as to why your code doesn't work. Focusing on your use-case: as the others have said, std::array::size is not static, and all std::size does is call that non-static function. Your best bet is to simply add a static size function to your Vector class:
static constexpr auto size() {
return D;
}
Your... |
62,536,268 | 62,536,571 | Unresolved symbol using aruco with opencv4 | I am trying to use the camera pose from opencv. So I'm following this series of tutorial which leads me to include these :
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/aruco.hpp>
#include <opencv2/calib3d.hpp>
Everything wo... | This is happening because you've downloaded a version of the aruco module that is not compatible with your current version of the OpenCV library. The best way to solve it is to compile OpenCV specifying that you want to add the opencv_contrib libraries. To avoid problems let's use the same versions for OpenCV contrib a... |
62,536,819 | 62,537,966 | Insert node at specified custom class iterator position | I'm trying to insert a node at a specified position, the issue is that the insertion happens one position after where I want it. For example:
insert 100 at list.insert(list.begin()++, 100) in 1,2,3,4,5,6,7 results in:
1,2,100,3,4,5,6,7
I thought of decrementing the iterator, then inserting but that would be a workaro... | The problem here in insert:
iterator insert(iterator position, const T& value) {
Node* newNode = new Node(value);
if (position == List<T>::iterator(head_)) {
newNode->next_ = head_;
head_ = newNode;
}
else if (!position.iNode->next_) {
position.iNode... |
62,537,487 | 62,537,580 | Why does std::cout print floats, doubles and long doubles to the same decimal precision? | Intuitively I would think that long doubles have more decimal places than doubles and doubles have more decimal places than floats, however, if so why does std::cout print out floats, doubles, and long doubles at the same decimal precision, even when they have overloads for all primitive data types?
C++ source code:
#i... | Values have a fixed precision depending on the type and you can't change it. It's implementation defined. You can only change the precision of the output and there is just one setting for all types of floats. You can't have different output precision for float, double and long double. The default output precision for a... |
62,537,581 | 62,537,964 | How and where is it possible that a variable does not has an associated name in C++? | In the C++17 standard is stated (emphasize mine):
"A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable’s name, if any, denotes the reference or object."
Source: ISO/IEC 14882:2017 (C++17), §6/6 - "Basic concepts"
Why the "if any"? Can a variable... | As mentioned in the comments,
void foo(int) {}
// ^
defines a variable without a name.
[basic.pre]/6:
A variable is introduced by the declaration of a reference other than a non-static data member or of an object.
It's not a reference obviously, but is it an object? Yes.
[intro.object]/1
An object is creat... |
62,537,760 | 62,537,974 | struct field name conflict with stl array in GDB | #include <array>
typedef struct {
int array;
} tp1;
int main()
{
std::array<int,8> array1;
/*int array=0;*/
/*array ++;*/
tp1 v1;
v1.array = 2;
return 0;
}
When struct has field "array" and the code uses std::array, it seems the 2 "array" are conflicted in gdb. I get syntax error in printing v1.array:
T... |
Not sure why it gets confused.
This is (was?) surely a bug in GDB.
It does not reproduce when using GDB 10.0 on x86_64, while compiling with g++ (Debian 9.3.0-8):
Temporary breakpoint 1, main () at t.cc:12
12 v1.array = 2;
(gdb) n
13 return 0;
(gdb) p v1.array
$1 = 2
Try newer GDB version?
|
62,538,295 | 62,538,343 | Declaration of IntRect SFML | I'm working on a project in SFMLand I would like to set the position of a rectangle on my sprite sheet using a std::pair. In my .hpp I have this attribut.
sf::IntRect _size; which is use to set the width, height, x, y of the rectangle.
In my .cppfile, I've done this.
void Character::setCharacter(const std::string& text... | The error means you're implicitly converting from float to int which can cause a loss of precision.
Explicitly convert the elements from float to int:
_size = {
static_cast<int>(rec.first),
static_cast<int>(rec.second),
static_cast<int>(recc.first),
static_cast<int>(recc.second)
};
Or change rec and re... |
62,538,629 | 62,539,299 | In practice, is there any "lazy" evalution in multiplication with zero in run time | Will the machine or compiler make use of the property that zero multiplied with an integer must always be zero? Consider
int f(int c, int d, int e, int f)
{
// some complex calculations here...
}
int foo(int a, int b, int c, int d, int e, int f)
{
return (a - b) * f(c, d, e, f);
}
In run time, if we pass some... | Compiler
The compiler usually (meaning most compilers) optimizes arithmetic calculations if they consist of constants. For example i = 1 + 3; will be optimized to i = 4; but the more complex the calculation, fewer the compilers that will be able to optimize it. Compilers usually work recursively with tree structures an... |
62,538,734 | 62,539,126 | did in i need in my c++ code to use vectors or learn STL | i need to initialize my code during runtime the program is searching for how many times is the number in multiplication table
#include <iostream>
using namespace std;
int main()
{
int x = 0, n = 1 , count=0 ;
cin >> n>>x;
int arr[n][n];
for (int i = 0; i <n-1 ; i++) {
for (int j = 0; j ... | I think by multiplication table you mean to say matrix.
For this particular problem you don't need even the matrix. You can just do by using a temporary variable. Something like this:
#include <iostream>
int main() {
int n, x, count = 0, tmep;
std::cin >> n >> x;
for (int i = 0; i < n; ++i)
for (int... |
62,538,942 | 62,540,995 | Generate the same sequence of random numbers in C++ from a given seed | I am using mt19937 to generate a random string from a given seed like this:
std::string StringUtils::randstring(size_t length, uint64_t seed) {
static auto& chrs = "abcdefghijklmnopqrstuvwxyz";
thread_local static std::mt19937 rg(seed);
thread_local static std::uniform_int_distribution<std::string::size_ty... | If reproducible "random" numbers are something you care about, you should avoid C++ distributions, including uniform_int_distribution, and instead rely on your own way to transform the pseudorandom numbers from mt19937 into the numbers you desire. (For example, I give ways to do so for uniform integers. Note that there... |
62,538,953 | 62,539,012 | Editing a string to include variables between brackets c++ | I have a string filename which contains the name of a file eg. example.plt. I would like to edit this string by inserting a integer variable between two brackets at the end of the string like so:
example.plt --> example(1).plt
What I've tried is removing the file extension (.plt), adding the brackets with the integer v... | If i is an int, then you need to convert it to a string first, using the to_string method.
filename = filename + "(" + std::to_string( i ) + ")" + ".plt";
As stated by PaulMcKenzie in the comments though, you should be using filesystem to get the file name, extension, etc..
Example:
#include <filesystem>
#include <ios... |
62,538,995 | 62,539,272 | std::adjacent_difference with std::chrono time_point | Consider the following code:
int main()
{
std::vector<std::chrono::steady_clock::time_point> time;
time.push_back(std::chrono::steady_clock::now());
std::this_thread::sleep_for(std::chrono::milliseconds(4));
time.push_back(std::chrono::steady_clock::now());
std::this_thread::sleep_for(std::chrono::m... |
My assumption is that algorithm does not work because result of substracting 2 timepoints is not a timepoint
Indeed, subtracting two time_points does not yield a time_point - it yields a duration. In <chrono>, durations and time_points form an affine space. This is similar to how you cannot add two pointers, but you ... |
62,539,214 | 62,539,343 | How to get the address of the element which is pushed back in the list, In constant time,in c++ stl? | list<int> l;
list<int>::iterator lastElement;
lastElement=l.end()
l.push_back(10);
cout<<"Address of the element 10 in the list is"<<&lastElement<<endl;
Is the above way the correct way to get the address of the last element of a list in constant time. I know there are many other methods but I want a method that gives... |
How to get the address of the element which is pushed back in the list, In constant time,in c++ stl?
After pushing the element, use std::list::back to get reference to the element. Then use the operator & to get the address of the element (or use std::addressof if the operator is overloaded, which is unusual).
Is th... |
62,539,731 | 62,539,778 | std::shared_mutex not scaling with threads doing lock_shared() | I wrote a simple program to test out the performance of std::shared_mutex across a number of threads looping lock_shared(). But from the result, it doesn't seems to scale with more threads added, which doesn't really make sense to me.
You may argue it's because the stopFlag limiting the performance, so the second for l... | Placing a read lock on a shared mutex modifies the state of that mutex. All your threads do nothing but try to change the state of the same object, the shared mutex. So of course this code is going to scale poorly.
The point of a shared mutex is to allow accesses to shared data that is not modified to scale. You have n... |
62,539,822 | 62,540,064 | Clarification needed in c++ erase function | So there was this question in recent programming contest.
we have a test case in that question
8
11001101
Now the output I want is 1 but this line
cout << s.erase(0,6) << "\n"
gives 01 even though i want to remove elements from 0 to 6th index position.
How should i remove elements from 0 to 6 (including 6)
Here is t... | Look at some documentation for std::string::erase. There's an overload that takes a starting index and a count of characters to remove. If you want to erase the first 7 characters then you should do:
s.erase(0, 7)
Just to be clear, the second parameter isn't a position. It's the number of characters to remove.
|
62,539,889 | 62,545,020 | Compile against a outdated explicit instantiation of a template | I use a library (Orocos) which defines its own std::basic_string with a custom allocator. In addition, it explicitely instantiate it:
namespace RTT
{
typedef std::basic_string<char, std::char_traits<char>, RTT::os::rt_allocator<char> > rt_string;
}
namespace std
{
extern template class basic_string<char, char_... | You should be able to add an explicit instantiation definition for the missing member function to your own code (in exactly one source file):
template char* std::basic_string<char, std::char_traits<char>, RTT::os::rt_allocator<char> >::data() noexcept;
This is not strictly conforming in that member function signatures... |
62,540,295 | 62,540,537 | Look up speed of a std::hash_map vs std::vector | In the following code would it be as fast to use a std::hash_map. I assume that the std::hash_map adds the extra step of needing a hash function to the process of looking up, but could the hash function be as fast a vector lookup?
bool isUniqueChars(const string &str){
if (str.length() > 128){
retur... | As with all performance-related questions, you should measure the difference to answer your own question. Fortunately, with this simple code it is easy enough.
Hash data structures have amortized constant complexity, i.e. the average time per operation is constant only if you do many operations. So I expect unordered_s... |
62,540,493 | 62,542,464 | N-Queen Problem: Cannot figure out why my solution is not working | I was having a go at the standard N-Queens problem for an upcoming interview.
I have tried to dry run my code and it seems to work fine. I can't spot the error in my code.
I am traversing it column by column, and using backtracking to recur back from an incorrect path.
Can anyone help me with why this doesn't give me t... | The bool flag variable (used to check if placing a queen at (row, col) would intersect with any existing queens in curr) is currently being re-used across rows.
So, if you place the line bool flag=false; just above for(int i=0; i<curr.size(); i++){, it should produce the correct output for your test case.
Other notes:
... |
62,540,516 | 62,540,645 | Using c# code from a native c++ application | I am working on a basic 2D C++ Game engine but i want to be able to use C# to make games with it like unity does but I'm not sure how to do it. I've seen people saying about CLI but not sure exactly how that works. I want to be able to access functions on the engine in C# and be able to have the engine run the C# code.... | Right now you have two big ways of doing this:
Make your C# application generate COM objects which you can consume from C++. Performance is a bit iffy, but doable and very simple.
Use reverse PInvoke, where you export functions from your C++ application with in function pointers that you fill in from the C# side with... |
62,540,523 | 62,540,560 | How to move one vector into another vector without copying | I have a large vector<object> created inside a scope that I want to push into a vector residing outside that scope without copying it (since it is very large). Is there a way i can push vector v into vvec without doing a copy as I am doing currently?
std:vector<std::vector<object>> vvec;
{
std::vector<object> v;
... | You could std::move it
std::vector<std::vector<object>> vvec;
{
std::vector<object> v;
v.emplace_back(object());
vvec.push_back(std::move(v));
}
If I mock a class as the following
struct object
{
object() { std::cout << "default construct\n"; }
object(object const&) { std::cout << "copy construct\n... |
62,540,725 | 62,540,781 | Variable argument list with ints | I am currently trying to understand variable argument lists in C++. I have one particular example from Java, that I'm trying to get to work:
class FindMax {
public static void main(String... args) {
System.out.println(findMax(3, 5, 7));
}
public static int findMax(int... n) {
int largest = ... | Look at this loop:
for (i=1;i<n;i++)
The first int that is passed to the function needs to be the number of arguments following it.
So, if you remove the 7 in the first call, the loop expects 702 ints to follow after the first argument. Since there aren't enough arguments, you are accessing invalid memory, which can c... |
62,540,754 | 62,555,101 | Overloading operator new for other class | Use case
I have a Node class that reads, creates and sends Message objects to other Node classes. I do not wish to modify the Message class constructor because I use it in other classes as well.
Message objects basically look like that (Message.hpp file)
class Message {
size_t size;
char* buffer;
Message(s... | My thanks to François Andrieux for his timely answers. The short answer to my question is to create a factory pattern to create Message objects. Something like :
(Node.cpp)
unique_ptr<Message> Node::createMessage(size_t capacity) {
return unique_ptr(new Message(capacity + header_size));
}
That way, the user doesn'... |
62,540,816 | 62,541,063 | C++: Constant Reference Parameters | why do we use Constant Reference Parameters in this code
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Converts a hex number as a string to decimal
int hex2Dec(const string& hex); // here why we use reference and const it seems we do not change hex in the function body
// Convert... | The naive solution is to use int hex2Dec(string hex) here. However because function arguments are copied in C++ calling this function would cause a new string to be created for hex, copied from the function argument every time hex2Dec is called. This can lead to needless performance issues, specially if the strings are... |
62,540,864 | 62,540,906 | std::getline not re-requesting user input in while loop | I am trying to write a program where a user is asked for input and then I check if the 2 sub strings (splitting in half) is the mirror image. I want to loop continually until a user stops entering in input but my code is not looping correctly. The code works fine on the first iteration of the while loop, but then durin... | In the first iteration of the loop:
cin >> quit;
will read up to, but not including the newline character.
In the second iteration of the loop:
std::getline(std::cin, input);
will read that newline character, and hence read an empty string into input.
There are several ways to fix this
You could use getline to read ... |
62,541,075 | 62,543,354 | What is the difference between *smart_ptr and *smart_ptr.get() | As well as I understand, dereferencing - *smart_ptr , and get() + dereferencing *smart_ptr.get() doing the same thing with smart pointers, but may be there is something under the hood that I'm not aware of, cause I've seen a lot of cases there the second approach was used, so what is the point? Does it affect performan... | From a functional standpoint, there is no difference between *smart_ptr and *(smart_ptr.get()), as they are defined in the C++ standard as doing the same thing - dereference the held pointer and return a reference to the object being pointed at.
However, from a debugging standpoint, there may be a subtle difference, de... |
62,541,168 | 62,541,492 | How to add precompiled headers in CMake for visual studio generator | CMake 3.18; VS 2019;
I'm learning CMake and to check my results I'm trying to generate visual studio project.
My current problem is precompiled header option.
What I want to achieve is that VS project will have "/use" or "/create" precompiled headers option with correct file name.
In my project folder I already have ug... | The command target_precompile_headers has been added in CMake 3.16.
You'll either have to upgrade your CMake distribution (The one shipped inside VS2019 is quite up to date) or install the latest from the installer.
Otherwise, you'll have to use cotire for precompiled header, but my recommendation would be to upgrade s... |
62,541,420 | 62,541,439 | error: cannot convert 'std::string' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)' | I am getting an error in the below program:
error: cannot convert 'std::string' to 'char*' for argument '1' to 'char*
strcpy(char*, const char*)'
std::string machine, account, passwd, dummyString;
short sRc = FtpDestGet( BAC_REQ_DEST, machine, account, passwd, dummyString );
if ( sRc )
{
fprintf( stderr, "Can... | You don't need strcpy for C++ strings.
Do this: passwd = getenv(BAC_REQ_DEST);
|
62,541,484 | 62,541,588 | using an abstract class from another header file in c++ | I have 3 files
dimentions.h:
namespace mtm {
class Dimensions {
int row, col;
//some code
};
}
IntMatrix.h:
#include "dimentions.h"
namespace mtm
{
class intMatrix
{
private:
int** data;
int col;
int row;
public:
intMatrix(Dimensions dims, int... | Welcome to StackOverflow!
Compiler messages are sometimes misleading, and in your case you have an error because you are repeating the default value in your implementation. This is probably the error the compiler is complaining about.
EDIT
As pointer out by drescherjm, you also forgot the add the class name to the cons... |
62,541,486 | 62,565,084 | How to use custom logger with websocketpp? | I am creating a telemetry server using websocketpp, and have followed the example here. My application will be running as a linux daemon which starts on boot, and therefore I won't be able to write logs to standard out. I would therefore like to add a customer logger using spdlog, and understand that it can be done bas... | Building a custom logger has two steps. First, write a policy class with the appropriate interface then create a custom config that uses that policy.
To write the policy class websocketpp::log::stub is a minimal implementation that doesn't actually do anything (it is primarily used for stubbing out logging in the unit ... |
62,541,663 | 62,542,540 | Move and copy constructors in a linked list | I am still trying to learn more about copy and move constructors. I have a linked list class that I want to deep copy using copy and move constructors but I'm having issues. First, to deep copy List class, do I only copy head_ and tail_ in the constructors. I know the code is horrendous, maybe I shouldn't jump into hig... | Here is my five cents.:)
The demonstrative program below shows how the copy constructor, move constructor, copy assignment operator, move assignment operator, and the destructor can be implemented including some other auxiliary functions.
#include <iostream>
#include <utility>
#include <functional>
#include <iterator>
... |
62,541,831 | 62,542,026 | What tokens are permitted as arguments to #include? | What sort of tokens are required to be allowed by the standard in includes? E.g., are spaces in file names allowed?
| From cppreference on Source file inclusion
Any preprocessing tokens (macro constants or expressions) are
permitted as arguments to #include and __has_include (since C++17) as
long as they expand to a sequence of characters surrounded by < > or "".
Then in Explanation
Searches for the file in implementation-defined m... |
62,542,285 | 62,544,770 | Implement Scrolling for QQuickView containing multiple QQuickPaintedItems | So recently I started a project where I want to display a graph showing relations between different datasets.
The graph consists of Edges and Nodes, while both of these classes inherit QQuickPaintedItem and override the paint(QPainter* painter) method. I have another class which stores all Nodes and Edges in two QLists... | If you don't mind rendering everything, what you need is Flickable.
Set the viewable width and height of your Flickable (explicitely, with anchors, or with layouts) and nest your custom item in it and set the contentWidth and contentHeight of the flickable depending on the total size or your custom item.
|
62,542,654 | 62,542,705 | Program crashes inside the copy constructor of a discriminated union | So I've been trying to create a discriminated union for my project. Coming from C, I thought it would be trivial... ;)
The structure is named Message. It has a MessageType and an inner union which holds either a MessageGet or a MessageSet.
enum MessageType {
MESSAGE_GET,
MESSAGE_SET
};
struct MessageGet {
... | U(const U& other) {
get = other.get;
set = other.set;
}
This always sets set last, making the value of get invalid. When you set one of the members of a union, it invalidates all the others. That's what makes a union different from a struct.
Where you have:
as = other.as;
You have to chang... |
62,542,721 | 62,543,467 | How to override "default" #define values of a C ++ library header with new values defined in an application header | What I'm trying to do is provide a library with some defaults set by #define directives in the library header. Those would determine what functions of the library code will be compiled with a given application. In case the application developer needs to add or remove library functions, it should "override" the library'... | Take advantage of the capabilities of your linker. If you want to exclude unused or unnecessary code from you binary, one way to do that is to put each function in its own source module. (Some compiler packages support Function Level Linking, where the linker can remove unreferenced functions.)
Trying to use macros the... |
62,542,832 | 62,542,884 | Can somebody tell me how this code working with no curly braces between two if? | If I am enclosing the code after first if upto second return in curly braces it is not giving me desired output.
static int comparator(Player a, Player b) {
if(a.score == b.score)
if(a.name == b.name)
return 0;
else
return (a.name > b.name)? -1:1;
return (a.score < b.s... | Your code has if() and else statements. Each will execute one line of code that comes after them. This means that it will only execute a single statement and end after the first ; that it finds.
for() loops, while() loops, if-else blocks can be used without curly braces if the statement you want to execute consists of... |
62,543,004 | 62,543,161 | How to structure templated function with inner templates? | I am trying to create a templated function that takes in any types of object which in of itself are also templated. An example is:
ObjA<int, string> o;
ObjB<float, int> o2;
I want to make a function that takes any of these types of objects but am unsure how to structure the template. This is my bad attempt:
template<t... | You need to turn V into a template template parameter:
template<typename T, typename U, template<typename, typename> typename V>
void Add(std::shared_ptr<V<T, U>> inst) {
}
Note that this restricts V to having two template arguments. Your goal of making a "templated function that takes in any types of object which in... |
62,543,081 | 62,608,650 | C++: How to install OpenCV with the compiler MinGW 9.2.0 on Windows 10 | I am a few days ago trying to install opencv using Dev-Cpp and Windows 10, i add the directories of the .h, .lib and .dll files to the Dev-Cpp, but when i compile the code always give me the same error.
In compiler options i add the next directories:
-C++ Headers--
C:\Users\admin\Downloads\opencv\build\include
-Librari... | Those are linker errors: it means the compiler can't find the binary code for those functions.
In other words, you might have forgotten to specify a few OpenCV libraries. If I'm not mistaken, imread() resides in opencv_imgcodecs.
|
62,543,094 | 62,543,219 | Why do we do "INT_MAX/10" and not just INT_MAX? | I was solving an easy question to reverse a 32-bit signed integer but I can't understand one part. To handle the overflow I tried applying if(res > INT_MAX || res< INT_MIN) and if(res*10 > INT_MAX || res*10< INT_MIN) but none of them worked. Only if(res > INT_MAX/10 || res< INT_MIN/10) worked. I couldn't understand the... | some_int_expression > INT_MAX and some_int_expression < INT_MIN are never useful because those are always false. No int value can be larger than INT_MAX and no int value can be less than INT_MIN.
When res > INT_MAX/10 is true, doing res * 10 will cause the operation to overflow the representable range of int, and as a... |
62,543,353 | 62,543,485 | Undefined symbols for architecture x86_64: std:terminate(), typeinfo, operator delete[], operator new[], and more | I am following the Lynda.com C++ Essential Training course, but some of the code isn't compiling. The following example gives an error when compiling:
// new-delete.cpp by Bill Weinman <http://bw.org/>
// updated 2018-10-27
#include <cstdio>
#include <new>
using namespace std;
constexpr size_t count = 1024;
int mai... | Use clang++, not clang
As pointed out by @eerorika in the comments, clang is a C compiler, not a C++ compiler. clang++ is for C++.
|
62,543,643 | 62,543,839 | Memory limit exceeded bad_alloc | I was solving a problem on codeforces and it gave me memory exceeded and even on my local compiler it says 'std::bad_alloc'
can someone explain why and how to solve this !!!
int tst;
cin >> tst;
while(tst--){
string s;
cin >> s;
ll n=s.length();
string ans;
if(n==2){
cout<<s<<endl;
}
... | So, firstly, specify your problem statement.
Secondly, please, pay attention to this cycle:
for(int i=0;i<n;i+2){
ans.push_back(s[i]);
}
The cycle which is written in this way would be infinite, because You are not incrementing i at all, and i will be equal to zero all way cycle goes(infinite times).
So, addition... |
62,543,695 | 62,543,925 | how can i fix this sfml header file namespace error? | i start sfml but can't success tutorial
because of..
and it says
The variable "namespace" is not a type name.
4723 error code
What should i do?
| You are trying to compile C++ code as C code. You get an error because namespace is a C++ concept.
Rename your file to test.cpp.
|
62,544,163 | 62,544,339 | How to overload the << operator so it only affects a member of a class? | I have a class Bitset that stores a vector of chars, and I want to be able, whenever I use cout << char, to cast that char into a short int ONLY if it is part of that class.
Code:
template<long long X>
class Bitset
{
public: std::vector<unsigned char> bit = std::vector<unsigned char> ((X+7)/8);
public:
... | You can't overload operator<< for char to behave the way you want. It has no idea where the char comes from, so it can't behave differently based on the source.
To make this work the way you want, you will have to make Bitset implement its own operator[] that returns a proxy object, and then you can overload operator<... |
62,544,409 | 62,544,502 | VS Looks for Headerfile in Debug folder | I am really new to C++ and in haven't worked with VS in a long time.
My problem is, VS suddenly throws me an error when I try to import one of my header-files that is in the same folder as the cpp file I try to import it in.
Maybe I hit some Keycombo or klicked on a "bad" button ^^
I also checked my "Additional Includ... | Just change #import "Game.h" to #include "Game.h".
Import directive is used for type libraries not header files.
Keeping in mind the fact, these files (tlh) are generated by the compiler, so its actually not weird that VS looks them in output folders.
|
62,544,756 | 62,544,838 | __cplusplus expanded minimum values | Am I right to understand that these are the minimum values of __cplusplus and that C++98 has the same value has C++03?
// C++ 98
#define __cplusplus 199711L
// C++ 03
#define __cplusplus 199711L
// C++ 11
#define __cplusplus 201103L
// C++ 14
#define __cplusplus 201402L
// C++ 17
#define __cplusplus 201500L
// C++ 20
#... |
Also, does C++20 have an official value now that the standard is released?
It does: 202002L. The format here is a date: YYYYMM (C++20 was made official in February 2020). The value for C++17 was 201703L, not 201500. All the rest are correct (C++03 did not change the __cplusplus macro).
However, this macro is far too ... |
62,545,002 | 62,545,037 | How is map searching for value at a given key | When I access a value in std::map at a given key, does the map search for this value linearly by checking each key-value pair if the key match or does it access the requested value directly?
| Neither. It will have to search through an index to find the value, but it will do that in a way, that is much more efficient than a linear search.
Typically, this is implemented using a Red-black tree and search time will be logarithmic to the number of elements in the map.
|
62,545,275 | 62,547,115 | Passing generic objects to Rust and passing back to C++ for destruction after usage | I want to send buffers from C++ to Rust, read them in Rust and destruct them on C++ when they're not needed anymore.
This is the function that I made to receive:
#[no_mangle]
pub extern "C" fn smol_stack_smol_socket_send(
smol_stack: &mut SmolStackType,
socket_handle_key: usize,
data: *mut u8,
len: usiz... | As I see it you have at least two possible paths. Which one works for you will depend a lot on how these calls all fit together.
This simplest is to just consider the data passed from C++ to rust to remain owned by C++. i.e. smol_stack_smol_socket_send is expected to not destroy the buffer passed to it. That job falls ... |
62,545,283 | 62,596,614 | Cannot create medium visualization for X.radio because network node visualization is not found- Omnet++ | I am attempting to add the communication ranges of the cars in the Veins_Inet example. I included a
visualizer in the network NED file:
visualizer: IntegratedVisualizer {}
I also the following line to the ini file:
*.node[*].wlan[0].radio.displayCommunicationRange = true # show range of car
*.visualizer.*.mediu... | I have encountered this error as well. In my case, I was using INET 4.2 but Veins 5.0. Visualization does not work in for Veins in this version.
You will need to update your veins_inet subproject to use the latest Veins.
Specifically, the version that has this commit:
https://github.com/sommer/veins/commit/4a1459c40833... |
62,545,719 | 62,545,775 | Should it be possible to add to an iterator of an empty deque in C++? | Here's an example of what will cause the problem:
#include <deque>
int main() {
std::deque<int> has_data = {1, 2, 3};
std::deque<int>::iterator iter1 = has_data.begin() + 5; // This works fine
std::deque<int> had_data = {4, 5, 6};
had_data.clear();
std::deque<int>::iterator iter2 = had_data.be... | The issue you're running into here is that it's undefined behavior to use the + operator to jump an iterator forward beyond the spot one past the end of a container. As a result, each of the iterator operations you're performing leads to undefined behavior, and it just so happens to be the case that the first two cases... |
62,545,830 | 62,546,128 | Unknown type name QML_ELEMENT and QML module can't be found even though copied straight from a official example | When I want to run this example of Integrating QML and C++ I get a error (in the backend.h) that QML_ELEMENT is not a defined type. I know that a similar question was asked here already, however since I copy pasted from the official example, I did #include <qqml.h>. That means the cause of my error has to be a differen... | QML_ELEMENT is available from Qt >= 5.15, as you are using Qt 5.9 then you must use qmlRegisterType<BackEnd>("io.qt.examples.backend", 1, 0, "BackEnd"); as points out for Qt 5.9 docs
|
62,546,386 | 62,555,194 | Is it necessary to acquire the lock and notify condition_variable if no thread needs to wake up? | I was reading this reference and saw:
The thread that intends to modify the variable has to
acquire a std::mutex (typically via std::lock_guard)
perform the modification while the lock is held
execute notify_one or notify_all on the std::condition_variable (the lock does not need to be held for notification)
If ... | Your on_pause function sets pause_ to true, while the predicate in check_pause verifies that it is set to false. Hence calling notify_all in on_pause is pointless, because the notified threads in check_pause will check the predicate and immediately go back to sleep. And since pause_ is atomic and you don't need to call... |
62,546,752 | 62,547,245 | C++, Why array is faster and use less memory than vector | During one leetcode question.
When I use std::vector to store things.
i_max, and j_max are integers.
vector<int> left_vec(i_max);
vector<int> right_vec(j_max);
Runtime: 100ms, Memory Usage: 71.5MB.
When I use std::array to store things.
int left_vec[i_max];
int right_vec[j_max];
Runtime: 40ms, Memory Usage: 16.1MB.
O... | Arrays are a simple sequence of data allocated on the stack.
Vectors are an object that probably is allocated on the heap. (I am not sure on that one for ALL cases, I think it might depend on the C++ std library implementation and compiler optimization depending on what you are doing with the vector. Two posts on that ... |
62,546,777 | 62,547,303 | Accelerate reading/processing log files in C++ | I am trying to read a large log files (around 10G) with the following format:
3 49
7 28
...
Basically we have two columns, each column is an positive integer.
And here is the code I am using to read the log files into a two-level map:
typedef std::map<int, std::map<int, std::tuple<int, int, int>>> coverage_info;
cov... |
First you should check which part of the code takes most time. Probably it is either fgets/sscanf pair, or dealing with maps. You should do this research before you ask the question here. How? Remove everything except sscanf from the loop, and see how much it takes now (you may want to read the smaller file, say 1... |
62,547,018 | 62,547,412 | Overloading prefix increment operator for iterator class throws segmentation fault | I'm getting segmentation faults when the iterator reaches the last node in class the linked list.
By debugging, I can see that when the iterator reaches the end of the linked list, node->next_ points to null and thus throws the seg fault.
EDIT:
I've include the definition for void push_front() method
List.h
void pu... | You need to initialize head_ to nullptr by default:
Node* head_ = nullptr;
otherwise head_ has some indeterminate value, and the following check in push_front is not guaranteed to work:
if (head_ == nullptr)
even though head_ is not pointing to valid memory.
Note that this problem arises even if you never call push_f... |
62,547,481 | 62,547,509 | Is there any way to store element and its frequency together in same data structure? | I have been working on a problem with arrays and the count of each elements must be considered and changed dynamically then and there. I want to know if there is a way to store both the element and frequency in a single data structure.
Any solution with code in cpp would be helpful.
|
int main()
{
int a[]={1,1,1,2,2,3,4};
map<int,int> m;
map<int,int>::iterator it;
for(int i=0;i<7;i++)
{
it=m.find(a[i]);
if(it!=m.end()) it->second++;
else m.insert(pair<int,int>(a[i],1));
}
//printing the output
for(auto i=m.begin();i!=m.end();i++)
cout... |
62,547,504 | 62,547,665 | Selection sort in C++ (modified) not working for all cases | I was trying to modify the selection sort code in c++ to check the results. My modified code is:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter number of elements\n";
cin>>n;
int i,j,small,pos,t;
int a[n];
cout<<"Enter elements of array\n";
for(i=0;i<n;i++)
... | The issue is because of wrong place of the swap logic. The swap should be placed outside the inner loop.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter number of elements\n";
cin>>n;
int i,j,small,pos,t;
int a[n];
cout<<"Enter elements of array\n";
for(i=0;i<n;... |
62,547,571 | 62,549,034 | Google Kickstart 2020 Round A Wrong Answer: What's wrong with my code? | There are N houses for sale. The i-th house costs Ai dollars to buy. You have a budget of B dollars to spend. What is the maximum number of houses you can buy?
My algorithm is pretty simple. Sort all the house prices by adding them to a min heap represented by a priority queue, then pop prices off the queue (counting a... | There's a few things that might be failing you:
As vivek_23 have mentioned while(sum < B) this loop will get runtime error if we can buy all houses with our budget, change it to while(sum < B && !pq.empty()) instead.
Also you are using same variable i in both nested loops change it to something else
|
62,547,716 | 62,547,842 | How to know when to call delete and when delete[] in C++? | I was implementing classes my_unique_ptr and my_shared_ptr that mimic the standard library smart pointers std::unique_ptr and std::shared_ptr to get to know it better.
When implementing the destructors I'm in this trouble to decide whether to use delete or delete[] to free the memory. As much as I read on SO and other ... | You are correct that you can't know if a memory was allocated by new or new[]. But you can't even know that a memory stores an automatic duration object. E.g. your user can do:
int a = 24;
my_unique_ptr<int> ptr1(&a); // oups
There is no way for you to know that. So do what the standard library does:
make a speciali... |
62,547,965 | 62,548,050 | Multiple Errors When Compiling with g++? | When compiling my code, I'm receiving many different errors such as:
frame.h:5:48: error: expected identifier before '(' token
frame.h:5:17: error: variable or field 'writeFrame' declared void
frame.h:5:17: error: 'GifWriter' was not declared in this scope
frame.h:5:34: error: expected primary-expression before 'double... | Change (std::vector<uint8_t>& frameOut) to std::vector<uint8_t>& frameOut.
Not sure why you felt the need to put the brackets there, and the first error message is telling you that's the problem.
Also note that you should write header files so that they are self-contained. This means that this header file should have #... |
62,548,178 | 62,550,229 | Assigning reference to local variable, would it go out of scope if the local variable is out of scope? | First I think the following is definitely Undefined Behavior:
Object & foo(){
Object o;
return o;
}
Object & ref = foo();
But now suppose a function that takes a reference of another object which will exists longer, and assign this reference to a local variable, and the local variable gets out of scope. Would... | It depends if the local variable within your function is defined as variable or as a reference. See the following example:
#include <iostream>
class Object{
public:
Object(){};
~Object(){};
};
Object & foo(Object & obj){
Object& o = obj;
std::cout << &o << std::endl;
return o;
}
Object & foo2(Object ... |
62,549,227 | 62,553,083 | How to get the type of non-static method without instance? | I am trying to create a template function in C++ like:
template<typename IteratorType>
double evaluate(const IteratorType &rBegin, const IteratorType &rEnd,
double(*function)( const decltype( *IteratorType ) &rObject )) // error, typename not allowed
// I'm unsure if I need to put the reference there, not part ... | First of all you need a minimal example to your problem. Here is what I understood from your comments:
#include <iostream>
#include <vector>
#include <string>
struct MyClass /* final */
{
static double member(std::string const& val) /* noexcept */
{
std::cout << "double MyClass::member(int val): " << v... |
62,549,344 | 62,549,832 | Convert Fraction to decimal number and sort them | I want to sort rational numbers into ascending order so I tried to convert the numbers into decimal and sort them. I have done the part of converting to decimals but I have no clue on how to continue after this part to sort the decimals.
For example: 1/3, 5/3, 7/2, 1/2
Output: 1/2, 1/3, 5/3, 7/2
#include<iostream>
#inc... | There's no need to convert to decimal to compare 2 fractions. If you have a/b and c/d then just compare a*d and b*c
bool operator<(const Fraction& left, const Fraction& right)
{
return (double)left.getNum()*right.getDem < (double)left.getDem()*right.getNum();
}
This is more correct than comparing the decimal value... |
62,549,888 | 62,550,022 | Build two slightly different projects from one code in Qt/C++ | I have a Qt project and I want to be able to build two slightly different executables - GUI and SimplifiedGUI. In the second one some of the tabs and the buttons will be hidden.
All the settings for the Simplified exe will be in an if statement and I need a way to make the boolean expression in this if statement True o... | You can use preprocessor symbols for conditional compilation:
#include <iostream>
#ifdef SIMPLE_GUI_FLAG
constexpr bool simple = true;
#else
constexpr bool simple = false;
#endif
int main() {
if (simple) std::cout << "simple";
}
For gcc you can invoke it with -DSIMPLE_GUI_FLAG to have the symbol SIMPLE_GUI_FLAG d... |
62,550,311 | 62,550,418 | how to generate multipile random number sequences independently in c++? | in my view, a seeded pseudo-random number generator will produce a deterministic sequence of numbers. in order to get 2 random sequence in one program, 2 generators with different seed are needed. that is:
default_random_engine gen1(1);
default_random_engine gen1(2);
uniform_int_distribution<int> dist(1, 5);
for (int i... |
Can i use only 1 generator to produce 2 independent sequences?
Well, yes and no.
If the sequence from a single generator were "truly" a sequence of independent and identically distributed samples (quotes since the meaning of that term is actually problematic) - then you can take the odd elements and the even elements... |
62,550,345 | 62,550,538 | I'm getting Runtime Error in a problem from Code Forces | Here is the problem: https://codeforces.com/contest/1256/problem/D .I'm getting runtime error("out of bound") in test case 15 here is my submission: https://codeforces.com/contest/1256/submission/84865113
Where am I doing wrong?
my approach:
#include <iostream>
using namespace std;
int main() {
int t;
cin>>... |
the range of k is out of int. You should use long long.
|
62,550,436 | 62,673,849 | Clang-format 10.0 vs. 5.0 const member fuction is formated differently | We are updating our clang-format from 5.0 to 10.0 (yes, I know that this is a big jump :-))
The file .clang-format is kept constant.
With the 5.0 version we get a format like this
virtual Composite *copy_composite_tree(Composite *parent // parent of copied tree
) const;
With the ... | I consider this to be a bug, which was introduced with clang-format 9.0.1, since all buildin styles, such as LLVM, Google, ... show the very same behaviour.
I reported this bug to the llvm project.
https://bugs.llvm.org/show_bug.cgi?id=46509
|
62,550,835 | 62,551,491 | SHBrowseForFolderA Errors | I recently found some code on here which shows us how to let users choose the directory in C++ which isn't as simple as C#. I keep getting three errors I barley understand. And i want to know how to store the path onto a string.
ERRORS:
argument of type "char *" is incompatible with parameter of type "LPWSTR"
a val... | try to add a L in front of the strings, like that :
bi.lpszTitle = (L"Browse for folder...");
this will turn the string into a Wide String
|
62,550,887 | 62,551,027 | C++ code works fine on desktop but not on the laptop | This simple code for some reason works perfectly fine on my desktop but when I try it on my laptop only the first part (printing the elements of vector) works then the program ends and instead of saying "Process finished with exit code 0" it says
"Process finished with exit code -1073741819 (0xC0000005)". I don't know ... | The problem is not with the computer but with the code.
array.erase(it); invalidates the iterator it, and any subsequent use of it has undefined behaviour.
The worst kind of undefined behaviour is the one that appears to work.
erase returns an iterator to the element after the erased one, and you should use that.
for (... |
62,550,963 | 62,556,918 | deleting boost archive object also deletes stream associated to it? | In my code, I have to keep a persistent boost::oarchive object to write. So I have a writer class which keeps pointers of ostream and boost::oarchive pointers say -
ofstream *fs = new ofstream();
boost::archive::binary_oarchive *afs = new boost::archive::binary_oarchive( *fs );
I am having issues while destructing them... | The archive probably wants to flush something to file stream before self destruction, but you already closed the file stream.
So, delete archive first, then delete your ofstream.
In most cases, it is safe to destruct dependent objects in the reverse order of their construction.
|
62,551,010 | 62,551,118 | Is const-casting away const-ness of references to actual const objects permitted if they are never modified through them? | I have an abstract class that declares const and non-const member functions. For the sake of discussion let's say it looks like this:
class record_interface
{
public:
virtual ~record_interface() = default;
virtual void set_foo(BoundedFloat) = 0;
virtual BoundedFloat get_foo() const = 0;
};
This is used as a ... | Per https://en.cppreference.com/w/cpp/language/const_cast:
const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object or a reference or pointer to non-volatile type that is actually referring to a volatile object. Modifying a const object through a non-co... |
62,551,360 | 67,383,228 | Getting started with the c++ taskflow library | I have tried out the taskflow librabry https://github.com/taskflow/taskflow for c++ and got one most basic program running. Next, I wanted to adopt this example https://www.cs.cmu.edu/~15210/pasl.html#_parallel_fibonacci of calculating Fibonacci numbers while using the taskflow library.
Now, I get a error message which... | The problem is that you are recursively creating Taskflow and Executor instances. The executor manages the workers and the task queue, creating separate instances for each call means there is no overall management of the tasks. Each executor will create at least one worker and the number of workers created will be >= n... |
62,551,393 | 62,552,032 | How do I find the index of the element being passed to the predicate in STL functions? | Consider the following piece of code:
std::vector<int> vec(n);
for (auto& elem : vec) {
std::cin >> elem;
}
auto count = 0;
while (!isGood(vec)) {
auto odd_it = std::find_if(vec.begin(), vec.end(), [] (int num) { return ~(num % 2); });
auto even_it = std::find_if(vec.begin(),... | The most clear solution in C++17 and below is simply to write your own version of find_if that passes an index to the predicate. The implementation is straightforward:
template<class Input_it, class Predicate>
Input_it find_if_with_index(Input_it first, Input_it last, Predicate p) {
for (std::size_t i = 0; first !=... |
62,551,762 | 62,551,796 | When you use shared pointers what is the mechanism that releases the memory from the shared pointer itself | I understand that shared pointers work by counting references and releasing the object the pointer is pointing to. But the shared pointer takes space itself, is it released somehow? is there a pool of shared pointers and they are reused? is this something easy to track in the library source code?.
| The place where you store the shared pointer is up to you, the same way any other variable.
For instance, if you have it as a local variable in a function, then it will likely be held in the stack.
|
62,552,160 | 62,552,594 | what is the format specifier for atomic<uint64_t> datatype in C++? | I am using Ubuntu virtual box and writing a project in C++.
I am unable to put a format specifier for atomic<uint64_t> datatype in C++.
| Use .load() to get uint64_t out of the atomic, then print it as a regular uint64_t using PRIu64:
#include <atomic>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
int main()
{
std::atomic<std::uint64_t> x = 42;
std::printf("x = %" PRIu64 "\n", x.load());
}
|
62,552,352 | 62,553,021 | Unexpected break during an if statement C++ | The program is to convert yen, euro or pounds (depending on user input) to a dollar.
I am asking 2 user inputs - double amount (money to convert) and char currency (to determine what currency to convert to dollar).
Sample Input: 1y
Sample Output: 1 yen(s) = 0.0094 dollar(s).
The problem is in the if-else block when I ... | To provide an actual answer, since I can't do so in the comments; here's an alternate way of getting the relevant user input, maintaining the same syntax. This assumes that the last character of the input string is the currency character. You can perform a check to see if the last character is a valid currency characte... |
62,552,485 | 62,553,481 | Linking a QWidget to another QWidget new created | I am try to, by pressing a button in the main QWidget, to create a new QWidget. In that new created QWidget I want to have a button connected to a slot of the main QWidget.
class UI : public QWidget
{
public:
UI(){connection();};
private:
QPushButton* all = new QPushButton{ "ALL" };
void connection(){
... | Before we start, there are some other problems with you code.
Note that in your second class, the constructor is not named the same as the class, which will cause some... Problems.
You also forgot to put a parent for your buttons (which may thus cause some unexpected results) AND for your Widgets (which is again not a ... |
62,552,502 | 62,557,404 | Decode svg from memory ImageMagick | How do I decode svg image from buffer? I know SVGs are just text but I don't know how to parse them to Magick::Image other than reading from disk.
#include <Magick++.h>
#include <stdio.h>
using namespace Magick;
int main() {
printf("EnableOpenCL ret: %d\n", Magick::EnableOpenCL());
Magick::Image svgImage;
... | You would copy the buffer into Magick++'s Magick::Blob and pass it to Magick::Image constructor.
Magick::Blob svgData(memory_ptr, memory_length);
Magick::Image svgImage(svgData, svgRenderSize, "SVG");
Where memory_ptr is the address of the svg data in memory, memory_length is the total byte size of memory_ptr, and svg... |
62,552,507 | 62,573,025 | Standard libraries still require additional runtime libs? (vcruntime140_1.dll) | I've created a Windows x64 program using standard headers and DirectX (see below). I was kinda expecting no additional runtime libs would be required for the users. But i got the feedback from some that the vcruntime140_1.dll was missing. It's an easy fix, but how do I ensure that users don't need to download additiona... | Running programs under Windows10 developed in Visual C++ require the associated runtime redistributables: https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads.
Microsoft has decided to include the universal C Runtime (CRT) libraries with the standard Windows 10 installation and these... |
62,552,871 | 62,553,950 | Performance related to multiple for loops vs single for loop wrt getting data from multimap | Below is the sample code of fetching data from a multimap and assigning to a typedef struct. I need to know if there is any performance difference/advantage/disadvantage in fetching data using multiple for loops compared to single for loop. Here dbR25GetRoute is the multimap.
int sz = dbR25GetRoute.size();
... | Whether there is a significant difference in performance can really only be answered by you, by actually measuring the performance in the execution environment where this code will be used.
It seems to me a trade-off. Good things about 28 separate for-loops:
No extra logic to figure out the type to extract from the mu... |
62,552,894 | 62,553,240 | Type of function pointer that receives and returns function pointer? | The type of pointer to int f(int i) { return i; } is int (*)(int) - this is fine. Also, if I set using f_ptr = int (*)(int), i.e. f_ptr is the type of pointer to f(), the type of pointer to f_ptr g(f_ptr fp) { return fp; } is natually f_ptr (*)(f_ptr) - this is also fine.
If so, I feel that f_ptr (*)(f_ptr) without usi... | C++ does it this way for compatibility with C
C does it this way so that definitions mirror uses
int f(int i) {
return i;
}
using f_ptr = int (*)(int);
f_ptr g(f_ptr fp) {
return fp;
}
int main() {
// Definition
int (*fp0)(int) = &f;
// Use
int m = (*fp0)(1);
// Definition
int (*(*gp1)(int (*)(int))... |
62,552,906 | 62,553,351 | Inheriting a templated conversion operator | Consider the following code:
template <class R, class... Args>
using function_type = R(*)(Args...);
struct base {
template <class R, class... Args>
constexpr operator function_type<R, Args...>() const noexcept {
return nullptr;
}
};
struct derived: private base {
template <class R, class... Ar... | GCC support this: [demo]
template <class R, class... Args>
using function_type = R(*)(Args...);
struct base {
template <class R, class... Args>
constexpr operator function_type<R, Args...>() const noexcept {
return nullptr;
}
};
struct derived: private base {
using base::operator function_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.