question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
65,950,623
65,975,185
CMake cross compiling Windows to Windows
Has anyone ever tried, to cross compile Windows to Windows in cmake? I have an exotic scenario. I'm participating in an open source project, built with cmake. The project has several platform ports. Eg. Windows, Linux, etc. Each platform has its own cmake subscript and some also have separate toolchain scripts. I'd lik...
Avoid directory commands add_definitions, add_compile_options, add_link_options, etc. Instead, add these to your toolchain file in the standard _INIT variables. The suffixes can be overridden using their language-specific variants, too: set(CMAKE_SYSTEM_NAME win32freertos) set(CMAKE_CXX_FLAGS_INIT "-DWIN32 -D_WINDOWS ...
65,950,762
65,951,179
C++ - Specify template value type
I have the function // Helper to determine whether there's a const_iterator for T. template <typename T> struct hasConstIt { private: template<typename C> static char test(typename C::const_iterator*); template<typename C> static int test(...); public: enum { value = sizeof(test<T>(0)) == sizeof(char) }; };...
You can use std::is_same to check if a type is exaclty the same as a specified one. If you want to check both of your conditions at once, you can simply use logical operators in the std::enable_if conditon: template <typename Container, typename = std::enable_if_t< (std::is_same<typename Container::value_type, int>...
65,951,841
65,952,162
Affecting a function to another function in c++
So there's this code am trying to understand: #include <iostream> using namespace std; int x = -2; int h(int &x) { x = 2 * x; return x; } int g(int f) { return x; } int &f(int &x) { x += ::x; return x; } int main() { int x = 6; f(::x) = h(x); cout << f(x) << endl; cout << g(x) << endl; cout << h...
The line f(::x) = h(x); is equivalent to operator=(f(::x), h(x)); First, one of the functions f or h are called and the returned value is passed to operator=. Then the other function is called and the returned value is passed to operator=. The order is irrelevant because in either case f changes the value of global x...
65,951,994
66,017,173
Fatal error: gtk--.h: No such file or directory
My name is Sebastian. I am trying to compile a project under Ubuntu 20. This project is for sending data to a Timex Datalink via a µc (link: https://github.com/dfries/datalink_ironman). In this Github repository is a folder name "graph". Inside this folder is a c++ source file (fun.cc) and a make file. When I open the ...
This program is probably using a very old version of gtkmm from when it was still named gtk--: https://wiki.gnome.org/Projects/gtkmm/FAQ#Why_is_it_named_gtkmm.3F I would expect to have to do some updates to get it to work with even the most recent version of gtkmm 2.x.
65,952,097
65,952,713
Implementing jobshop problem in old ORTools
I want to implement this simple jobshop example: https://developers.google.com/optimization/scheduling/job_shop but in the old version of ORTools in C++ and I can't seem to find any support for the syntaxes in the older version. I have to write it in the old version to learn the syntaxes cause I have a bigger code that...
The old version can be found in earlier releases: see here. This being said it is no longer developed the CP-SAT version is much better.
65,952,213
65,952,600
Does declaring functions in anonymous namespace with "static" reduces the linking time and memory by not polluting the symbol table
I am in a discussion in one of the code review sessions. The debate is about if the functions in the anonymous namespace should be declared static or not. As an example, I am being told the square3 function which declared with "static" keyword has advantages. namespace { int square2(int num) { return num * num; } ...
1 - Is using a function with static keyword in the anonymous namespace helps with memory/linking time? Static does not affect functions in anonymous namespace as far as the language is concerned. This is because being in an anonymous namespace already achieves the same thing as declaring the function static achieves....
65,952,326
66,210,604
error C2971 a variable with non-static storage duration cannot be used as a non-type argument
Here is a simple example (the idea is to avoid a huge if..else or switch block inside a function): namespace foo { enum class VALUES : int { val_0 = 0, val_1 = 1 }; template<VALUES T> void print(); template<> void print<VALUES::val_0>() { std::cout << "val_0\n"; } template<> void print<VALUES::v...
Here is a way to do so: https://stackoverflow.com/a/66171400/15104979 we just need a storage for all those functions and also they can be not templated. Also for non-members the Callback can be defined like using Callback = void(*)();. But we have to measure both cases: with if/else and Callback, specifically for your ...
65,952,407
65,952,684
How to access objectNames of objects in ApplicationWindow of QML?
How to access objectName of children of ApplicationWindow? With ApplicationWindow: import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.12 ApplicationWindow { id: head visible: true width: 640 height: 480 Rectangle{ height:1; width: 1; objectName: "AA"} Rectangle{ height:1;...
Instead of data, we have to access contentData with respect to ApplicationWindow Component.onCompleted: { console.log("parent.data[0].objectName", head.contentData[0].objectName) console.log("parent.data[1].objectName", head.contentData[1].objectName) } From: https://doc.qt.io/qt-5/qml-qtquick-...
65,952,544
65,962,175
Custom boost serialization input archive fails only with vectors (boost::archive::archive_exception)
I'm working with boost serialization and I have written a custom input archive that derives from boost's binary input archive. Event though this class is for now doing exactly the same as boost's binary_iarchive, I get a boost::archive::archive_exception when deserializing std::vectors of primitive types. I don't get a...
There are two major things missing: Q. As you can see, the InputArchive simply inherits from the appropriate boost::archive::binary_iarchive_impl and does nothing more. A. Yeah, but not in the appropriate way. Your constructor forgets to initialize the archive. Just forwarding to the base class constructor is half ...
65,952,594
65,952,665
Iterate over vectors with n and n*n elements
I have this Google test assertions ASSERT_FLOAT_EQ(longerVector[0], shorterVector[0]); ASSERT_FLOAT_EQ(longerVector[1], shorterVector[1]); ASSERT_FLOAT_EQ(longerVector[2], shorterVector[2]); ASSERT_FLOAT_EQ(longerVector[3], shorterVector[0]); ASSERT_FLOAT_EQ(longerVector[4], shorterVector[1]); ASSERT_FLOAT_EQ(longerVec...
Use this instead for(size_t i = 0; i < longerVector.size(); i++) { ASSERT_FLOAT_EQ(longerVector[i], shorterVector[i%3]); }
65,952,908
65,953,001
Inheritance with same default template arguments
Given the following class: template<typename BoringArg1 = int, typename BoringArg2 = char, typename ThisDefinitionIsSoLong = int, typename WhoWroteThis = double> class A { // ... }; Now I want to inherit from A, keeping it templated: template<typename BoringArg1 = int, typename ...
If all your parameters are of the same sort (types, non-types or templates), you may let B accept a parameter pack template<typename... Args> class B : public A<Args...> { // ... }; This will either forward the corresponding arguments to A, or use the default if the pack isn't long enough.
65,952,954
65,953,341
Function pointer definition inside a class template based on the template variable arguments
using FuncDef = void(int a, int b); template <typename R, typename... Args> class WrongFunction { public: void F1(R(*Fn)(Args...)) {}//error: C2091 function returns function }; template <typename T> class Function; template <typename R, typename... Args> class Function<R(Args...)> { public: void F1(R(*Fn)(Arg...
The follow class template: template <typename R, typename... Args> class WrongFunction { public: void F1(R(*Fn)(Args...)) {}//error: C2091 function returns function }; defines a template parameter API which expects: a return type R, and a variadic number of arguments (of possible different types) Args. Now, a ...
65,953,158
65,953,662
Broadcast STL Map using MPI
I have a variable looks like this map< string, vector<double> > a_data; long story short, a_data can be filled only by node 0. Hence, broadcasting it using MPI_Bcast() is necessary. As we know that we can only use primitive data type. So, how should I do to broadcast STL datatype like map using MPI_Bcast()??
One approach that you can do is to: first broadcast the number of keys to every process; So that every process knows the number of keys that will have to compute; broadcast an array that has coded the size of each of those keys; broadcast another array that has coded the size of each array of values; create a loop to ...
65,953,337
65,953,458
std::istream::unget() setting fail and bad bits if first read failed but not if second or further reads failed
I have the following code: #include <algorithm> #include <ios> #include <iostream> #include <string> #include <vector> std::vector<int> read_ints(std::istream& is) { std::vector<int> res; std::cout << "Please input a list of integers ('quit' to finish):" << std::endl; for (int i; is >> i; ) { ...
Your mistake seems to be thinking that when reading an integer and a non-digit is found that character is consumed. It isn't. Just remove the call to std::unget.
65,953,492
65,953,758
Memory use of one-time use class member variables
I have a C++ class Foo that has a private member variable bar that is only used once by Foo's constructor and is then unused afterwards for the lifetime of a Foo object, i.e. no other method of Foo uses bar. Assume that bar is a rather large object. Assume also that there is a reason why bar needs to be a member of Foo...
My question: Will bar exist in memory for the lifetime of a Foo object, Yes. or will the compiler free up the memory bar occupies after construction of the Foo object? No. If bar uses dynamic memory allocation and supports move semantics (like a vector or string etc), you could however free the resources it's alloc...
65,953,812
65,954,050
Is any C++20 feature test for defaulted equal operator?
I wanted to use defaulted equal operator bool operator ==(...) = default; if only compiler supports it, otherwise I could still use existing implementation. But I cannot find an appropriate feature test in https://en.cppreference.com/w/cpp/feature_test Point me the correct feature test or help to fix this code: struct...
As default comparison is tightly connected to P1186R3: When do you actually use <=>? you may be able make use of the __cpp_impl_three_way_comparison feature test also for the subset case of default comparison. See also P1185R2 (<=> != ==).
65,953,893
65,954,680
Compile time selectable code standard question
For an embedded system, I've written a code that's generating a delay based on a compile-time and run-time selected variable. The compile-time version boils down to writting as much NOP instruction as required for reaching the expected CPU cycle count. The main part is like this: #define IS_CONSTEXPR(...) __builtin_con...
What part of the standard implies that the expression: "constexpr_bool ? variable_or_constexpr : constexpr" is a constexpr ? No part does, because __builtin_constant_p is not a standard function (or a regular function at all), and that ternary would not normally be a constexpr. You're using the documented behaviour o...
65,954,080
65,954,992
Performance difference of making class object then calling function vs using static function with scope resolution operator
Is there a performance difference (memory and speed both being considered no matter how big or small) if you do this: ClassA a; a.functionb(); vs this: ClassA::functionb();
It depends how expensive it is to create an object of the class. If this cheap, there is no difference. This example compiles to the very same binary an thus has the same execution speed. class Foo{ public: static int bar() {return 1;} }; class Foo2{ public: static int bar() {return 1;} }; int main ...
65,954,441
65,954,457
What to do when I encountered wrong answer in codechef
I found the question in CodeChef which asks us to write a program to calculate the sum of the first and last digit of a number N(1 ≤ N ≤ 1000000) for T test cases(1 ≤ T ≤ 1000)(Here's the full problem definition https://www.codechef.com/problems/FLOW004/). I pass the sample input but when submitting gives me the wrong ...
The condition abs(n) > 10 looks wrong. It should be abs(n) >= 10 or abs(n) > 9 to loop until the number becomes one-digit long.
65,954,462
65,954,615
What's wrong with deleting a file?
I wanna delete txt file when the password has a lowercase letter. Creating file code: FILE *files[20]; char filename[20]; sprintf(filename, "%d.txt", i); files[i] = fopen(filename, "w"); string login, pass; //wprowadzanie zmian w licznie kont ...
Take a look at the declaration of the function that you call: int remove( const char* fname ); Pay particular attention to the type of the parameter. It is const char*. The type of the expression to_string(i)+".txt" which you used as the argument however isn't const char*. The type is std::string. You cannot pass an a...
65,955,178
65,955,329
a question about the "getlline" function in c++
https://en.cppreference.com/w/cpp/string/basic_string/getline In this page, the std::getline defined as followed, template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,...
From https://en.cppreference.com/w/cpp/language/template_argument_deduction : Template argument deduction In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from ...
65,955,274
65,955,641
VSCode showing error while running C++ program on g++ compiler
I ran this C++ program (Code on gfg) on VSCode using the run button and it exits with code=1 and shows this message : [Running] cd "c:\Users\pawar\OneDrive\Desktop\cp\" && g++ 5.cpp -o 5 && "c:\Users\pawar\OneDrive\Desktop\cp\"5 In file included from c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\cassert:44:0, ...
#include<bits/stdc++.h> This line was included twice, which caused the error.
65,955,550
65,955,692
Why zero in array in C++ is considered as NULL(using CODEBLOCKS)?
I've entered zero as an integer in an array and when using a function to print array (show()) it exits the function considering the ZERO as NULL. array = {1,2,3,0,4,5} expected output = 1 2 3 0 4 5 output = 1 2 3 Why is it so? Is something wrong with the CodeBlocks settings? Thank you int show(int arr[]) ...
expected output = 1 2 3 0 4 5 output = 1 2 3 Why is it so? In short: Because your loop stops when it encounters an element that is equal to '\0' and 0 == '\0'. To clarify, '\0' is a character literal with the value 0. Character types are integer types. Furthermore, NULL is a macro that expands to a null pointer const...
65,955,632
65,955,721
Can I emplace arguments into a class member without first default-constructing said member?
template <typename StoredT> class InternalObject { public: using RefCountT = unsigned short; template <typename... CtorTs> static void* emplace(CtorTs&&...); Types type; RefCountT reference_count; bool is_immovable; StoredT stored_value; InternalObject(); InternalObject(Stored...
Consider using std::optional<StoredT>, which will allow you to defer the construction of the StoredT that you want to hold: #include <optional> template <typename StoredT> class InternalObject { public: using RefCountT = unsigned short; template <typename... CtorTs> void emplace(CtorTs&&... args) { ...
65,955,805
65,955,969
Solved the given question below but not able to get the final output
A drawer contains socks of n different colors. The number of socks available of i'th color is given by a[i] where a is an array of n elements. Tony wants to take k pairs of socks out of the drawer. However, he cannot see the color of the sock that he is picking. You have to tell what is the minimum number of socks Ton...
The problem is because your trying to assign an int to a variable of type int* here: a = (int)total_socks ; I think what your looking for is a = (int*)total_socks ;. But still it is pointless as your not using the variable again (unless your actually planning on returning it). So is the rest of them, n and k. Theres an...
65,956,508
66,058,025
C++ How do I find the value in the external program pointer address?
I would like to find the value in 0x109B74 + 0xF8. Where did I get it wrong and how should I correct it? Please help me. #include <iostream> #include <string> #include <Windows.h> using namespace std; int main() { HWND hwnd = FindWindowA("AssaultCube", NULL); DWORD procID; GetWindowThreadProcessId(hwnd, ...
0x109B74 is a relative offset, not an absolute address. It needs to be added to the base address of the module at runtime. There are other issues with your code, but the best solution is to replace it all with this: #include <iostream> #include <Windows.h> #include <TlHelp32.h> #include <vector> DWORD GetProcId(const...
65,956,571
65,956,669
How to allocate and deallocate an array of function pointers and keep valgrind happy?
How can I allocate and deallocate an array of function pointers in C++? I've tried two different strategies, first using single pointers and the second using double pointers but I can't seem to make valgrind happy. Here is my situation: // function pointer typedef double(*function_ptr)(double); // function that adhers...
Your make_function_ptr function allocates space for only one function_ptr in the 'outer' table, rather than allocating space for size pointers. So, this: auto **trsfm = (ESfcnTrsfm **) malloc(sizeof(function_ptr *)); Should be: auto **trsfm = (ESfcnTrsfm **) malloc(sizeof(function_ptr *) * size); // Need to mu...
65,957,035
65,957,082
C++ is there another way to access members first and second than using a range for loop for std::vector <std::pair <int, int>>?
I solved another problem the other day involving a std::vector <std::pair<int,int>> called name. My question is, how do I access the name.first and name.second of this type? I ended up using a ranged-for loop, that solved my issue for(i : name) { i->first , i->second} But, is there another way? I am particularly inter...
The usual way for (size_t i = 0; i < name.size(); i++) { cout << name[i].first; cout << name[i].second; } This is just the typical way to access a vector (or array) of structs. BTW the code you said worked in fact does not, for(i : name) { i->first , i->second} should be for(i : name) { i.first , i.second}. ...
65,957,179
65,958,084
Use concepts or SFINAE to check if class has a templated member function with a std::array parameter
Introduction I want to detect, using concepts and/or type traits, if a class has a member function with a std::array parameter. For example: Class below would pass the concept. class OStreamRealizationGood { template<size_t size> uint8_t send(std::array<uint8_t, size> array) }; Up until now, I have used a tric...
Is there a way to write this to ensure that send(array) is a templated function? You can use the template keyword in the constraint to signify that send needs to be a template function: template<typename T, std::size_t size> concept GoodRealization = requires(T t, std::array<uint8_t, size> array) { { t.template s...
65,957,270
65,958,068
std::chrono::milliseconds(2000) vs 2000ms
I am implementing a timer library, In 2nd parameter of std::condition_variable::wait_until, std::chrono::steady_clock::now() + 2000ms is working fine, but std::chrono::steady_clock::now() + std::chrono::milliseconds(2000) is not. Please guide me what I am missing, and how to use later. /* * Inspired by: * https://www...
You're passing a reference to a temporary std::chrono::milliseconds(2000) into Timer::once(), and subsequently into the lambda. The temporary stops existing at the end of the full-expression (the ;), so sleep_duration becomes a dangling reference when the lambda is executed in another thread. Pass sleep_duration by-val...
65,957,465
65,958,196
C++ Boost: determinant and inversion of complex matrix
Do you know whether boost has functions that can calculate the determinant and the inversion of a complex matrix? The matrix dimension isn't large (less than 50). Inversion: Input: matrix M = A +i*B with A,B two real matrices of dimension (n x n) with n <50. Output: Inversion: matrix N = C + iD with C,D two real matri...
Finally I know why these operators on inversion and determinant of matrices aren't implemented. It's because we have closed-form solution of these 2 operators from classical operators on real matrices. For matrix inversion: we have this closed-form solution https://fr.mathworks.com/matlabcentral/fileexchange/49373-comp...
65,958,560
65,959,013
error: no suitable user-defined conversion from "Data" to "std::__cxx11::string" exists when using icc 17.0
I am getting a compiler error when I am trying to compile with specific compiler version. ie. icc 17.0 with -std=c++17 -O3 Compiler Error: source>(19): error: no suitable user-defined conversion from "Data" to "std::__cxx11::string" exists Data temp{std::forward<Data>(d)}; ^ compilation aborted f...
This is yet another curious example of when the fickle aggregate strikes, here alongside an arguable bug in the ICC compiler (version 17.0). Data is an aggregate class in C++14 and C++17 (but not in C++11) In C++11, an aggregate class was defined as, as per [dcl.init.aggr]/1 (N3337) [emphasis mine]: An aggregate is a...
65,958,614
65,958,920
Compile-time what is the largest value that can be squared without overflow (integral types)?
In C++, is there a compile-time way to compute the largest value of an integral type T that can be safely squared, i.e. that mathematically x * x <= std::numeric_limits<T>::max() so that if the operation x*x were to be performed, it would not cause undefined behavior (for signed types) or overflow (for unsigned types? ...
Set the lower half of the bits. For signed types, add 1 and then divide with sqrt(2) #include <climits> #include <limits> #include <type_traits> template<class T> constexpr T largest_squareable() { static_assert(std::is_integral_v<T>, "Must be an integral type"); if constexpr (std::is_unsigned_v<T>) { ...
65,959,132
65,959,203
C++20: generate type from given variadic types
Lets say, I have a variadic type list which can grow e.g. #define MY_TYPES void, float, int, vector<long>, ..... I am looking for way to generate these type definition at compile time in c++17/20 in generic way, e.g. #define to_tuple(MY_TYPES) ==> std::tuple<future<void>, future<float>, future<int>....> using tupleT...
template <typename ...P> using tuple_of_futures_t = std::tuple<std::future<P>...>; using X = tuple_of_futures_t<void, float, int, std::vector<long>>;
65,959,514
65,959,731
Count letters in string
Can someone help me. for example I input for x RandomName for y and it needs to count each y letter in x word, and output should be. a: 2 n: 1 d: 1 void counter(string x, string y) { int signs[100]; int amount = 0; for (int i = 0; i < y.length(); i++) { signs[i] = y[i]; for (int j = ...
There are several errors in you code: You always compare x[i] to y[i] ignoring the j index completely, which means you will never count a letter that is not in the same place in both strings. You have a signs array you assign values to, but never use it. Also, it has the size 100, but for what? You never reset the a...
65,959,805
65,959,806
How to create a java string in JNI C++?
How can I create a String from C++ and send to a method in java? Suppose I have an env and I need to simply create a jstring to send to a method. How can I do that?
env->NewStringUTF("Hello world") So you can use like this: jobject result = env->CallStaticObjectMethod(myClass, myMethod, env->NewStringUTF("Hello world"));
65,960,187
65,960,439
Is it possible to calculate function length at compile time in C++?
I have this piece of code: constexpr static VOID fStart() { auto a = 3; a++; } __declspec(naked) constexpr static VOID fEnd() {}; static constexpr auto getFSize() { return (SIZE_T)((PBYTE)fEnd - (PBYTE)fStart); } static constexpr auto fSize = getFSize(); static BYTE func[fSize]; Is it possible to decla...
There is no method in standard C++ to get the length of a function. You'll need to use a compiler specific method. One method is to have the linker create a segment, and place your function in that segment. Then use the length of the segment. You may be able to use some assembly language constructs to do this; depends...
65,960,605
65,961,823
Minesweeper SFML code issue with revealed board
I have problem with this code. This is Minesweeper game. The game is good, but when I move the cursor outside the game window, the whole board is revealed to me. How to fix it, does anyone know? Could you help me with this problem? I think the problem may be checking the cursor location, or the way the table is filled....
It looks like you are updating x and y grid positions whether a mouse button has pressed or not, on this line: if (sgrid[x][y] == 9) sgrid[i][j] = grid[i][j]; Also, it looks like you are checking the display sgrid[x][y] instead of the data grid[x][y] at the mouse click location. What you'll most likely want to do is a...
65,960,672
65,969,661
iOS Metal shader language how to flip order of values inside float2?
If I have a struct in the metal shader language: How do I access individual struct (like float2) elements and flip their order? const float2 sampledCameraPoint = cameraSamplePatternBuffer[vertexID]; // (has x and y) const float2 flipped = float2(?, ?) // how to get (sampledCameraPoint.y, sampledCameraPoint.x)?
You can access the elements using x, y etc, so this should work: float2 flipped = otherFloat2.yx;
65,961,121
65,961,927
why i get "no attirubute error" when i try to call python function from c++
Hi' i follow this tutorial to call the python function from a c++ code. This is embeddedPython.cpp #define PY_SSIZE_T_CLEAN #include <Python.h> #include <iostream> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(std...
The name of your Python file is test.py but there is already a Python module test for regression tests (see Python documentation) which doesn't contain a multiply() function. Rename your python file to avoid collision with existing modules. The example in the tutorial uses multiply.py which works. I used test1.py which...
65,961,242
65,961,335
Cannot enter while loop. Is it to do with using an unordered map?
I am trying to do a coding challenge where we have to shorten and minimise direction instructions. I am using an unordered map prior to implementing the while loop. The rest of the code works as expected but the while loop cannot be reached so I cannot output an appropriate value. std::vector<std::string> dirReduc(std:...
Your issue is that you're trying to do both x and y in the same loop. This means every loop you must push_back an east or west AND push_back a south or north. But that doesn't make any sense. What if you don't have the same number of each? Instead, you should use two loops: while (x) { if (x<0) { x++; ...
65,961,667
65,961,726
Find if structures with same values exist in vector array
I want to check if there are structures with the same values in the vector array. May someone explain to me how should I do this? struct mineCoordinate{ int x; int y; }; std::vector<mineCoordinate> mines; // vector array if(std::find(mines.begin(), mines.end(), mineCoordinate{userInputX,userInputY}) != mines.end()) {...
What seems to be missing from your code is a definition of what it means for two of your mineCoordinate objects to be equal. If you add this bool operator==(const mineCoordinate& a, const mineCoordinate& b) { return a.x == b.x && a.y == b.y; } then I think it will work too. You might have thought that this definit...
65,962,708
65,962,740
"expected a qualified name after 'typename'" when I try to use iterator inside of a templated function
I want to make a function that takes a container T (can be vector, map, list...) as template and a T and a Int as arguments, in this function, we're assuming that T is a container of int, and I want to return the first occurence of the int in the container. Here's the function: template <class T> int & easyfind(T conta...
T is a type, not a template. You need typename T::iterator it; to access its iterator type member. The reason you see code like std::vector<int>::iterator is because std::vector is the name of a template, and you need to specify the template parameter. In your case T is already an instantiation of a template, so th...
65,962,929
65,962,992
function is being redefined somewhere and I cannot see where I am doing it
I am getting this error and I can not figure it out can someone please help explain what I am doing wrong? I have tried removing some of the include statements as well as creating a makefile for my project but I keep getting the same errors This is my Token.h #pragma once #include <string> #include <iostream> enum Tok...
Your error message tells you file named and lines in each file. Line 11 of the CPP and line 40 of the header file. Delete the body (the stuff in {}) part of thr=e function in the header file )reppacing it with a ;), or delete all mention of the function in the cpp file. Both work.
65,963,111
65,963,239
Should I read and write from the same file?
According to Reading and Writing from same file?, if I use 2 streams (one input, and other output) to read and write from/to a file, I have to flush the output one before opening the input one for reading. But suppose I'm writing a voice recorder. I might want to go back into some point to play. Flushing the file for r...
Yes, std::fstream supports both reading and writing using the same file stream object. Since you initially didn't show your code, I could only guess that you are not setting the file position pointer properly. When using seekg() or seekp(), keep in mind that in case of file streams, these both refer to the same positio...
65,963,238
65,963,347
How do I convert chrono::steady_clock::duration to ostream?
ostream& operator<<(ostream& os, const TimedEvents& t) { os << "Execution Times:\n--------------------------\n"; for (int i = 0; i < t.nEvents; i++) { os << os.width(21) << t.events[i].name << ' '; os.width(13); os.setf(ios::right); ...
You don't want to convert it to std::ostream, you want to convert the duration object to a type that can be inserted into an output stream (like an integer, double, ...). os << t.events[i].duration.count(); Or overload the std::ostream& operator<<(std::ostream& os, chrono::steady_clock::duration duration) to define ho...
65,963,616
65,964,335
C++ tbb flow graph, multifunction_node giving incomplete type error
Far as I understand, incomplete type error happens when there's forward declaration without full specification of type, then instantiate that type since the compiler can't tell the size of such type. In my case I don't understand how this code produces such a problem. For simplicity I've removed unrelated parts. class ...
Isn't the type PartialResult fully specified already? Yes, but that is not what the error message complains about. The error message should be read as "error: incomplete type ‘[name of the incomplete type]’ used [place where it is used]". The incomplete type is std::tuple_size<FilterOnNode::PartialResult*>, not Parti...
65,963,888
66,129,687
SHA512 hash in crypto++ library throws exception
I built crypto++ 8.4 in visual studio 2010 and made some test code. It works fine in 'Win32|Debug', but in 'Win32|Release' hash.CalculateDigest throws an exception. string source = "I am a programmer."; CryptoPP::SHA512 hash; CryptoPP::byte digest[CryptoPP::SHA512::DIGESTSIZE]; hash.Calcula...
I have found definite case of an exception. If 'hash' is declared as a pointer rather than a local variable, no exception is raised. CryptoPP::SHA512 * hash = new CryptoPP::SHA512; I don't know why this is happening, but in the case of SHA512, I doubt that there is a memory management problem in cryptopp in VS 2010.
65,964,102
65,964,128
C++ Thread: How to pass parameter in main thread to another thread with lambda function
I am trying to pass a bool flag from the main thread to another thread with lambda function, but it does not seem to work. My idea is to create a LED_thread blinks LED every one second while the main threaddoes something else. Once the main task finishes, the stop_blink_flag will turn on and the LED should stop blinkin...
Right now you are passing the variable by value - the lambda makes a copy. To pass it by reference instead - so the lambda accesses the original variable - just put & before it: // before std::thread LED_thread{ [stop_blink_flag] { // after v std::thread LED_thread{ [&stop_blink_flag] { Note that sinc...
65,964,320
65,966,946
Unordered_map of unordered_map vs custom hash function for pair key C++?
I have some keys that are pair<string, string>. I was originally going to write my own hash function but thought that it might be easier to just implement an unordered_map<string, unordered_map<string, val>>. Are there any performance differences between these two I should be aware of?
I would use std::unordered_map<std::pair<std::string, std::string>, Value, [pair_hash][1]> for two reasons: Performance Of course, you can measure your two versions with your favorite profiler, but basing on my experience - the number of allocation is what matters here the most - so see: flat_map.insert(key, value));...
65,964,384
67,724,531
How to make clang-format 11 put a space after variadic template decleration
I'm not sure what's going on and how to accurately describe it. Here's the source code template <typename ...Args> void foo(Args &&...args) { bar(std::forward<Args>(args)...); } My friend with clang-format 10 on Ubuntu generated this template <typename ... Args> void foo(Args &&... args) { bar(std::forward<Arg...
Since I had the same issue, after some git bisecting, I found the commit that introduced this change: https://reviews.llvm.org/D83564 clang-format does not obey PointerAlignment: Right for ellipsis in declarator for pack The reasoning behind this change is that you can either consider the annotation &&... part of the...
65,964,418
65,966,750
Creating a DLL for a group of .cpp, .h files
I have a legacy project, containing a bunch of .cpp, .h files. I want to create a DLL file for this entire project so that I can use it from Java code. I am not sure how is it done. I found some tutorials on creatign DLL using visual studio, but they mostly create a brand new project. Any input would help.
You still would have a brand new project of API between your old code and application. And note that .dlls are limited in what they actually can do or can use. SO you may start with building new .dll from scratch with function that represents the interface, then add your C++ code later.
65,964,670
65,965,608
Filling a 2*n room with two different tiles
I came across a problem where I have to fill a rectangle having 2 rows and n columns. There are two tiles one 1*2 tile and second a L shaped tile of larger sides having dimension 2 units and smaller sides having dimension 1 units. I solved it through dynamic programming and am not pretty sure if it is working all righ...
Using approach from my first comment. l[3] configuration: L[3] configurations: #include <iostream> using namespace std; int tileways(int n) //n=no.of columns of the rectangle. { int l[20];//straight border int L[20];//extra square l[0] = 1; l[1] = 1; L[0] = 0; L[1] = 1; for (int i = 2; ...
65,964,929
65,965,095
What's the issue in this merge sort algorithm in c++
I have learnt this from gfg course even the link they have given for the code is similar code I have written but still not able to find the problem in this: #include <iostream> #include <algorithm> using namespace std; void merge(int a[], int low, int mid, int high) { int m = mid - low + 1, n = high - mid; in...
You are confusing your m variable (size of left array) with mid (last index in left array) Instead of this: for(int j=0;j<n;j++){ right[j] = a[m+j]; } This: for (int j = 0; j < n; j++) { right[j] = a[mid + j + 1]; } Pro-tip: One letter variables are fine as an index in a for-loop. But for anything else give t...
65,965,157
65,965,283
error: cannot initialize return object of type 'const char' with an lvalue of type 'const char [34]'
I am a new to g++. I am trying to compile this simple code. However, has this error. error: cannot initialize return object of type 'const char' with an lvalue of type 'const char [34]' #include <boost/python.hpp> char const doYouDo( const char* jobs ){ return "Hello, I am an embedded engineer."; } BOOST_PYTHON_M...
"Hello, I am an embedded engineer." ... is a String Literal, it has a type of const char[] and your function is defined to return a single constant character (char const), hence your error. What you can do: Since you can't return C-style arrays by value in C++, you can return a pointer instead: char const* doYouDo( c...
65,965,225
65,965,267
Why is c outputting without any decimals in the command line?
#include<iostream> #include<iomanip> #include<cmath> using namespace std; int hypotenuse(double x, double y) { double z; z = sqrt(x * x + y * y); this should equate to square root of 81 + 225 return z; } int main() { double a, b, c; cout << "Enter the lengths of the two legs of a right triangle: "; e...
Because your function is returning int not double that is why you are getting just 17. Here int hypotenuse(double x, double y) Change it to: double hypotenuse(double x, double y)
65,965,238
65,965,895
Range based for loop through non-const literal c++
Compiler context: I am compiling with GDB v8.3 Ubuntu with options g++ -Im -O2 -std=c++0x. Very frequently I need to complete some loop for two or three objects so I use wrap the expression in a range based for loop with a containing litteral. In Python3 this would look like: a = [1,2,3] b = [4,5,6] for v in (a,b): ...
int x,y; for(int& i:{std::ref(x),std::ref(y)}){ i=7; } auto& won't work, and you do have to repeat std::ref for each element. Another trick is: auto action=[&](auto&foo){ // code }; action(v1); action(v2); You can write: void foreach_arg(auto&&f, auto&&...args){ ((void)f(decltype(args)(args)),...); } or pre-...
65,965,420
65,965,513
How to make a function that uses incomplete type objects
I want to make a class one that can build up class two by func1. I have two type of class overloading. The primary template class, and the overloading template specialization class. Primary class one is fine. But class one<void> can not implement func1. The compiler complains return type 'class two<void>' is incomplete...
To avoid errors related to incomplete types the one::func1 method can be defined after two. It can be declared like this: template<> class one<void> { public: two<void> func1(); }; And then, after two has been defined: two<void> one<void>::func1() { // ... }
65,965,865
65,971,803
Is it possible to write a type trait that checks if a type is a specific type with an addition?
I have a type: struct A {} template<typename T> constexpr bool is_A_v = false; template<> constexpr bool is_A_v<A> = true; // here I don't know how to apply std::remove_cvref_t<?> before checking? I am new to type traits so any help is appreciated.
Based on the comment, you're look for: template <typename T> inline constexpr bool is_A = std::is_same_v<std::remove_cvref_t<T>, A>; In C++20, you could spell this as a concept: template <typename T> concept is_A = std::same_as<std::remove_cvref_t<T>, A>; Which has some slight syntactic advantages, but also prevents ...
65,966,354
65,966,416
error in conversion of 2d array in C++ functions
#include<iostream> using namespace std; int add(int x[2][2], int y[2][2],int z[2][2]); int main() { int a[2][2], b[2][2]; cout << "Enter two matrices to add them " << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cin >> a[i][j]; } } cout << endl; ...
cout<<add(a[2][2],b[2][2])<<endl; should be cout<<add(a,b)<<endl; This is a very common misunderstanding. To reference an array you use the name of the array (i.e. a or b) not the array and it's dimensions (i.e. a[2][2] or b[2][2]). You only need the dimensions of the array when you are declaring it, not when you are...
65,966,744
65,967,626
10 digit number gets inputted differently in text file
I am trying to create a phonebook using CPP and filesystem method. When I enter the 10 digit phone number, it gets stored as some other random number than the input number. However, when I enter numbers uptill 9 digits, it gets stored and outputs perfectly. Why is this change happening only in 10 digit number? I have e...
Consider phone number belongs to same city or region you are! as 6 up 9 digits integer number! But when phone number belongs other city or country, and it starts with one 0 or 00 or + sign, how you read/write it as number! change number from long int to string!
65,966,945
65,971,542
std::stoi not throwing std::invalid_argument
If I am doing something like this: #include <iostream> #include <string> int main() { std::string s = "123abc"; auto i = std::stoi(s); std::cout << i; // prints 123 } The program is not throwing any exception. What to do in case I want an exception instead of 123 here?
Using the pos argument of std::stoi, I was able to write the following function, which does the job for me. #include <stdexcept> #include <string> int stoi_strict(const std::string &str, int base = 10) { int res; std::size_t pos = 0; try { res = std::stoi(str, &pos, base); } catch (const std::i...
65,966,969
66,333,485
Why does march=native not work on Apple M1?
Whenever I try to compile any C++ program with march=native on a Macbook with a M1 chip, I get the following error when using clang: clang: error: the clang compiler does not support '-march=native' However, it used to work on an older Macbook with an Intel CPU. Does clang not support this architecture (yet)? clang --...
As far as I know this is not Apple M1 specific, it occurs also with clang for various other architectures (mostly various other arm processors). e.g. See this bug report here https://github.com/DMOJ/judge-server/issues/303 Basically every build of clang for a new architecture must choose to provide defaults for "march=...
65,967,124
65,967,193
std::tie for C++17 struct operator<?
Consider the following C++17 struct: struct S { M1 m1; M2 m2; M3 m3; bool operator<(const S& that) const { return tie() < that.tie(); } auto tie() const { return std::tie(m1,m2,m3); } }; Is this correct? Will S::tie return a tuple of references to the members, or will it take a copy? Will auto deduce the ...
Is this correct? Yes, although that may depend on what you are intending to do. Will S::tie return a tuple of references to the members Yes. or will it take a copy? No. This is easy to verify by trying it with a non-copyable type. Will auto deduce the correct type (a tuple of references) ? Yes. This won't be n...
65,967,233
65,969,662
Lazy shared pointer - assignment operator
I have created simple lazy shared pointer class. However, currently I can have only single instance of it and my design does not support copy assignment. /// <summary> /// Simple lazy shared pointer /// Pointer is initialized when first needed /// /// Create new instance with CreateLazy static method /// /// Copy is ...
Here's a sketch - not tested, with missing pieces that should be easy to fill in. I hope the general idea is clear. template <class T> class LazySharedPtr { struct ControlBlock { std::shared_ptr<T> ptr; std::function<std::shared_ptr<T>()> factory; std::shared_ptr<T> InitAndGet() { // Add thread safe...
65,967,313
65,967,403
If an old C++ compiler doesn't implement a new keyword, is it wrong to define it away?
I am maintaining a library that is still supported on older compilers, one of which is Visual C++ 2013 on Windows. So far we've been extremely conservative and stuck to C++03; we're now moving to C++11. VC++2013 supports most of the newer features, but it doesn't recognize noexcept. Of course the canonical way to add...
Since it wasn't a keyword in the old standards, you were, and technically still are allowed to define such macro when targeting the old standard. P.S. The typical definition for pre-C++11 is to use throw() in place of noexcept. P.P.S. Note that in the case of noexcept, the macro doesn't work for declarations such as vo...
65,968,619
65,969,351
How is std::forward_list emplace_after O(1)?
I'm currently implementing a forward list (Singly linked list). I noticed that std::forward_list::emplace_after is O(1), so the complexity is constant: How is this possible? I'm asking because: You can have the position of the new element to be in the middle, As far as I know, the only way to find the position where a...
You seem to have a misunderstanding about how iterators are supposed to work in singly linked lists. They are not just an identifier you can (and have to) search for, they should point to an actual node in one way or another. Illustration: Iterator ------------------+ | ...
65,968,779
65,969,389
Can giving same variable names to actual and formal parameters in C++ create any problems?
Can giving the same name to formal parameters in the called functions as the actual parameters in the calling function create any problems while passing by reference? Also, would it be any different while passing by value?
If you are talking about stuff in picture, simple answer is it does not matter at all. In "pass by value" case, value of caller function is copied to the address of parameter of called function. When it comes to references, here is one quote: A reference shares the same memory address with the original variable but a...
65,968,789
65,969,783
Direct initialization fails with class derived from std::tuple, while it works for std::pair
from time to time it happens that I want to change a type I defines via using by a real class. For example I here a sample, how I can use a struct the same way as a type: using t_int_pair = std::pair< int, int >; struct s_int_pair : public std::pair< int, int > { using std::pair< int, int >::pair; // inherit ctor }...
I started from splitting the instruction into two parts (with the old-style initialization to bypass any problems related to std::initailizer_list, if any): s_int_triple s( 0, 0, 0 ); auto [b1, b2, b3] = s; The compiler error reads: main.cpp:27:10: error: cannot decompose class type ‘std::_Tuple_impl<1, int, int>’: ...
65,968,989
65,969,258
No instance of overloaded function when resizing
I got an error of "No instance of overloaded function" when I used resize(). I'm aware that what's inside of resize() might be wrong as well. I'm trying to resize x, an array of floats to all zeros. Not sure if std::vector>(0, 0) would be the right syntax for it as I am very new to C++. How do I solve the existing erro...
This: x.resize(Xf.size(), static_cast<std::vector<float>>(0, 0)); should be x.resize(Xf.size()); // or x.resize(Xf.size(), 0.f); if you want to be explicit and this: x[k] += x[k] * std::exp(expval); should be: x[k] += a_function_that_converts_a_complex_float_to_a_float(x[k] * std::exp(expval)); The implementatio...
65,969,224
65,969,390
c++ templates and inheritance, can templates be more selective
Can templates be limited to a class that inherits from other class. for example template<T>, T must inherit from Foo in order to be used in a template function or class. For example I have a class that requires a controller, this controller will be created in class constructor, but I need to know the type of a control...
If you want to only allow only Ts that derive from a certain interface you can use SFINAE (substitution failure is not an error). Here is an example: #include <type_traits> struct Base { virtual ~Base() = default; }; struct Derived : Base {}; struct NotDerived {}; template <class T, class = std::enable_if_t<std...
65,969,323
65,970,083
Why binding 2 openGL sampler1d texture doesn't work?
I want to pass two 1d textures into my fragment shader. I am creating two sampler1d textures, bind them to my shader program but seems that both samplers use same texture. When I use sampling texelFetch for texture1 it takes wrong color I have defined in texture2. Following Shader program returns me GREEN screen when I...
Actually, the bind point for both texture sampler uniforms (texture1 and texture2) is the default (0) as the bind point is never set. glUniform specify the value of a uniform variable in the default uniform block of the currently installed program object. The uniform location is just a number that addresses a uniform i...
65,969,435
66,002,583
Undefined symbols for architecture x86_64: "_PyUnicode_Type", referenced from: when using python_boost
My environment is using Anaconda/Python 3.7.9 on Mac OSX Catalina. I have installed boost_python for conda boost #include <boost/python.hpp> char const * doYouDo( const char* jobs ){ return "Hello, I am an embedded engineer."; } BOOST_PYTHON_MODULE( what ){ boost::python::def( "doYouDo", doYouDo); } then com...
It solved with python-config --ldflags My final gcc command is below. aiwave is my anacond env name $export LIBRARY_PATH=/Users/whitebear/anaconda3/envs/aiwave/lib/ $g++ -fPIC -Wall -I/Users/whitebear/anaconda3/envs/aiwave/include/boost/python/ -I/Users/whitebear/anaconda3/envs/aiwave/include/python3.7m/ `python-config...
65,969,445
65,971,073
Accessing C++ class state via Lua wrapper yields garbage values
I'm trying to expose a simple C++ class to Lua via Lua's C API. I know there are libraries that already solve this problem but I would like to understand how to do this with just the C API. Here is my program: #define LUA_LIB #include <cassert> extern "C" { #include "lua.h" #include "lauxlib.h" } namespace { cl...
There are 2 problems: You allocating memory auto **__obj in lua function new, but acessing as auto *__obj in lua function foo_get_state. Memory leak - you're missing functionality to collect garbage for new Foo() It is not good to mix metatable with data object, but in your case it should work like: int foo_new(lua_S...
65,969,492
65,969,722
Removing Constants from a string
I write a code to remove constants from a strings and return vowels. My code is not working for the string which have numbers of words separated by space. Here is my code: int T;// integer T denoting the number of test cases. For each test case, we input a string. cin>>T; string s; char arr[10] = {'a', 'e', 'i', 'o...
The above error is because while entering the input through command line C++ omits the data after space so it reads the data only before the space that's why you are getting the vowels present only in the first half. Three ways to over come this error. to use getline to read the string with spaces the new altered code...
65,969,627
66,156,473
QuickFix C++ and SSL: Issue connecting to LMAX using sTunnel
Goal: Using sTunnel with QuickFix C++: To login to the LMAX UAT over SSL-internet and send FIX 4.2 messages over a TCP connection. Another similar SO question can be found here, but doesn't appear to solve this particular issue. OS: Ubuntu 19.10 | sTunnel version: 5.55 | Engine: quickfix-1.15.1 | Venue: LMAX [UAT-LD4] ...
SOLUTION: It appeared that indeed the IP address (as helpfully noted by @Christoph John) had not been correctly whitelisted by the server-side. However, the problem persisted. In the sTunnel configuration, I had to change sslVersion = TLSv1.1 to sslVersion = TLSv1.2. As well as this, it appears that the UAT would not a...
65,969,774
65,970,132
C++ openssl: editing ciphersuites
I have very basic C++ application that uses openssl library. Application sends request to server and the list of ciphersuites have to be the next: 4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53 (Codes of ciphersuites can be found here: https://learn.microsoft.com/en-us/dotnet/api/system.ne...
According to the man3 SSL_set_ciphersuites the cipher suits TLS_ECDHE_* in your list are not valid for the function. Valid TLSv1.3 ciphersuite names are: TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1305_SHA256 TLS_AES_128_CCM_SHA256 TLS_AES_128_CCM_8_SHA256 Are you sure the server you are trying...
65,970,232
65,970,395
Do I have to include List as a header in c++ when Im using it?
I currently started programming in C++. My question is, whether when Im working with Lists I have to include this as a header file etc.? Im working with this reference: https://www.cplusplus.com/reference/list/list/ How can I know when I have to include something as a header file in general? Thanks in advance.
In general, yes; otherwise, your code won't compile. But when writing C++ there is always these considerations: Do you put the include in your header or the cpp file? If your class or function header file doesn't require the include, then put it in your cpp file. This reduces compile time dependencies. Does your fil...
65,970,403
65,970,672
Can't convert string to lower case
I'm trying to convert string to lower case, here is my program: #include <iostream> #include <algorithm> #include <string> using namespace std; int main(){ string a; getline(cin, a); transform(a.begin(), a.end(), a.begin(), ::tolower); cout << a; } When I build the program, I get the warning: C4244 '...
Your use of tolower has undefined behavior! The cppreference page on std::tolower tells you exactly what to do to fix it: Like all other functions from <cctype>, the behavior of std::tolower is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely w...
65,970,482
65,970,838
occasional *** stack smashing detected*** with c++
I have following C++ code for bubble sort. This code compiles without any error, but when I re compile and run, I get *** stack smashing detected ***: terminated As a C++ newby I want to know ,why do I get these occasional errors when it runs? void bubbleSort(int eatenPanCakes[10],int arrSize){ int temp=0; ...
You program is accessing array beyond its size which is an undefined behavior. Check this for loop condition: for (int j = 0; j < arrSize-i; j++) [I believe, arrSize value is 10 as the type of eatenPanCakes array is int [10]]. when i is 0, arrSize-i value is 10 and in last iteration when j value is 9, this statement ...
65,970,628
65,970,750
Triangle isn't rendering correctly
I'm trying to render a 2D triangle that rotates after time but it is not rendering correctly. It starts with an normal triangle but than transforms itself into someting that i cant explain at all. Can someone explain what is going on here? What i mean as a video: https://imgur.com/a/aWilS6Q ... ... Here is how im bu...
You're missing a glClear(GL_COLOR_BUFFER_BIT) call. As a result you draw the rotated triangle over the previous one.
65,970,670
65,971,414
How do I use a templated class as an argument type?
I am new to C++ and I know this is very basic, but I couldn't determine the correct keywords to find a solution to this particular problem I'm having. So say I have two classes: Food and Dog. Food is a template class. I then want to pass a food object as an argument into a function called "eat" in Dog. What is the best...
You don't need to make the whole class dog template, you might just have template method: template <class T> class Food { public: Food(T value) : value(value) {} T value; }; class Dog { public: template <typename T> void eat(Food<T>) { std::cout << "Eating food\n"; } }; int main() { Food<int> fo...
65,970,700
65,970,939
how to copy to array inside struct?
How to copy to flexible array inside struct in c? #include <stdio.h> #include <string.h> typedef struct { int val; char buf[]; } foo; int main() { foo f; f.val = 4; // f.buf = "asd"; -> invalid use of flexible array member memcpy(f.bu...
You may want to read information on flexible array member here. It seems as, when using a flexible array in a struct there must be at least one other data member and the flexible array member must be last. And also you may have an element of clarification concerning the usage of flexible array members in C here
65,970,749
65,971,209
C++ openssl: setting list of ciphers
I have very basic C++ application that uses openssl library. Application sends request to server and the list of ciphersuites have to be the next: 4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53 Using SSL_set_cipher_list and SSL_set_ciphersuites I am setting list of ciphers. But when I use ...
255 is a special cipher suit identifier. Reading RFCs when you deal with security is always useful. RFC5746 3.3. Renegotiation Protection Request Signaling Cipher Suite Value Both the SSLv3 and TLS 1.0/TLS 1.1 specifications require implementations to ignore data following the ClientHello (i.e., extensions) if they d...
65,970,801
65,971,765
Transferring variables with object reference. With or without &?
#include <iostream> class class1 { public:int number = 2; }; class class2 { public: void method(class1 &obj) { obj.number; std::cout << obj.number; } }; int main() { class1 c1; class2 c2; c2.method(c1); } What is the difference between running the void method(class1 &obj) wi...
To make it very simple, Pass by value means the actual value is passed on. Thus you need to copy this value to a variable to use it. void method(class1 obj) Pass by reference means a number (called an address) is passed on which defines where the value is stored. The address is passed and then no copy is done and the ...
65,970,834
65,970,905
Calories consumed based on the number of items and type of food eaten
Write a program that asks the user to input how many prosperity burgers (either single or double patty), twisted fries, drinks and 3 other available menus from McDonalds that he or she actually ate and then reports how many calories were consumed. At the end of your program, you need to display some wish for CNY. For e...
Variable name shouldn't contain spaces According to a rule to declare varaible name in C++ Variable name must begin with letter or underscore. It should not start with numbers It should not contain spaces No special symbols are allowed other than underscore. It must be declared as BeefProsperityBurgerSet or Beef_Pro...
65,970,867
65,971,130
Taking union as a method parameter
I wanna write a method taking different type of method pointers using argument polymorphism. I thought union will be a good idea in this situation. However, I don't know how to reference to the correct union instance using method argument. #include <iostream> union Method { struct { void (*a)(); void (*b)(in...
You are correct, you "don't know how to reference to the correct union instance". That's how unions work. There's nothing about a union that indicates which instance of a union member is the one that's set. Some other, out of band, mechanism must be used to track that, and it is your responsibility to implement it, and...
65,970,931
65,971,043
What is the type of arr in T(&arr)[N] here
I came across this function below while learning about templates template<typename T, int N> int length(const T(&arr)[N]) { return N; } int main(){ int nums[]{1,2,3,4}; int len = length(nums); } I used __PRETTY_FUNCTION__ to understand what's going on, output is int length(const T (&)[N]) [with T = int; int N...
What is the type of arr here? It is const T (&)[N] i.e. reference to an array of N objects of type const T. Note that this function template (or nearly identical) already exists in the standard library (by the name std::size), so there is no need to re-write it.
65,971,294
65,982,730
Call Boost Python functions from simple python classes/functions
I have classes defined in C++ code, and added to the python dictionary like this: try { Py_Initialize(); } catch (bp::error_already_set &) { parse_python_exception(); } main_module = bp::import("__main__"); main_namespace = main_module.attr("__dict__"); bp::class_<Gamefunctions> gamefunctions_binding = bp::cla...
After a long searching, I found this page here: Boost Python - Global and Local dictionary I already knew, there is something with the local and global scopes, but I approached the probmem from the wrong direction. I tought, I need to link the inside classes somehow in the python function/class itself, but actually I n...
65,971,342
65,974,513
FFmpeg Change audio filter parameters during runtime
I am making a music app where the user can add FX to playing music through a pad. I am using FFmpeg in C++ to dsp. In FFmpeg you can create an audio filter and set it parameters just like the following: beat_fx = avfilter_get_by_name("aecho"); beat_fx_ctx = avfilter_graph_alloc_filter(filterGraph, beat_fx, "ech...
I asked this question through ffmpeg mailing list and this is the answer I got It is currently not implemented, because nobody needed such feature. Latest git ffmpeg master, have T support for agate and >acompressor and couple others.
65,971,519
65,981,640
Reduce the time needed for a database to be read
I'm writing a program in which I have to read a huge amount of data from a database (Sqlite) and then display the obtained values in a window. I need to refresh the windows each second, so the operation of reading the all data need to last less then a second. The database is composed by two columns a primary key and a ...
If you must SELECT many rows with SQL, your best bet is to do it with one SQL SELECT statement to get all the rows you want, in a multi-row result set. Instead of issuing one SELECT for each ID value you want, issue SELECT ID, ZPOS FROM TABLE` and set up your code to read multiple rows. That being said, I guess you're...
65,971,841
65,972,237
Using CMake and not able to run program without getting "LINK : fatal error LNK1104: cannot open file 'src.lib'" error
I'm trying to get my head around CMake and have been testing it out in Visual Studio Code on Windows 10 with a simple project that has a couple of header files and compiles with no issues when done manually. I've run cmake .. successfully from the build folder, but upon running cmake --build . I get the above error in ...
The underlying problem is this: target_link_libraries("${PROJECT_NAME}" PUBLIC src) This tells CMake to link to a library named src. However in the src/CMakeLists.txt the libraries are called. imperial_to_metric and metric_to_imperial add_library(imperial_to_metric imperial_to_metric.cpp) add_library(metric_to_imperi...
65,971,903
65,971,983
I'm getting an error for my c++ code when my input string contains spaces
Problem Link :https://leetcode.com/problems/longest-substring-without-repeating-characters/ class Solution { public: int lengthOfLongestSubstring(string s) { if(s.length()==0) return 0; if(s.length()==1) return 1; int ans=0; int len=0; //s.erase(r...
for(int i=0;i<s.length();i++) { if(count[s[i]-'0']==0) { The value of ' ' (0x20) is smaller than the value of '0' (0x30), so s[i]- '0' is a negative value for s[i] containing a space char. The conversion of this value to size_t (the type used for indices) yields a value pretty close to the maxim...
65,972,490
65,972,550
To read fileName as commandLine argument and perform file Operation "open" in c++98 Linux
I am reading abc.cpp file which is placed under /home/documents/abc.cpp. To open file I am performing file operation open("t.open("/home/documents/abc.cpp"). where i am able to perform open operation on file. I want to try to read file name using command line argument. so what i am trying here is in command line ./a.ou...
t.open(file.c_str()); will solve your problem. Until C++11 the only function declaration was void open( const char *filename, ios_base::openmode mode = ios_base::in ); The error message informs you very clearly: no known conversion from ‘std::string’ to ‘const char*’.
65,972,571
65,973,124
How to Convert "struct tm" (VTYPE_TM) to DATE(double) - Native API?
I am writing a small DLL in native C++ (Visual Studio 2013 version) using Native API technology. From an external program inside my DLL, I get the Date (no Time: only day, month, year) as a variable of type VTYPE_TM (this is "struct tm"). if (paParams[0].vt == VTYPE_TM) double dateFrom = (double)paParams[0].tmVal ; /...
This can easily be done with C++20 <chrono>. Unfortunately this part of C++20 isn't shipping yet, but vendors are busy implementing it. Fortunately there exists a free, open-source, header-only preview of this part of C++20 which works with C++11/14/17. Additionally, the preview has an examples page with this very pr...
65,972,751
65,973,002
linux pseudo terminal (open select read)
I have a following scenario: Someone creates a pseudo terminal via opening /dev/ptmx. New terminal is created and named for example /dev/pts/2. Then, in my program I open /dev/pts/2 for reading. But I also open other devices for reading and use select() function to wait for any incoming data. The select have also some ...
After select() returns indicating that there's something to be read, the shown code loops repeatedly trying to read() from the non-blocking file descriptor until it is 0: do { rd = read( ... } while (rd > 0); That's certainly reasonable. Except that the closed connection results in the very first read(...
65,972,778
66,019,801
C++ concepts for template-values and parameter pack
Was wondering what syntax would be the most effective/convenient for concepts on parameters pack, including values template-parameters when types (ou values' types) depend on each other? For instance, with the following function : equal_v<values...> is true when all values are equal template <auto... values> constexp...
Well, as conclusion, here are answers to the two questions : How to apply constraints on template-value-parameters ? As pin-pointed by @Artyer and @Davis Herring, concept auto value is a legal syntax defined in p1141r2. NB : It's not currently part of cppreference documentation. How to apply constraints on parameters...
65,972,891
65,973,109
Is there a way to print the sum of randomly generated numbers in a do while loop?
I am writing a program to very fundamentally simulate a black jack game using rand() % 11. We have to tell the players their running total as well as asking if they want another card (hit). My first problem is getting multiple random numbers and my second problem is not being able to add the two random numbers together...
I assume this is an assignment given by an educator, otherwise, you shouldn't be using rand() at all (I don't blame you, I blame the instructor for not keeping up with the language.) You must call rand() again to get a new number and use another variable to store the total: Sidenote: You should really declare your vari...
65,972,908
65,972,971
C++ copy constructor activation in return-by-vlaue
I wasn't able to find a concrete answer for the following question: Consider the following code: Obj f() { Obj o2; return o2; } int main() { Obj o1 = f(); return 0; } How many times is the copy constructor activated without compiler optimization? In case there isn't move constructor, isn't it one time...
Before C++17, yes there are two copy constructor calls (both of which can be elided even if they have side-effects). You can see this with -fno-elide-constructors in gcc/clang. Since C++17 due to the new temporary materialization rules there is just one copy involved inside f (which, again, can be elided). To be accur...
65,972,972
65,972,994
How can I convert a .out file in exe on Debian Linux?
I perfectly know that .exe files are not executable under Linux but I need some files to be converted in .exe. Is there a way?
You can cross-compile your source files with special compilers : they are runnable on one platform, but produce executables for another.