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,000,834 | 62,000,887 | C++ Array variable in class causes "was not declared in this scope" error in one function of implementation file but not in the constructor | The title pretty much says it all. I'm required to write a program for a Software course I'm taking that puts two basic algorithms against each other in a game of checkers. For this, I have a Square class that stores whether the square is occupied (bool), which player by (enum Pl, either NA, P1, or P2), and the label o... | bool canMoveL(int i, int j)
should be
bool Board::canMoveL(int i, int j).
else you define free function unrelated to Board.
|
62,001,175 | 62,068,069 | CLion, SDL2, CMake: No available video device | I am trying to start using SDL2 (with CLion as my IDE), but I'm running into errors. I'm on Pop!_OS 19.10 (based on ubuntu)
Here are the relevant project files:
CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(sdlpractice)
set(CMAKE_CXX_STANDARD 20)
find_package(SDL2 REQUIRED)
include_directories(${SDL2_IN... | Removing /usr/local/bin/sdl2-config,/usr/local/include/SDL2 and /usr/local/lib/libSDL2* (as suggested by Botje) solved the problem due to the self-built version of SDL2 missing the required video headers.
|
62,001,374 | 62,001,492 | Rearrange keys in std::map | I have a map looking like this:
0, 1234
1, 5678
2, 9012
Now, for example I remove the entry with key 1, so the map looks like this:
0, 1234
2, 9012
Now I want to rearrange the keys, so that the map looks like this:
0, 1234
1, 9012
Any idea how to do this?
| Use vector
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int j = 0;
std::vector<int> v = {100, 200, 300};
std::for_each(v.begin(), v.end(), [&j](auto const& p) {
std::cout << "index = " << j++ << " value = " << p << std::endl;
});
/* Delete item at index = 1 *... |
62,001,869 | 62,003,550 | Partially sort a C-style 2D array with std::sort | I came across this question regarding sorting the first 2 lines of an array of integers, the obvious way that came to mind was to use std::sort so I proposed a solution like:
int mat[][3] = { {4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3} };
std::sort(std::begin(mat[0])... | The problem comes from the way the standard defines an array type (8.3.4 [dcl.array]):
An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.
but it does not explicitely says that a contiguous allocated set of objects of the same type can be used as an array.
For compatibil... |
62,001,929 | 62,002,201 | Difference between 24bit addresses and 24bit arithmetic vs 24 bit address with address arithmetic of 16 bit address? | i have found in the c167 Dokumentation a note on arithmetic of pointers.
There are two macros _huge and _shuge.
A cite from the Doku:
_huge or _shuge. Huge data may be anywhere in memory and you can
also reference it using a 24 bit address. However, address arithmetic
is
done using the complete address (24 bit). Shu... | Huge was used in the (good?) old 8086 family mode addressing. These were 16 bit processors with a 24 bits address bus. A full address was given by a segment (16 bits) address and an offset (again 16 bits), with the following formula:
linear_address = segment * 16 + offset
The difference between 2 _huge adresses was co... |
62,002,852 | 62,002,938 | C++ static evaluation of templated argument | Function that I can't seem to get to work:
void Add(const Event &event, T callback) noexcept
{
if constexpr (event == Event::Type1)
{
m_type1callbacks.push_back(callback);
}
else if constexpr (event == Event::Type2)
{
m_type2Callbacks.push_back(callbac... | If you make event a template parameter to your function, you will be able to use it in a constexpr context:
template <Event event>
void Add(T callback) noexcept
{
if constexpr (event == Event::Type1)
{
m_type1callbacks.push_back(callback);
}
else if constexpr (event == Event::Type2)
{
... |
62,003,836 | 62,016,274 | Can't load TGA image embedded with CMake? | I'm trying to embed images and shaders in a single opengl executable file by adding this:
FUNCTION(ADD_RESOURCES out_var)
SET(result)
FOREACH(in_f ${ARGN})
FILE(RELATIVE_PATH src_f ${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/${in_f})
SET(out_f "${PROJECT_BINARY_DIR}/${in_f}.o")
ADD_CUSTOM_COMMAND(OU... | Actually my problem has nothing to do with this embedding issue. The tga object was successfully loaded. It was the image loading library that didn't recognize the object due to my misunderstanding of the parameters.
So the conclusion is that both cmake and my loading code work well. Now should I just delete this quest... |
62,003,902 | 62,003,929 | C++ String Subcript Out of Range when using string.length() as end of for loop | I have a C++ function that is supposed to iterate through the characters in a string and change it to lower case. I am using the length of the input string as the end of the sequence, which works in example functions in the textbook, but gives me a "subscript out of range" error when trying to implement it in the foll... | You lowerCaseCopy string is empty, so indexing into it is undefined behavior.
You could use push_back to add elements:
string lowerCaseCopy;
for (i = 0; i < str.length(); i += 1)
lowerCaseCopy.push_back(tolower(str[i]));
Or you could allocate enough space for it before indexing:
string lowerCaseCopy(str.length())... |
62,004,186 | 62,005,571 | Undefined reference using external library with CMake and Conan | I am trying to develop a program that communicates with a PCSC USB reader using Conan and CMake with the LibLogicalAccess library. I followed the instructions of building and installing the library which seemed to have gone fine. I created a small simple console project with a "main.cpp" file. Following the C++ guide o... | Your error says:
main.cpp:(.text+0x140): undefined reference to `logicalaccess::LibraryManager::getReaderProvider(std::__cxx11::basic_string, std::allocator > const&)'
It occurs because your CMake is using libstdc++11 to link, however, Conan is configured to use libstdc++ due backward compatibility.
You need to upda... |
62,004,538 | 62,004,700 | Run files via cmd in c++ | In my c++ program I need to open a txt file using another application(imagine EXCEL). How should I do that in code correctly?
Maybe I should use something like system("start file.txt EXCEL.exe");
| It would simply be:
system("excel.exe file.txt");
See Command Line Switches for Office Products for more information.
How it works will depend on the application because applicatons decide how they handle their command line parameters. If you want a universal way, use:
system("open file.txt"); // Windows
system("xdg-o... |
62,004,736 | 62,005,520 | Call an overloaded operator from GDB | I have this sample code for example :
class Test
{
int var;
public:
Test(int v_):
var(v_)
{}
int operator()(int a)
{
return var + a;
}
};
int main()
{
Test t = Test(10);
return 0;
}
How can I call operator() of Test class from gdb when I'm in a breakpoint before the ret... | The issue is not that the operator() is being inlined, but the linker is just removing the function, since is not called anywhere in your program.
On my machine, if I change main to:
int main()
{
Test t = Test(10);
t(42); // some call, result can be ignored
return 0;
}
then running the command gives:
(gdb)... |
62,004,858 | 62,004,907 | Why does x = 44 in this case? |
unsigned char x = 0;
unsigned char y = 150;
x = 2 * y;
cout << "x: " << (int)x << endl; // returns 44
I understand that unsigned char meaning ASCII characters from 0 to 255 but i dont know why the x is printing our 44.
Does anyone have an ASCII chart i can follow?
|
I understand that unsigned char meaning ASCII characters from 0 to 255 but i dont know why the x is printing our 44.
Because 2*150 is 300 which is greater than 255. 300 is outside the representable values of unsined char on your system.
When the actual result of an arithmetic operation is outside of representable val... |
62,005,102 | 62,005,308 | Collectible not deleting on contact | I have created collectible objects and a vector to store them, for easy and efficient deletion on contact.
I know that my contact listener works, and that my marked, GetBody and SetUserData functions for my collectibles also work.
I have tried checking each individual collectible object for contact, which does work, al... | If you iterate through a vector, you better do not use the erase function of the vector in the iteration loop.
Use a while loop instead. Or the problem is that you only use a copy of the coins and not the pointer to the coins.
That's what I would do:
...
std::vector<Collectible*> m_coins;
...
m_coins = { m_coin, m_coi... |
62,005,121 | 62,005,240 | How to print last element in set in C++ | I am trying to print last element of a set set<int>s; where actual last element is 9.
set<int>:: iterator it=s.begin();
while(it!=s.end())
{
cout<<*it<<endl;
it++;
}
when i use this loop ,through this set, it shows that last element is 9 which is correct.
but when is use this piece of code it shows last elemen... | end() points past-the-end of a collection. It should never be dereferenced.
You can use rbegin() instead:
if (!myset.empty()) {
cout << *myset.rbegin() << endl;
}
|
62,005,472 | 62,008,859 | C++ IPv6 string representation into boost::multiprecision::uint128_t | I need to convert IPv6 string address into boost::multiprecision::uint128_t
For IPv4 I used the following algorithm:
uint32_t byte1 = 0, byte2 = 0, byte3 = 0, byte4 = 0;
sscanf(ipAddress, "%3d.%3d.%3d.%3d", &byte1, &byte2, &byte3, &byte4);
uint32_t ip = (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | (byte4);
How can I... | Using the example from Wikipedia:
Also using Boost Asio's address_v6 implementation instead of a 1970-era parsing:
Live On Coliru
#include <boost/asio/ip/address_v6.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <cstdio>
using boost::asio::ip::address_v6;
using boost::multiprecision::int128_t;
int main() ... |
62,005,548 | 62,014,800 | SDL2 - Why is a text flickering if my color is not initialized as a private variable? | I try to present text with the following code:
void Text::display(SDL_Renderer *renderer, int x, int y) {
// pos is an SDL_Rect and font is a TTF_Font
pos.x = pos.w = x;
pos.y = pos.h = y;
SDL_Surface *surface = TTF_RenderText_Solid(font, text.c_str(), color);
SDL_Texture *texture = SDL_CreateTextureFr... | The value of the private member is not initialized, and so it gets random/garbage value. As you allocate new Text instance for every frame. You allocate on heap (every time in a new place), so it is sort of guaranteed to actually be garbage.
Why it didn't flicker in other cases?
Public member: my guess is that you als... |
62,005,554 | 62,007,965 | If I casted an int member of a struct to char* to serialize it, should I cast it as int* type when deserializing it? | The struct date has two int types on which the write function of the struct uses reinterpret_cast<char*>() to store it on disk. To read it back again from disk and to store it as an int variable of the struct, should I not reinterpret_cast the int day variable as <int*> to properly store it?
Like so:
os.write(reinterpr... | Your code is fine, as it is, and there is no cause to worry about day (or year) being interpreted as anything other than the int that is declared to be.
In the calls to is.read and os.write, the only thing you are casting (to a char* pointer) is the passed address of the day variable. This, together with the following ... |
62,005,698 | 66,702,426 | LibClang clang_getArgType() returns wrong type | I tried parsing C++ methods using libClang, but when trying to get the parameters/arguments of functions, it gives the wrong types sometimes.
Example:
I have two separate methods
std::string Method::exportMethod(std::map<std::string, std::string> &defines) const
and
std::string Field::exportField(std::map<std::string,... | I know this question is 9 months old, but in case anyone else stumbles across this... I struggled with this too, until I realized that I was missing the diagnostic messages that libclang was emitting. The default type for everything in clang is int, so if your call to clang_parseTranslationUnit is missing an include p... |
62,005,703 | 62,005,865 | static vs reinterpret cast between pointer to POD types | I ran into this problem while trying to traverse a byte array where the data length in bytes is known at run-time.
https://godbolt.org/z/-vgEk_
#include <cstdint>
void f()
{
uint8_t* array = new uint8_t[4*10];
// cannot convert 'unsigned char*' to 'unsigned int*' in initialization
uint32_t* fourByteIterat... | uint32_t* fourByteIterator1 = (whatever_cast)array;
Accessing fourByteIterator1 is Undefined Behavior, no matter how you manage to get the cast working. Accessing the memory obtained from new uint8_t[4*10]; as objects of type uint32_t is a violation of the strict aliasing rules.
As for why some methods of casts work a... |
62,005,841 | 62,049,907 | How does the use of `static` affect the speed of my code? | I was solving an exercise online, and at one point i needed to delete the "" from a the beginning and end of a string. This was my code:
void static inline process_value(std::string &value) {
if (value.back() !='>') {
value = value.substr(1, value.size()-2);
}
}
Called from this benchmark loop:
static ... | Clang uses a cost based decision whether a function will be inlined or not. This cost is affected by a lot of things. It is affected by static.
Fortunately, clang has an output, where we can observe this. Check out this godbolt link:
void call();
inline void a() {
call();
}
static inline void b() {
call();
}
... |
62,005,944 | 62,006,301 | Trouble with glVertexArrayVertexBuffer() / glVertexArrayAttribFormat() in different buffer layouts | I'm trying to bring my OpenGL code up to speed with Direct State access and have been closely following the code from Guide to Modern OpenGL Functions. I have a little test project with some vertices and colors in the form of:
std::vector<float> vertices;
for (float y = -1.0f; y < 1.1f; y += 1.0f) {
for (float x = ... | The offset parameter of glVertexArrayVertexBuffer is the offset of the first element of the buffer in bytes, form the begin of the buffer and stride is distance between consecutive attributes within the buffer.
The vertex specification for case A is wrong:
glVertexArrayVertexBuffer(vao, bindingindex_a, vbo, 0, 5 * si... |
62,006,128 | 62,006,222 | error in implementing stack using linked list | I'm trying to implement a stack using linked list in cpp. I'm using class to make the linked list but I'm getting the following error and I dont understand why
#include <bits/stdc++.h>
using namespace std;
class Stack{
public:
int top;
Stack* next;
Stack(int data){ //constructor
top = data;
... | Use -> whenever you are accessing data member of structure pointed by a Pointer. In your case, try using -> instead of . on s in the main function ()
So, either do
Stack s;
s.push(1);
Or
Stack* s;
s->push(s,1);
|
62,006,349 | 62,006,469 | How to get an easier way of generating the alphabet in C++? | i am trying to make a project,to experiment and learn C++, i didnt finish making it,but what it does is you type in a 3 or 4 (the variable noc) word and the program runs through all the possible (noc) letter words or nonsense, until it finds yours,so there are 2 factors: the length of the word or nonsense and what char... | Because all characters can be represented in ASCII codes ('a' starts at 97, all ASCII codes are int), you can simply make a loop to do that. For example:
char albet[26];
for (int ch = 'a'; ch <= 'z'; ch++) {
//do ch-'a' because we start at index 0
albet[ch-'a'] = ch;
}
and you are done!
|
62,006,839 | 62,007,132 | Draw 2D HUD elements over 3D rendered scene | I searched for this and only found a post from 2014 asking about a somewhat similar situation. However, as I couldn't understand what was done there, I'm asking again, specifically for my implementation, hoping this sheds some light on the topic in general as well. I am fairly new to c++ and openGL, so please be so kki... | You did screw up your GL state very badly:
void renderHUDQuad() {
if (HUDquadVAO == 0)
{
[...]
glGenVertexArrays(1, &quadVAO);
You actually use quadVAO in the rest of this function, so you overwrite your fullscreen quad by the smaller one, which means the rest of your scene will be scaled dow... |
62,007,049 | 62,007,134 | Correct syntax to store function pointer | Surprisingly, the following code compiles well both in gcc and clang no matter what symbol before function name is used: *, & or nothing. Does standard allow any of them? What is preferred way to store function pointers?
#include <stdio.h>
typedef int foo(int a);
template <typename X>
int g(int y) {
return y * s... | All should work fine and have the same effect here. Which one is preferred is a style-issue, IMO the 1st one in your code is confusing, the other two are quite common usages.
I'll explain in the reverse order of your code for convenience,
For xxx = g<float>;, function-to-pointer implicit conversion is performed from g... |
62,007,208 | 62,007,646 | Parity of the Number of Swaps of Swap-Based Sorting Algorithms | If I have a permutation of the integers from 0 to n-1, and I want to sort the permutation in ascending order, is it true that no matter what swap-based sorting method is used, the parity of the number of swaps it will take to sort will be the same among all swap-based sorting methods?
For example, consider a swap-based... | Yes it's true. The sketch of the proof goes something like this.
An inversion in a sequence of elements is any pair of elements that are not in proper sorted order: that is, a[i] > a[j] for some i < j. A fully sorted array has zero inversions. Swapping any two elements changes the total count of inversions by an odd nu... |
62,007,262 | 62,008,416 | How to pass a overloaded function pointer with a template data type? | In the below code I want to create a function count which counts the number of integers/strings which qualifies a match criteria from a vector of integers/strings.
But I am not clear about how to write the function definition.
#include <iostream>
#include <vector>
using namespace std;
bool match(int x) {
return (x... | The function pointer type is
<return-type>(*function-pointer-identifier)(<argument-types>)<other specifiers>
Meaning, you need to remove the extra <> from the count function and you are good to go.
template <typename T>
int count(std::vector<T>& V, bool (*test)(T))
// ^^^^^^^^^^^^^^^^^
Or yo... |
62,007,531 | 62,007,994 | Using pointer in heap for c++ | I am learning the basics of C++ and came across this question as I was learning pointers. I understand that * is used to access the value of the address stored in the pointer. So if I were to do this:
int *p;
p = new int[5];
why is it that the second line would create an array in heap and store the address of the arra... | Understanding pointers may be hard.
Suppose there's a house, at "GreatStreet no 234". Nobody knows about this house.
Now person A, who lives somewhere else, is told about that house. The information is just the address of the house. There's a plus in the info: it says "it's a house, no other thing".
Same goes with poin... |
62,007,672 | 62,007,853 | PNG saved from OpenGL framebuffer using stbi_write_png is shifted to the right | I have been trying to solve this visual bug for a few days without any success, so I'm asking this question to see if somebody can help me understand what is happening.
First I will describe the problem without any code, and then I will present some code. Here is the situation:
My OpenGL application renders this image... | The issue is cause be the alignment of a row, when the image is read by glReadPixels. By default the alignment of the start of each row of the image is assumed to be 4.
Since the width of the image is 450, which is not divisible by 4 (450/4 = 112.5) and the format is RGB (3 bytes), the alignment has to be changed.
Chan... |
62,007,920 | 62,008,543 | How can i increase value of x in function? | C++ Program: - I know that in the function definition, x is not passed so it would get error message but i want to increase in function, so what can i do?
#include <iostream>
using namespace std;
fun(int& p)
{
cout << p;
x++;
}
int main()
{
int x = 15;
int c = 1;
fun(c);
cout << x;
return 0;... | You can either set x as a global variable or you can also pass it to your function.
fun(int &p, int &x) and then call it from main.
|
62,008,160 | 62,008,365 | Can "T t = {};" and "T t{};" produce different results? | The question is simple. Is it possible to construct such a type T, for which the following two variables declarations will produce different results?
T t1 = {};
T t2{};
I've been digging through the cppreference and the standard for more than an hour now, and I understood the following:
T t2{}; is a value initializat... | If you consider a case in which one statement will compile, but the other will not compile as "different effects," then yes, here's a context:
#include <iostream>
class T {
public:
int data{ 0 };
explicit T() {
data = 0;
std::cout << "Default constructor" << std::endl;
}
};
int main()
{
... |
62,008,305 | 62,013,912 | How to get the process ID when starting Mozilla Firefox? | The task of getting the PID of the process that I'm starting, CreateProcess() ProcessInformation.dwProcessId does a great job of this, but in my case, the process that I start opens the child processes and then closes, and I need to get all the PIDs that creates the process I am opening.
I found this code, it receives ... | I tested that the process of Firefox is not new and exit in order(the pid obtained by CreateProcess will exit), and your code will not receive the new Firefox process if there is any new process created later.
You could use swtich-case statement, the following sample work for me:
int openProgram(const wchar_t* programP... |
62,008,371 | 62,009,904 | Encode additional information in pointer | My problem:
I need to encode additional information about an object in a pointer to the object.
What I thought I could do is use part of the pointer to do so. That is, use a few bits encode bool flags. As far as I know, the same thing is done with certain types of handles in the windows kernel.
Background:
I'm writing... | This is heavily dependent on the architecture, OS, and compiler used, but if you know those things, you can do some things with it.
x86_64 defines a 48-bit1 byte-oriented virtual address space in the hardware, which means essentially all OSes and compilers will use that. What that means is:
the top 17 bits of all val... |
62,008,378 | 62,008,691 | Create 2D vector from 2 1D vectors | I am fairly new to vectors and I'm trying to populate a 2D vector from 2 1D vectors for coordinate points. I have 2 vectors like this where source_x and source_y contains values from a file:
std::vector<float,T<float>> pos_x(5);
std::vector<float,T<float>> pos_y(5);
for (int i = 0; i < 5 ; i++){
pos_x[i] = i+1; /... | So my guess is this
std::vector<std::vector<float>> position(num, std::vector<float>(2));
for (int i = 0; i < num ; i++){
position[i][0] = pos_x[i];
position[i][1] = pos_y[i];
}
But I could easily be wrong.
UPDATE based on the example in the question I now think this is the correct code
std::vector<std::vec... |
62,008,843 | 62,009,279 | Replacing each regex match with different number | I have a little problem doing my homework.
I need to make a fraction equation parser where fractions are presented by a|b.
I took all the fractions out of the string into a vector and now I want to replace them in string with subsequent numbers so I have an easier time putting them on stack for the shunting yard algori... | You can use std::regex_iterator, and generate a new string with the replaced numbers:
const std::string s = "2|1+4|1*5|2-18|5";
std::regex r("\\d+\\|\\d+");
// std::regex r(R"(\d+\|\d+)"); // as a raw-string literal, which reduces the need for backslashes
auto begin = std::sregex_iterator(s.begin(), s.end(), r);
aut... |
62,009,021 | 62,009,155 | CPU you selected doesn't support x86-64 instruction set | I want to compile a program which has lots of 32-bit static libraries which I cannot recompile to 64-bit because the lack of makefiles but there are some libraries that I should compile to obtain some static libraries to use alongside them.
One of the libraries that I want to compile has a Makefile as follows :
CC = c... | To compile 32-bit code on a 64-bit system, use the option -m32 to gcc. -mtune=i386 is not correct.
|
62,009,270 | 62,009,448 | C++ file open on windows always fails | I got this code from another answer to a similar question, but I can't figure out why this is not working for me. The test.csv is in the same folder as the compiled .exe file, but it doesn't find it. I tried the full system path ("C:\Users\hhv\eclipse-workspace\oncemore\Debug\test.csv") but it still fails to open the c... | The path is relative to the current working directory (where the program is executed), not to the source file. Also when you use backslashes in the file path you must escape them like so "C:\\Users\\hhv\\eclipse-workspace\\oncemore\\Debug\\test.csv"
|
62,009,589 | 62,011,785 | CPPYY/CTYPES passing array of strings as char* args[] | I only recently started using cppyy and ctypes, so this may be a bit of a silly question. I have the following C++ function:
float method(const char* args[]) {
...
}
and from Python I want to pass args as a list of strings, i.e.:
args = *magic*
x = cppyy.gbl.method(args)
I have previously found this, so I used
de... | ctypes does not have a public API that is usable from C/C++ for extension writers, so the handling of ctypes by cppyy is by necessity somewhat clunky. What's going wrong, is that the generated ctypes array of const char* is of type const char*[2] not const char*[] and since cppyy does a direct type match for ctypes typ... |
62,009,633 | 62,010,403 | Compare user value with value from enum | The essence of the task: to choose the best screen resolution for the user, based on his data.
I need to ompare user value with value from ENUM and return the appropriate one.
For example:
enum class Resolutions {
V720_height = 720,
V720_width = 1280,
V1080_height = 1080,
V1080_width = 1920
};
int main... | Using enums is not the best way to do that. I recommend you to use std::map if you need to name the different resolutions.
#include <map>
#include <string>
#include <iostream>
struct Resolution {
int height;
int width;
};
const std::map<std::string, Resolution> resolutions = {
{ "V720", {720, 1280} },
... |
62,009,677 | 62,054,967 | Serialize struct with a pointer to a struc | I'm trying to follow an article written at https://accu.org/index.php/journals/2317
I found it kind of interesting now that I'm trying to dive in serializaton / file saving / loading for some administrative tools I'm working on. I tagged it c++ because Ill wrap it on a class after I make it work (hopefully with your he... | I read the article a little bit more, and seems like the data they're receiving in the stream object, comes from the machine, that's why the pp and ppend, probably having the "before and after" state saved there. Plus, the functions seems to be made only for that purpose.
Too bad as I thought it was kind of good code t... |
62,009,717 | 62,009,795 | C++ Use derived class method to change base class data member | I'm having a hard time trying to figure out how to access and change base class data member using derived class method.
Following code is a sample of what I want to do.
class A
{
protected:
string name;
public:
A():name("Name 1"){}
void DisplayA()
{
cout<<name<<endl;
... | You must define name as static std::string because modifying non-static members of an object change them only for that object.
|
62,009,768 | 62,014,666 | QT Unable to draw box on screen (QRect and QRubberBand) | I'm trying to write a tool in C++ that will help me with my language study. It will capture an area on the screen (a word or sentence), process the text, then display information on the captured text in a GUI application.
This is a basic diagram of what I'm trying to do:
This is supposed to be very similar to screen ... | You need to create a frameless, alwaysOnTop window that contains a widget. The window should be defined as having a translucent background, whereas the widget will be used to display the border (or semi-opaque background). You can then manipulate the position and size of the window through code by detecting mouse click... |
62,010,279 | 62,011,928 | Undefined reference errors in simple boost serialization | I have a minimal example of Boost serialization where I try to save an integer in a binary archive file
Here is main.cpp:
#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
int main() {
int t = 0;
std::ofstream file("Test.bin");
boost::archive::binary_oarchive archive(file)... | After realizing that the issue was what I mentioned in EDIT, I looked further into how that issue could be resolved, and I found out you can manually set the compiler that is used to search through the variable Boost_COMPILER.
I changed my CMake file to the following:
cmake_minimum_required(VERSION 3.15)
project(Test)
... |
62,010,405 | 62,010,532 | Can std::initializer_list be specialized? | While going through the various rules on list-initialization, I found this in dcl.init.list#3.6:
Otherwise, if T is a specialization of std::initializer_list<E>, the object is constructed as described below.
On the other hand, in the synopsis of std::initializer_list, in support.initlist, I found the following sta... | "A template specialization" has two distinct meanings:
"Explicit (full) specialization" or "partial specialization" - a language construct that changes the meaning of a template for some combination of template parameters.
Something that was generated from a template by substituting template arguments into it.
In othe... |
62,010,632 | 62,011,047 | Print string in reverse | why isn't my code properly grabbing all my inputs? It only passes the last input to my function and reverses it. I want it to hold all the input from the user until quit is typed in.
I believe it's not actually quitting the program when q, quit, or Quit is getting read.
I was told that using fgets (never used it befor... | There is no loop in your main function so it'll do cin.getline(userInput, MAX); 3 times and reverse the last string you've entered, which is quit.
You could solve that with a while-loop:
int main() {
char userInput[MAX];
// loop for as long as cin is in a good state:
while(cin.getline(userInput, MAX)) {
... |
62,010,743 | 62,011,275 | Recursive Karatsuba Algorithm giving Imprecise Answers | I've been trying to implement the Karatsuba multiplication algorithm in C++ for two large numbers of the same length. My code is behaving properly for smaller numbers, such as 3456*1492, but fails with large numbers such as those with 64-digits. It generally gets the first few digits correct but goes awry after that. I... | I suspect one problem is that pow is returning a floating point representation which is being inaccurately converted into a cpp_int.
Using a multiprecision version of pow could help.
Also, len/2 rounds down, so when computing pow(10,len) this should instead be pow(10,(len/2)*2).
|
62,011,157 | 62,011,224 | push_back is more efficient than emplace_back? | I wanted to see the difference between push_back and emplace_back, as in several places I read recommendation as now it's better to use emplace_back as "it can do all push_back can do and more", so I expect ti to be more efficient. But to my surprise
#include <iostream>
#include <vector>
class A
{
public:... | push_back is not more efficient, and the results you observe are due to the vector resizing itself.
When you call emplace after push_back, the vector has to resize itself to make room for the second element. This means that it has to move the A that was originally inside the vector, making emplace appear more complex. ... |
62,011,454 | 62,011,522 | How can I detect if http request come from same client? | I am making http/1.1 server for understanding better how webserver works.
I saw that http/1.1 version support "keep-alive" as default for network improvement, so I am trying to figure out how can I implement it...
For exemple, if client access one page,
and send these two request (one for index.html for the first time... | I think you mix two things: server socket is used to accept incoming connections. new_socket is used to read data from. If you want to handle keep-alive then you should not close the new_socket but wait for data on that socket using select
|
62,011,511 | 62,011,641 | Why is the move constructor not being called here? | I'm trying to invoke the move constructor in the code below, where the addition of two lists occurs. Given what I read in the Stroustrup book, the move constructor should be invoked when operator+(const X& a, const X& b) returns, however it does not per the output below. Only the move assignment is being invoked.
Doe... | In this snippet:
X ph;
// This should call move constructor
ph = px + py + pz;
ph is already created, so there is no question of calling the move constructor.
If you change the snippet to:
X ph = px + py + pz;
you still won't call the move constructor, due to copy-elision.
You can see the move constructor being invok... |
62,011,780 | 62,011,836 | how can i get the size of an array so i can declare said array from a function | const int size = arraySize();
int list[size];
I get the following error:
expression must have a constant value
I know this may not be the best way to do it but it is for an assignment.
| Try dynamic allocation of this array.
int size = arraySize();
int* list;
list = new int [size];
It should work.
In addition, there is a condensed explanation of how dynamic arrays works: DynamicMemory
PS. Remember to free memory that you dynamically allocated, when it won't be needed:
delete [] list;
|
62,011,851 | 62,011,862 | Pointer changes value after storing it in an object (C++) | I notice (to me) weird behavior. If I initialize a DerivedClass and pass a pointer of another class (player) to it, then it receives the right pointer value. However, if I then try to use that pointer, later on in check_pointer_of_player(), the value changed. I do not understand this behavior, and I would like to know ... | Inside the body of the constructor, the parameter player is shadowing the member player, so you are not actually assigning the parameter to the member. This is why only the constructor shows the correct value of player when you print it out.
You can disambiguate like this:
DerivedClass(Coord p, Player* player) : Parent... |
62,011,863 | 62,555,431 | is there any way to obtain ANSI escape code for users OS? | I am making a project where I use escape codes to style printing, I know my escape key is "\033", however other OS's have different escape codes and I would like my project to be cross-platform and work on any OS. Is there any macro that provides the users escape code? if not, is there any table sort of table listing d... | ANSI escape sequences are standardized (it's even in the name : American National Standards Institute), and you shouldn't have any problems with them on different terminals (because it's not the OS that interprets escape sequences, but the terminal emulator).
You could be interested in using libraries like readline or ... |
62,011,959 | 62,012,437 | C++ Process exited after 4.017 seconds with return value 3221225477 | I am new to C++ and I am trying to write this simple code where I input and display employee data.
I want to pass the user input to the inputEmployee function by address, save it in an array then display it. When I get to the part of typing the employee name I get the following message "Process exited after 4.017 seco... | You should go a step back and read something about memory management, arrays, pointers and references in C++. This is a hard part, you have to learn, when you want to program C++. You should definitely read some more articles.
Learning-by-doing is only half the the way to go here. You need to understand what happens in... |
62,012,005 | 62,014,608 | count all subsets of integers (including negative) that sum to x | I am given an array of max length 40 containing integers in [-10^9;10^9]. I am also given the expected sum X which lies in [0;10^9]. Now I am supposed to give the total amount of subsets that sum to X. I can't figure out a way to deal with the negative numbers. I first tried the brute-force approach which works fine fo... | Sum range and item count looks too large for dynamic programming due to memory reason.
But limit of 40 items allows to apply something like "meet-in-the-middle" principle.
Separate the first 20 items and count sums for all possible subsets - just walk through 2^20 subsets (including empty one!) (using recursion or bi... |
62,012,357 | 62,012,467 | Sorting vectors in c++ asc and desc order | I have class Player, and i have to make static method void Player::sortPlayers( vector<Player> &players, bool (*c)(const Player&, const Player&)) and the method should contain only one line, in which you call the function sort with which you can arrange players ascending or descending with age, and than in main create ... | std::sort takes three args and the third one is a comparator. You can define your comparator to make std::sort suite your needs, as follows
void Player::sortPlayers(vector<Player> &players, bool (*c)(const Player&, const Player&)) {//define sortPlayers function
std::sort(players.begin(),players.end(), c);
}
bool asce... |
62,012,761 | 62,012,867 | What is the meaning of "type* = nullptr" | I don't undestand.
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = nullptr)
{
return t;
}
type* = 0? What is this.
| This is a way of achieving SFINAE: The function can only be selected if all the types can be substituted in properly.
If std::is_integral<T>::value is false (i.e., T is not an integral type), std::enable_if<...> will have no member type, thus a substitution failure happens and this function won't be called (and a diff... |
62,012,809 | 62,013,485 | How does one process a user input with cin that contains whitespace? | I'm just starting to learn C++ and ran into a little bug in my program:
#include <iostream>
using namespace std;
int main() {
string name;
int number;
cout << "Hello!\n";
cout << "Please enter your name: " << flush;
cin >> name;
cout << "Please enter a whole number: " << flush;
cin >> numb... | Try using getline http://www.cplusplus.com/reference/string/string/getline/
Is this of any help?
#include <iostream>
#include <string>
int main() {
std::string name;
int number;
std::cout << "Hello!\n";
std::cout << "Please enter your name: " << std::flush;
getline(std::cin, name);
std::cout << "Please enter a whole n... |
62,012,951 | 62,024,676 | Can we reduce time complexity of the maximum winner problem? | Two teams (A and B) are competing each other. Each team has the same number of players. Every team member, of both teams, has some power associated with them. A player can win only when their power is strictly greater than the opponent's power. A player from team A is paired with a player in team B, following the way t... | As it is a greedy algorithm. We are picking the optimal choice every time. You are doing right. We need to sort both arrays. If we use merge sort then time complexity would be O(nlog(n)). One statement is very popular in algorithm design is can I do batter?. Apply different approaches then figure out the relation betwe... |
62,013,013 | 62,021,679 | dnn opencv c++ 'getMemoryShapes' assertion failed | I have trained a CNN in keras saving the result as .h5 and .json.
After that I converted the files to a .pb using a python script, and now I want to import the network into opencv in c++ using cv::dnn::readNetFromTensorflow.
But I am getting an assertion failed on 'getMemoryShapes', what can be the issue here?
The err... | It can be fixed by finding the blob and forwarding it to the network:
blob = cv::dnn::blobFromImage(image, 1.0, cv::Size(32,32));
net.setInput(blob);
|
62,013,034 | 62,013,390 | Why does the compiler throw "undefined reference to..." error in this case? | I'm trying to run the code in CLion that worked perfectly in Visual Studio. The program has an external dependency - OpenCV 4.2.0 library. I've never worked wtih CMake before so i searched for the solution on how to link the library to the project. I am using MingW-w64 as my environment. CMake builds without a single w... | Looks like you are using msvc libraries, but if you use MinGW compiler it will not work.
You can read this link to understand why.
Providing the right libraries should fix your problem ! Usually the owner of the project provide msvc 12/14/15/16 and mingw binaries. If you don't have them I found this unofficial build wi... |
62,013,220 | 62,013,750 | Sort function from standard library gives an error using an iterator | I am relatively new to C++ language and trying to implement sort function from algorithm library defined in standard namespace and use std::sort directly.
The common structure to sort a vector using sort is given using iterator and comparison function.
Consider vector v as {4,3,5,9} and after sorting it will look like ... | Ok let's sort things out one by one.
First about your error message. Your vector stores pointers and keep in mind that a->b is equivalent to (*a).b, so open_list.begin()->h_value equals to open_list.front().h_value, and a pointer clearly doesn't have member variable. To refer to the member variable, you need to write (... |
62,013,280 | 62,013,463 | Why can char be initialized to nullptr in a std::array, but not by itself? | This code doesn't compile (using gcc 9.3)...
int main() {
char bar = nullptr; //error: cannot convert ‘std::nullptr_t’ to ‘char’ in initialization
}
But this code does compile...
#include <array>
int main() {
std::array<char, 1> foo = {nullptr}; // foo[0] == char(0), why?
}
Why is there a distinction?
|
Why can char be initialized to nullptr in a std::array
It can't. The shown program is ill-formed in C++.
When an ill-formed program compiles, there are typically two possibilities:
It is a language extension.
It is a compiler bug.
In this case, I think it is the latter. The bug reproduces in GCC 9, but appears to h... |
62,013,510 | 62,014,558 | C++ derived class calls method on base class before initialization | Here is a simple program, that I am pretty sure has undefined behavior, but I want to be certain.
struct A {
int x;
A(int y):x(y) {}
int foo() { return x; }
};
struct B : public A {
B():A(foo()) {}
};
I am assuming that this has undefined behavior because the call to A::foo occurs before the A object is const... | This is undefined behavior in both cases (including virtual member functions), as specified in class.base.init:
Member functions (including virtual member functions, [class.virtual]) can be called for an object under construction... However, if these operations are performed in a ctor-initializer (or in a function cal... |
62,013,608 | 62,013,916 | Trouble getting two variables to update in C++ for loop | I am creating a function that splits a sentence into words, and believe the way to do this is to use str.substr, starting at str[0] and then using str.find to find the index of the first " " character. Then update the starting position parameter of str.find to start at the index of that " " character, until the end of... | Couple of issues:
The substr() method second parameter is a length (not a position).
// Here you are using `endWord` which is a poisition in the string.
// This only works when beginWord is 0
// for all other values you are providing an incorrect len.
testWord = str.substr(beginWord, endWord);
The find() method sear... |
62,013,625 | 62,016,723 | Can i overload the << operator for a class type to produce a text and a binary file in C++ while being able to chain the << operation? | I want to overload the << operator in C++ to produce a binary and a text file for the following class type.
class data
{
public :
int a;
char b;
}
how can i overload the << operator to produce both a binary and a text file for this class type like so:
ostream& operator(ostream &out, data &d) //for text
{
... | Rather than define an operator<< for data, create 2 wrappers to represent the 2 formats you want, and then define operator<< for them instead.
class data
{
public:
int a;
char b;
};
struct asText
{
const data &m_data;
asText(const data &d) : m_data(d) {}
};
struct asBinary
{
const data &m_data;
... |
62,013,680 | 62,025,360 | How to print out to standard output a boost::asio::ip::tcp::v4 | I am running the c++11 chat example from boost.asio examples and trying to print out the tcp::v4() return value to see what ip address the server is using. There is no to_string function that works on boost::asio::ip::tcp as it does on boost::asio::ip.
Here is the main function from the server.cpp of the chat example:... |
There is no to_string function that works on boost::asio::ip::tcp as it does on boost::asio::ip
That's confused. boost::asio::ip::tcp is a class that you never instantiate (it's a static class modelling a protocol), boost::asio::ip is a namespace, you can't expect to print a namespace.
Then, there's a lot of irreleva... |
62,013,688 | 62,014,199 | What does "classes are not objects" mean? | From the GoF book:
Prototype is particularly useful with static languages like C++, where
classes are not objects, and little or no type information is
available at run-time. It's less important in languages like Smalltalk
or Objective C that provide what amounts to a prototype (i.e., a class
object) for crea... |
What is meant by "classes are not objects"?
Exactly what it sounds like. In some languages, classes themselves are also objects that you can send messages to. For example, in order to create an instance of a class (i.e. a new object), you send the +alloc message to the class (and then you typically send the resulting... |
62,013,940 | 62,013,992 | What does "in-situ without memory allocation" mean for folly implementation of String? | From Folly documentation
Small strings (<= 23 chars) are stored in-situ without memory allocation.
Medium strings (24 - 255 chars) are stored in malloc-allocated memory and copied eagerly.
Large strings (> 255 chars) are stored in malloc-allocated memory and copied lazily.
Where are these "Small String" stored ?
| This means that the cost of std::string already includes 23 characters. Anything more requires additional allocations.
This means internally the structure looks approximately like:
struct string {
// ...
char internal[23];
char* external;
};
This is presumably to make copying short strings very cheap as no heap ... |
62,014,848 | 62,014,931 | Using this pointer to write object to binary file in c++ | void Employee::store_data(string filename) {
fstream file;
file.open(filename,ios::app | ios::binary);
if (file) {
file.write((char*)&this,sizeof(this));
file.close();
}
else cout<<"\n Error in Opening the file!";
}
this is what i tried.
I want to store the current object of employ... | this isn't an actual variable, so you can't take its address. But it already is a pointer, so you don't need to. It also has size of a pointer, so your sizeof is wrong. And then in C++ you should not use C-style casts. So fixing these 3 things, your line becomes
file.write(reinterpret_cast<char*>(this), sizeof(*this));... |
62,014,895 | 62,021,901 | Failing for specific case | This is for finding the top view of a binary tree. My logic has been line by line traversal of the tree. I have used two maps here, m2 for storing node and horizontal distance, the other(m1) with horizontal distance and node data. It seems to fail for a specific case(I cannot copy the test case here because the test ca... | The problem is that you add new members to m2 when the root is seen from the top of the tree:
if(m1.find(m2[root]+1)==m1.end())
{
m2[root->right]=m2[root]+1;
This will not work for a test case like this
1
10
1 2 L 1 5 R 2 -1 N 2 3 R 5 -1 N 5 -1 N 3 -1 N 3 4 R 4 -1 N 4 6 R
which has the fol... |
62,015,097 | 62,016,411 | Does vector allocates memory consecutively for std::moved objects | If I reserve vector with certain size, then I have a loop where I take local variable and then emplace_back(std::move(local_object)), since std::move transfer the ownership of the memory. Will the vector have the elements with consecutive locations?
| Those are not rules of language, but architectural concepts:
You have to remember that storage occupied by object is not owned by said object. It is owned by something hierarchically higher. That can be another object or process, or a function in case of automatic storage.
Taking ownership of allocated dynamic memory... |
62,015,172 | 62,015,402 | How to find c++ source code of torch.bmm of pytorch | I have trouble finding the source code of torch.bmm(), which is defined in https://pytorch.org/cppdocs/api/function_namespaceat_1aac51f71f807ca70fd210814114520c34.html#exhale-function-namespaceat-1aac51f71f807ca70fd210814114520c34.
I have confidence it is located in namespace at, since it is referenced as at::bmm in o... | There is no (single) source for bmm per se. From ATen's Readme:
ATen "native" functions are the modern mechanism for adding operators and functions to ATen (they are "native" in contrast to legacy functions, which are bound via TH/THC cwrap metadata). Native functions are declared in native_functions.yaml and have imp... |
62,015,355 | 62,015,390 | Given the declaration, `std::unique<T> p;`,why `!p` is legail since there is no memory function 'operator !()' for `std::unique<T>` | As the code below, I could not understand why !p is legail since there is no member function 'operator !()' for std::unique<T>.
As std::cout << p.get() << std::endl; is legal, i think p is an object ,not a pointer.So i am confused.
Could anybody do me a favor?
std::cout << "unique ownership semantics demo\n";
{
... | When !p is compiled the compiler implicitly calls the operator bool that unique_ptr<T> has and then negates that.
See here for more details.
|
62,016,021 | 62,016,377 | How to get a sales report(daily sales) from my coffee machine? | Hey the following code part is for a simple coffee machine.People can buy coffee anytime.Here I want to get a sales report after pressing "Leave the machine"(No.8).As an example if customers bought 3 espressos and 5 lattes at the time i press "leave the machine" it has to display that details.(Coffee names,Quantity and... | int nKindNumb[7] = { 0 };
while (coffeetype != 8) {
for (int i = 0; i != sizeof(drink) / sizeof(drink[0]); ++i)
cout << "\n " << i + 1 << ") " << drink[i].name << "\t\t" << drink[i].itemprice << "\t\t" << drink[i].country << "\t\t(" << drink[i].quantity << ") remaining";
cout << "\n 8) Leave the drink... |
62,016,323 | 62,016,740 | Error Code 0x80070002 when debugging C++ in VS19 | I'm very very new to coding C++
I'm learning OOP in C++ and I was trying to write a program on my own
class Account
{
private:
string name;
double balance;
public:
Account();
Account(string name_val);
Account(double bal_val);
Account(string name_val, doubl... | I am adding the full code which is executing successfully on my machine. Copy and execute to see if the code executes succesfully on your end.
#include<iostream>
using namespace std;
class Account
{
private:
string name;
double balance;
public:
Account();
Account(string name... |
62,016,746 | 62,030,400 | How to debug unresolved external symbols error in VS when lib is already added to additional dependencies | I'm using a C++ library that uses functions in wininet.lib. When I compile in VS2017 I get link errors.
I've added wininet.lib to the project's additional dependencies and made sure it's in the final commandline but still get the linker errors:
LNK2001 unresolved external symbol __imp_InternetOpenW
But everything ... | You probably added wininet.lib only for a specific configuration or platform but built for another combination. Please have a closer look at your project properties. There're two drop down lists in the top most part of the properties dialog.
This would at least explain why the #pragma works since it applies regardless ... |
62,016,959 | 62,017,041 | c++ using recursion instead of for loop | I have a code below
#include <iostream>
void print(int n){
if(n == 0) {return;}
for(int i=0; i<n; i++)
cout<<"Hello world"<<endl;
}
int main(){
print(n);
}
What it does is it prints "Hello world" using for loop n times. My question is would it be possible to print it using recursion instead of usin... | You can adapt your code like this. The print function will be called recursively n times, then return since in the last call n will be equal to 0 and because of the first condition it will stop the recursion.
#include <iostream>
void print(int n) {
if(n == 0) { return; }
std::cout << "Hello world" << std::en... |
62,016,982 | 62,017,249 | How to count decimal digits of an integer? | I wrote a program to determine the number of digits in a number
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long num1 = 1999999999999999;
long long num2 = 9999999999999999;
int number_of_digit_1 = log10(num1) + 1;
int number_of_digit_2 = log10(num2) + 1;
cout << numb... | log10 takes various floating point types as arguments and returns the same type in its result. In your case it is converting to double.
double only has 53 bits for it's integer (significand) part.
9999999999999999 needs 54 bits to be represented accurately.
When you convert 9999999999999999 to double you get 1000000000... |
62,017,149 | 64,042,453 | Do not mangle name of shared library with Bazel | Given a C++ application, built with Bazel, that depends on an external, system provided shared library:
cc_binary(
name = 'app',
srcs = ['app.cpp'],
linkstatic = False,
deps = ['@my_system//:system_lib'],
)
The WORKSPACE and BUILD.my_system files:
new_local_repository(
name = 'my_system',
build_file = 'BUI... | Wrap your library with another cc_library.
I can't explain why it works, but it does.
cc_library(
name = "libsystem_lib",
srcs = [ ":system_lib" ],
hdrs = ...
)
Depend on this one instead.
|
62,017,307 | 62,017,363 | Can you make an 8 bit or 16 bit enumerator in C++ (GCC)? | Just curious.
I wanted to do a bitmask for 8 values, but whenever I evaluate it, it always ends up being 32 bits.
I tried
enum Foo {
A = quint8(0)
}
sizeof(A); // 4 bytes, 32 bits
sizeof(quint8(0)); // 1 byte, 8 bits
I thought because it was possible to make 64 bit enumerators, that the opposite was true, tha... | You need to use the C++11 syntax for declaring the underlying type of an enum. Your attempt at restricting the enum values is undone by integer promotion.
enum Foo : uint8_t {
A = 0,
};
|
62,017,581 | 62,017,759 | Can a lvalue-ref-qualified function be used directly in a rvalue-ref-qualified function? | I have been writing the following code to support function calls on rvalues without having to std::move explicitly on the return value.
struct X {
X& do_something() & {
// some code
return *this;
}
X&& do_something() && {
// some code
return std::move(*this);
}};
But ... |
Is this a valid transformation?
Yes. Inside a member function *this is always an lvalue. Even if the function is rvalue reference qualified. It's the same as
void foo(bar& b) { /* do things */ }
void foo(bar&& b) {
// b is an lvalue inside the function
foo(b); // calls the first overload
}
So you may use an lva... |
62,018,160 | 62,018,628 | How can I set custom text to a QLabel in C++? | I'm working on a C++/Qt simulator which integrates a parameter's page. At the end of the parameters, a QLabel notifies the user whether the entered data is valid or not.
This text should appear with a custom color, so I implemented this:
ParametersDialog.h
#include <iostream>
#include <QtWidgets>
using namespace std;... | the problem is that std::string and QString are not straight forward concatenable...
a trick can be done:
QString mx = "<font color=%1>%2</font>";
notificationLabel->setText(mx.arg(color.c_str(), message.c_str()));
|
62,018,447 | 68,205,830 | What do I need to do in order to use CMake from a custom directory? | I've installed a version of CMake to /some/where/cmake, and have put /some/where/cmake/bin in the PATH.
What environment variables do I need to set, and what other actions do I need to take, in order for my custom CMake to function properly? Specifically, how do I ensure it looks in /some/where/cmake/share before /usr/... |
What environment variables do I need to set, and what other actions do I need to take, in order for my custom CMake to function properly? Specifically, how do I ensure it looks in /some/where/cmake/share before /usr/share for CMake-related files?
Nothing! CMake is designed to look relative to the binary's actual loca... |
62,018,483 | 62,018,670 | Why should you check if Base is a private or protected base of Derived? | The only difference between std::is_base_of<Base, Derived> and std::is_convertible<Derived*, const volatile Base*> is that the former is true also when Base is a private or protected base class of Derived. But, when do you really need to know if Base is a private or protected base? Why should the user care about intern... | As one example, consider
template <typename T>
struct Foo : T, Bar {};
In this case it is no longer an implementation detail whether T does inherit from Bar (or any other class) even if the inheritance is protected.
For private inheritance, consider a base class that does some book-keeping. For example creating log en... |
62,018,556 | 62,018,676 | Validating user input using cin | Im trying to do this:
if the value is greater than 50 or less than -50, or not an integer, than cin again the value (until it is valid)
for (size_t i = 0; i < cities; i++)
{
for (size_t j = 0; j < days; j++)
{
cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
cin >> *(temperatures + i *... | The problem is that you are testing the value of *(temperatures + i * days + j) even when the input has failed. Plus you are using ignore incorrectly (only ignoring one character instead of all outstanding characters). Plus you have overly complex code
Here's a better version
#include <limits> // for std::numeric_limit... |
62,018,635 | 62,018,720 | How to get the last directory in a std::filesystem::path? | I have a path to a directory and I want to get the name of that directory, using C++'s std::filesystem. For example, if the path was:
std::filesystem::path fake_path("C:\\fake\\path\\to\\my_directory\\");
I would want to get "my_directory".
I've seen this answer and initially assumed that what worked in boost::filesy... | You could obtain it using:
fake_path.parent_path().filename()
|
62,018,727 | 62,019,082 | Makefile by ocaml and cpp extension | I have large number of .ml and .cpp files in a same directory which are totally independent of each other. Is there any way I can compile them with Makefile without using external bash / shell scripts?
CC=g++
CFLAGS=-Wall -std=c++14 -Wno-unused-variable
CCML=ocamlc
SHELL := '/bin/bash'
.SUFFIXES = .cpp .ml
cpp_objs:=$... | According to the manual you are supposed to configure .SUFFIXES like a target, not like a variable:
.SUFFIXES: .cpp .ml
However, the better approach is to use pattern rules so you can drop the use of .SUFFIXES entirely.
%: %.ml
$(CCML) -o $@ $<
|
62,019,151 | 62,020,626 | vscode keeps telling me nullptr is undefined | I'm writing C++ in VSCode. The nullptr is marked by red cursive line and showing identifier "nullptr" is undefined. Though, I can run this code perfectly with code-runner extension. But how do I get rid of this false alert in VSCode?
| As is pointed in the comments, in the project folder, just find .vscode/c_cpp_properties.json file and change the C++ version to C11. Problem fixed.
|
62,019,401 | 62,104,806 | Check if GTK window has keyboard and mouse focus window C++ | Is there a GTK3 function that detects if a window has focus? I am currently using the following code:
#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
GtkWidget *LinuxWindow;
static void buttonMessage(GtkWidget *widget, gpointer data)
{
g_print("Yay, you clicked me!\n");
}
int main() {
... | There is a function: gtk_widget_is_focus ().
You need to assure parents have the "has-focus" property set.
Doc. excerpt:
gtk_widget_is_focus (GtkWidget *widget);
Determines if the widget is the focus widget within its toplevel. (This does not mean that the “has-focus” property is necessarily set; “has-focus” will only... |
62,020,047 | 62,020,383 | C++ variable not recognized | I'am having a problem with a program I write. How you will see I'm calling a class I wrote in another file which is in the same folder when I try to use a variable I only get the error message: "C4700 The uninitialized local variable "query1" was used". I tried to name the variable diffrently but it didn't work. Here'... | The problem is that class Save_status lacks a constructor. Check your C++ book on how to write one.
|
62,020,083 | 62,020,163 | Why does std::array::begin not return an iterator? | I am trying to build a nested iterator template and relied on iterators having various traits like value_type. But as it turns out, not all STL types even return iterators with those traits. For instance:
#include <array>
#include <type_traits>
template <typename T>
using iterator_t = decltype(std::declval<T>().begin(... | The standard doesn't specify how the iterator should be implemented and what the exact type it should be. In fact pointers like int* does satisfy the requirements of the iterator of std::array, so it's quite legitimate for implementation.
You can use std::iterator_traits to get the value_type as std::iterator_traits<it... |
62,020,245 | 62,020,500 | Trying to get a fibonacci numbers lower than a input number in a fibonacci loop in c++ | I'm trying to build a program that asks a user for a number "k" and print a series of numbers lower than the number k.
For example if the user writes 20 the output has to be:
0, 1, 1, 2, 3, 5, 8, 13
Instead I got:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181
This means that are... | You are comparing the inputed k limit with the iterator i, so the input is read as the quantity of numbers in the fibonacci sequence you want to output, not the upper limit.
To do what you want you need to compare the limit k with the fib function returned result so that you can stop the loop as soon as the limit is ex... |
62,020,466 | 62,020,554 | C++: Reading a line as : 'string string;int' | I have started coding lately(school curriculuim) and ran into a little problem. I want to read a .txt file, the lines are like "firstname lastname;phonenumber".
ifstream file("names.txt");
string line, fname, lname;
int num;
while (getline(file, line)) {
istringstream iss(line);
iss >> fn... | Two possible solutions:
One relatively simple way is to read fname like you do now, then use std::getline with ';' as the separator (instead of the default newline) to get lname. Then you could read into num.
Get fname like you do now. Then get lname;num into a second string. Find the semi-colon and create two sub-str... |
62,020,583 | 62,020,800 | How do I call C++ functions from C? | I'm writing a C program (myapp) which needs to use a particular api; the api is written in C++. I've worked with C and C++, but never both at once, and I'm getting confused.
So, the api provides the following directory, which I've placed in a folder called include, at the same level as my makefile:
libmyapi.a
api/api.h... | You can write a small C++ program that creates a C binding for the API.
Gvien this API:
namespace MyAPI {
namespace API {
typedef SimpleProxyServer SimpleConnection;
}
}
you can create c_api.h
#ifdef __cplusplus
extern "C" {
#endif
struct api_handle_t;
typedef struct api_handle_t* api_handle;
api_handle myapi... |
62,020,693 | 62,021,079 | How can i get an typedef for std::queue in c++ | I want to use the std::queue in an program. But later I may change to an other implementation of queues. I have a header with all my typedefs but typedef dont works for std::queue.
Is there a way to have something simular to an typedef for std::queue?
Edit:
I dont want a typedef for a specific type like this:
typedef s... | template <class T>
using Queue = std::queue<T> ;
and then in main, you can use it as follows
int main() {
Queue<int> q;
q.push(3);
}
|
62,020,736 | 62,020,774 | C++ inheritance and same funciton names | I have this situation:
class A
{
public:
A();
virtual ~A();
void doSomething();
};
class B : public A
{
public:
B();
void doSomething(int parameter);
};
If I do the following:
int main()
{
B b;
b.doSomething();
}
It gives me a compile error (no matching function).
How can I solve that wi... | Currently, B::doSomething hides A::doSomething.
You might use using to resolve your issue:
class B : public A
{
public:
using A::doSomething;
B();
void doSomething(int parameter);
};
|
62,020,753 | 62,020,896 | The logic behind nested for loops | I am learning C++ and trying to print out the following using nested for loops in C++ in two cycles. In the end there should be 16 ADD operations and 8 DELETE operations:
ADD operation : Caller ID= 1 , Selected Queue= 2
ADD operation : Caller ID= 2 , Selected Queue= 2
ADD operation : Caller ID= 3 , Selected Queue= 1
AD... | You have an semicolon at the end of your for statements that doesn't belong there.
You loops work, but they only execute the code block afterwards, which is an empty statement in your example.
Remove the semicolons and it should work just fine.
e.g. for(i=0;i<N;i++);{ should read for(i=0;i<N;i++){
|
62,020,872 | 62,021,080 | Merge all *.txt files in one text file whose name is given by the user using C++ | I am trying to make a small and simple shell using c++ and i want to use something like this .
if (arr[0] == "type")
{
system("type *.txt >> output.txt");
}
If the user enters type the programm will merge all the text files in the current working directory into one . When i run it with the code abov... | Probably what is happening is that output.txt is also being matched by *.txt so at some point is going to write again all the content to that file. You can easily test that changing the extension of the output.txt to, for example, output.out.
For the second question you could do something like this:
ofstream os;
string... |
62,021,166 | 62,021,222 | I wonder why `std::unique_ptr<int> foo (new int)' is legal since `std::unique_ptr<int>` requires the input argument type should be `int`? | I wonder why std::unique_ptr<int> foo (new int) is legal.
What confused me is that I think the input argument type should be int in std::unique_ptr<int>, but the type new int is int*.
I am a novice in C++. I thought it over and over but I still could not get the idea.
Could anybody make it clear for me? Thank you for ... | Actually std::unique_ptr has several constructor overloads one of which is
explicit unique_ptr( pointer p ) noexcept;
Constructs a std::unique_ptr which owns p, initializing the stored pointer with p and value-initializing the stored deleter. Requires that Deleter is DefaultConstructible and that construction does no... |
62,021,531 | 62,025,797 | Is there a possibility to get source code of ELF file using debug_info? | I have a file with type: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), with debug_info, not stripped. Is there a way to get source code of this file? How can I use debug_info?
| I believe you're looking for a debugger or decompiler. The usual suspects for these applications are the linux programs file for file info, gdb for debugging, and recently with its open-sourcing of the NSA program ghidra; that is, if you trust a software produced by the NSA. Ghidra should be able to decompile your ELF ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.