dimanche 31 mars 2019

Enable a struct if enable_if determines that T is a container?

I am trying to build a templated struct that will only take containers for T. I found this post that showed how to determine whether the passed in value is a container or not. So I decided to go ahead and try to use that for my program as I do not want the user to create a struct of integers, floats, or doubles.

Here is code that I have written:

template<typename T> 
struct is_container : std::integral_constant<bool, has_const_iterator<T>::value && has_begin_end<T>::beg_value && has_begin_end<T>::end_value> { };

template<typename T, typename Enable = void>
struct Cont;

template <typename T>
struct Cont<T, typename std::enable_if<is_container<T>::value>>
{
  Cont(const std::string &n) : name(n) {}
  std::string name;
};

However, when I try to write to main:

int main()
{
  Cont<std::vector<int>> myContainer("Vector");
}

I get a compiler error: Cont<std::vector<int> > myContainer has initializer but incomplete type. I'm kind of stuck on where to go with this, because if I remove the enable_if from the template parameter, it compiles just fine. Which leads me to believe that I am doing something wrong with enable_if or I am missing something rather simple.

What I am trying to achieve is the following:

int main()
{
  Cont<std::vector<int>> myContainer("Vector"); //happily compiles
  Cont<int> badContainer("Bad"); // will not compile
}

How can I achieve this?

How to replace a sequence in vector

Let's assume that I have the following vector:

std::vector<int> data{0,1,2,3,4};

I would like to replace the sequence {1,2,3} with a single number. I have found an example with std::replace but there a single number is replaced with other single number. How to replace a sequence in vector ?

How to fix undefined reference to ... in c++

I am trying to compile mathgl with fltk on a linux debian. In the mathgl directory, I do the followin cmd to configure the compilation :

cmake -Wno-dev -D enable-hdf5=on -D enable-jpeg=on -D enable-png=on -D enable-fltk=on -D enable-qt4=on .

and the result is:

...................................

[82%] Linking CXX executable mglview

cd /home/sosroot/MathLib/mathgl/utils && /usr/local/bin/cmake -E cmake_link_script CMakeFiles/mglview.dir/link.txt --verbose=1 /usr/bin/c++ -fopenmp -O3 -DNDEBUG -rdynamic CMakeFiles/mglview.dir/mglview.cpp.o -o mglview -Wl,-rpath,/home/sosroot/MathLib/mathgl/widgets:/home/sosroot/MathLib/mathgl/src:/usr/local/HDF_Group/HDF5/1.10.5/lib: ../widgets/libmgl-fltk.so.7.5.0 /usr/local/lib/libfltk_images.a /usr/local/lib/libfltk_forms.a /usr/local/lib/libfltk_gl.a -lGL /usr/local/lib/libfltk.a -lSM -lICE -lX11 -lXext -lm ../src/libmgl.so.7.5.0 -lGL -lGLU -lpng -lz -ljpeg /usr/local/HDF_Group/HDF5/1.10.5/lib/libhdf5.so.103.1.0 -ldl -pthread -lm

../widgets/libmgl-fltk.so.7.5.0: undefined reference to XftFontOpenXlfd' ../widgets/libmgl-fltk.so.7.5.0: undefined reference toXftListFonts'
......................................................................

../widgets/libmgl-fltk.so.7.5.0: undefined reference to `XRenderComposite'

../widgets/libmgl-fltk.so.7.5.0: undefined reference to `XRenderQueryExtension'

../widgets/libmgl-fltk.so.7.5.0: undefined reference to `XRenderCreatePicture'

collect2: error: ld returned 1 exit status

utils/CMakeFiles/mglview.dir/build.make:104: recipe for target 'utils/mglview' failed

make[2]: *** [utils/mglview] Error 1

make[2]: Leaving directory '/home/sosroot/MathLib/mathgl'

CMakeFiles/Makefile2:1041: recipe for target 'utils/CMakeFiles/mglview.dir/all' failed

make[1]: *** [utils/CMakeFiles/mglview.dir/all] Error 2

make[1]: Leaving directory '/home/sosroot/MathLib/mathgl'

Makefile:132: recipe for target 'all' failed

make: *** [all] Error 2

can some one help me ?

Thank you.

samedi 30 mars 2019

Why is there no output for friend function?

I can compile and run with no errors, however, there is no output when I run the program.

The friend ostream& operator<<(ostream&, Element&) function should output the Element to the provided ostream.

//In .h

...

struct Element{
public:
  string key_;
  vector<string> values_;
  Element()=default;
  Element(string, initializer_list<string>);
  bool operator==(const Element&)const;
  friend ostream& operator<<(ostream&, Element&);
};

...


//In .cpp:

ostream& operator<<(ostream& os, Element& e1){
    os<<e1.key_<<':';
    copy( e1.values_.begin(), e1.values_.end(), ostream_iterator<string>(cout, ", ") );
return os;

...

int main(){
    Element e1("abc",{"a","b","c"});
    ostringstream oss;
    oss<<e1;
    string result = oss.str();
}

Output format should be something like this:

Element e ("abc",{"a", "b", "c"});
ostringstream oss;
oss << e;
string result = oss.str();
string ans = "abc:a,b,c";

XPATH use in c++ boost

Is there any way of XPATH usage in boost similar to C# (SelectSingleNode() etc).

I am trying with boost::property_tree::ptree, but it is bit different than C#/VBA XML parsing.

<?xml version="1.0"?>
<Classes>

  <Class name="first">
   <Elements>
    <ElementA>aa</ElementA>
    <ElementB>bb</ElementB>
   </Elements>
  </Class>

  <Class name="second">
   <Elements>
    <ElementA>cc</ElementA>
    <ElementB>dd</ElementB>
   </Elements>
  </Class>

  <Class name="third">
   <Elements>
    <ElementA>ee</ElementA>
    <ElementB>ff</ElementB>
   </Elements>
  </Class>

</Classes>

I have to iterate on this kind of config and select subtree on the basis of Classes/Class[@name] attribute.

How can I do this with ptree.

How to change `void *` type to `string` type

I have supplied code from a demo and the type associated with the fonts are of type void *.

Here is the type of the font as declared in vscode

#define GLUT_BITMAP_HELVETICA_18 (&glutBitmapHelvetica18)
Expands to:

(&glutBitmapHelvetica18)

I am trying to write a quick little conditional to check whether the font is from a list or not.

if (find(begin(fonts), end(fonts), reinterpret_cast<char*>(font) ) != end(fonts))

I am using an iterator to iterate through an array of strings.

    array<string, 7> fonts = { 
      "GLUT_BITMAP_TIMES_ROMAN_24", 
      "GLUT_BITMAP_TIMES_ROMAN_10", 
      "GLUT_BITMAP_HELVETICA_12",
      "GLUT_BITMAP_HELVETICA_10",
      "GLUT_BITMAP_8_BY_13",
      "GLUT_BITMAP_9_BY_15" };

My issue is that since all the elements in that array are strings it is throwing a type error between the void * and the string. I am not too sure how to cast the type to a string or if there is a better way of checking if that void * is within the array or even a simple list of possible options.

Why the program show that the string is out of range?

I'm doing homework about removing some words from the string. It always shows that the string is out of range and I do not know what's wrong with my code.

There are the strings that I use to test my function:

  • "The house whirled around two or three times and rose slowly"
  • "through the air. Dorothy felt as if she were going up in a balloon."
  • "The north and south winds met where the house stood, and made it the"
  • "exact center of the cyclone."

and the following is the words that I have to remove from the above strings:

  • a
  • an
  • A
  • and
  • The
  • the
  • in
  • or
  • of

The program works well for the first two lines, but it shows that it is out of range for the third line, I think that is because I have to remove the last word from the third line (i.e. "the").

int RemoveWordFromLine(string &line, string word)
{
  int no_of_occurence=0;
  int const length_of_stopword=word.length();
 int  const length_of_line=line.length();

 for(int j=0 ;j<=length_of_line-length_of_stopword;j++){

   if (j==0){
   if(line.substr(j,length_of_stopword)==word){

       line.replace(j,length_of_stopword," ");
       no_of_occurence++;
  }
}
if ((j-1>=0) && (j+length_of_stopword<length_of_line)){
  if ((line.substr(j-1,1)==" ") && (line.substr(j+length_of_stopword,1)==" ")){//I have to check this to ensure 'a' in "air" is not removed by the function.
    if(line.substr(j,length_of_stopword)==word){

      line.replace(j,length_of_stopword," ");
      no_of_occurence++;
 }

  }
}

How do I view::concat 2 different range views?

I'm trying to view::concat 2 views. I don't understand when I can and can't do this, and why. Any help would be great. This question sounds similar, but doesn't address my problem.

I tried the following code

#include <iostream>
#include <range/v3/all.hpp>
using namespace ranges;

int main () {
  // 'string' of spaces   
  auto spaces = view::repeat_n(' ',4);  // 1
  // prints [ , , , ]
  std::cout << spaces  << std::endl;

  // 'string' of letters
  auto letters = view::iota('a', 'a' + 4); // 2
  // prints [a,b,c,d]   
  std::cout << letters  << std::endl;

  // 'string' from concat of letters and spaces   
  auto text = view::concat(letters,spaces); // 3
  // prints [a,b,c,d, , , , ]       
  std::cout << text  << std::endl;

  // 'vector<string>' repeat letters
  auto letter_lines = view::repeat_n(letters,3); // 4
  // prints [[a,b,c,d],[a,b,c,d],[a,b,c,d]]
  std::cout << letter_lines  << std::endl;

  // 'vector<string>' concat 2 repeated letter_lines
  auto multi_letter_lines = view::concat(letter_lines,letter_lines); // 5
  // prints [[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d],[a,b,c,d]]
  std::cout << multi_letter_lines << std::endl;

  // 'vector<string>' from concat of letter_lines, and spaces_lines
  // this doesn't work (well it compiles)
  auto text_lines = view::concat(letter_lines,space_lines);
  // this doesn't compile
  std::cout << text_lines  << std::endl;   //  6 ERROR
  // I expected [[a,b,c,d],[a,b,c,d],[a,b,c,d],[ , , , ],[ , , , ],[ , , , ]]

  // This works
  auto flat_text_lines = view::concat(letter_lines | view::join,
                                      space_lines | view::join); // 7
  // prints [a,b,c,d,a,b,c,d,a,b,c,d, , , , , , , , , , , , ]
  std::cout << flat_text_lines << std::endl;
  // but the structure is lost; it's a 'string', not a 'vector<string>'
}

The cout after line 6 gives the error

note:   template argument deduction/substitution failed:
concat.cpp:21:19: note:   cannot convert ‘text_lines’ (type‘ranges::v3::concat_view<ranges::v3::repeat_n_view<ranges::v3::iota_view<char, int>>, ranges::v3::repeat_n_view<ranges::v3::repeat_n_view<char> > >’) to type ‘const ranges::v3::repeat_n_view<char>&’
      std::cout << text_lines  << std::endl;

If I understand the error, it's saying, concat<repeat_n<iota<char>>,repeat_n<repeat_n<char>>> can't be converted to repeat_n<char>. Ok, I actually want the concat to convert to something like repeat_n<repeat_n<char>>, so the error kind of makes sense.

But then I would expect the cout after line 3 to complain by saying something like concat<iota<char>,repeat_n<char>> can't be converted to repeat_n<char>.

Why does line 3 work; what type does it actually become? What should I do to get line 6 to work?

Why does Visual Studio give unexpected output for this C++ code?

I was learning about pointers and testing out some code from an online video. When the teacher ran his code from an online ide, he produced different results on the 4th line of output. When I ran my code on a random online ide (different from that of the teacher's), I got the same 4th line of output the teacher got. This output should be the right output, so why do I get the wrong output in Visual Studio 2017.

 #include <iostream>

 using namespace std;

 int main() {


int a = 5, b = 7, c = 10, d = 14;

cout << a << " " << b << " " << c << " " << d << endl;

int *pa = &a, *pb = &b, *pc = &c, *pd = &d;

cout << &a << " " << &b << " " << &c << " " << &d << endl;

cout << pa << " " << pb << " " << pc << " " << pd << endl;

pa++;
pb++;
pc++;
pd++;

int da = *pa;
int db = *pb;
int dc = *pc;
int dd = *pd;


cout << da << " " << db << " " << dc << " " << dd << endl;
cout << &da << " " << &db << " " << &dc << " " << &dd << endl;

getchar();

return 0;

}

Teacher's results (what I expected):

5 7 10 14                                                                               
0x7fff7336d390 0x7fff7336d394 0x7fff7336d398 0x7fff7336d39c                             
0x7fff7336d390 0x7fff7336d394 0x7fff7336d398 0x7fff7336d39c                             
7 10 14 7  <----- Correct output                                                                         
0x7fff7336d3a0 0x7fff7336d3a4 0x7fff7336d3a8 0x7fff7336d3ac      

My results:

5 7 10 14
010FFC44 010FFC38 010FFC2C 010FFC20
010FFC44 010FFC38 010FFC2C 010FFC20
-858993460 -858993460 -858993460 -858993460    <------ Weird values
010FFBE4 010FFBD8 010FFBCC 010FFBC0

P.S. I know that the second "7" in the 4th line of output from the teacher's results will not always be "7", since I'm accessing memory I don't really know about. The teacher said that the value could be 7 or 10 or 14. I'm also wondering, why is it only limited to those numbers, why can't that number be some random number or garbage value?

how big are 1000 double?

i an learning c++ and in one lesson was a code which is about exception handling. My question to this code is actually: is the output and calculation of the memory size correct? When I allocate a block of memory with new double(1000), isn't the size then 8000bytes ?

The "cerr" only counts as 1kB instead of 8kB. Am i wrong?

Thanks a lot for any answer

i got the size of 1 double with getsizeof(doulbe) to confirm it is 8Bytes.

#include <iostream>
#include <cstdlib>
#include <new>
using namespace ::std;
int main()
{
    int i = 0;
    double *q;

try
{
    while (1)
    {
        q = new double[1000];
        i++;
    }
}
catch (bad_alloc &ex)
{
    cerr << "The memory is used up.  " << i
         << " Kilobyte were available." << endl;
    exit(1);
}
}

Whilst reading through a datafile, how do I find anagrams of the user's string input?

Basically I've been given a datafile which contains 100 words and my task is to program an anagram finder to find the anagrams within the datafile. Once the anagram is found, I am struggling to code to print out the word which is in the datafile.

I've managed to sort the strings into alphabetical order to compare and I made an if statement to say if the current word is the same as the original string then print out the word.

I apologise if this question sounds confusing, I've been stuck on this for a few days and I can't wrap my head around this at all.

string FindAnagram(string originalString) {
string currentWord;
string localString;
localString = originalString + currentWord;

ifstream dbFile;
dbFile.open(cDATAFILE);

while(!dbFile.eof()){
    getline(dbFile, currentWord);

      sort (currentWord.begin(), currentWord.end());
      sort (originalString.begin(), originalString.end());

if(currentWord == originalString){
          cout << "\n\t Anagram of the current word: " << localString << endl;
        }
        else {
          cout << "\n\t No anagram available." << endl;
        }

    }
dbFile.close();
return currentWord;
}

For example, if the currentWord is "alert" then it would read through the datafile and print out the words that are an anagram of the word "alert" but I'm struggling to make it print out the word in the datafile.

For example, "later" is expected to be printed out but "alert" is being printed out instead.

Thanks in advance.

Is there a way to limit data size at C++ compile time and produce a compile error?

I have build a tool that enable students to compile and test their own C++ code on line (on a protected environment).

I would like to check, at compile time, that the total amount of data size in a program does not exceed a certain size, and produce a compile error if it does.

(immediate goal : limit c++ std::array size )

I did not find information on the Web.

My compile chain is :

g++ -Wall -Wextra -Waddress -std=c++11 -lm -fstack-protector -lm -o exename srcname

Thanks for help.

Troubles with compiling C++ code with BOOST Library

I have installed boost on my Ubunutu machine using following command:

sudo apt-get install libboost-all-dev

When I try to compile my C++ program using: g++ *.cpp -o main I get the following error message:

/tmp/ccnMHibM.o: In function main': main.cpp:(.text+0x46): undefined reference toboost::thread::thread()' /tmp/ccnMHibM.o: In function __static_initialization_and_destruction_0(int, int)': main.cpp:(.text+0xec): undefined reference to boost::system::generic_category()' main.cpp:(.text+0xf8): undefined reference to boost::system::generic_category()' main.cpp:(.text+0x104): undefined reference to boost::system::system_category()' /tmp/ccnMHibM.o: In function boost::system::error_category::std_category::equivalent(int, std::error_condition const&) const': main.cpp:(.text._ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition[_ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition]+0xb8): undefined reference toboost::system::generic_category()' main.cpp:(.text._ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition[_ZNK5boost6system14error_category12std_category10equivalentEiRKSt15error_condition]+0xf3): undefined reference to boost::system::generic_category()' /tmp/ccnMHibM.o: In function boost::system::error_category::std_category::equivalent(std::error_code const&, int) const': main.cpp:(.text._ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei[_ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei]+0xb8): undefined reference to boost::system::generic_category()' main.cpp:(.text._ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei[_ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei]+0xf3): undefined reference toboost::system::generic_category()' main.cpp:(.text._ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei[_ZNK5boost6system14error_category12std_category10equivalentERKSt10error_codei]+0x1d2): undefined reference to boost::system::generic_category()' /tmp/ccnMHibM.o: In functionboost::thread::~thread()': main.cpp:(.text._ZN5boost6threadD2Ev[_ZN5boost6threadD5Ev]+0x14): undefined reference to boost::thread::detach()' /tmp/cc70LCDt.o: In function__static_initialization_and_destruction_0(int, int)': ts_hash_table.cpp:(.text+0x819): undefined reference to boost::system::generic_category()' ts_hash_table.cpp:(.text+0x825): undefined reference toboost::system::generic_category()' ts_hash_table.cpp:(.text+0x831): undefined reference to `boost::system::system_category()' collect2: error: ld returned 1 exit status

When I try to manually specify the path to boost library, like so: g++ *.cpp -o main -lboost_thread I get another error:

/usr/bin/ld: /tmp/ccyqvpMZ.o: undefined reference to symbol '_ZN5boost6system15system_categoryEv' //usr/lib/x86_64-linux-gnu/libboost_system.so.1.65.1: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status

Here is my actual code (main.cpp):

#include "ts_hash_table.hpp"

HASH_TABLE* hash_table = createHashTable(TABLE_SIZE);

int main() {

   srand (time(NULL));

   boost::thread arr[THREAD_NUM];

   return 0;

}

And here is ts_hash_table.hpp file:

#ifndef TS_HASH_TABLE_H
#define TS_HASH_TABLE_H

#include <iostream>
#include <boost/thread/thread.hpp>
#include <atomic>
#include <stdio.h>
#include <stdlib.h>

#define TABLE_SIZE 10
#define THREAD_NUM 10

typedef struct element{
       std::atomic<int> tag;

       std::atomic<int> data;
       std::atomic<int> key;

       struct element* next;
}ELEMENT;

typedef struct {
    int size;
    std::atomic<ELEMENT*>* buckets;
}HASH_TABLE;

extern HASH_TABLE* hash_table;

HASH_TABLE* createHashTable(int);
ELEMENT* createElement(int,int);
ELEMENT* get(int);

int calculateHash(int);
void insert(int, int, int);
void modify(int, int);
void printList(ELEMENT*);
void printTable();  
void clearList(ELEMENT**);
void clearTable();

#endif // TS_HASH_TABLE_H

Can anyone help me out and tell me what I am doing wrong?

Do we need to check if an unordered_set contains an element before trying to erase it?

Say I have a set:

std::unordered_set<int> mints;

Then I do:

mints.erase(foo);

But mints doesn't contain foo! Is it guaranteed that nothing bad will happen, and that erase will simply just return 0 ?

Class definitions in seperate cpp file

I created a new class in c++ with the declarations in the "Bull.h" header file and the corresponding definitions in an extra "Bull.cpp" file just for the class. Now when I try to call a method of that class from my "main.cpp", I get the following error:

Undefined symbols for architecture x86_64:
  "Bull::Bull()", referenced from:
      ___cxx_global_var_init in main-0d8dea.o
  "Bull::intro() const", referenced from:
      _main in main-0d8dea.o
ld: symbol(s) not found for architecture x86_64

I tried to put the method definitions directly in "main.cpp" and it worked fine. I believe, the "Bull.cpp" file with all method defintions is not correctly linked to the header file.

//main.cpp
#include "Bull.h"
#include <iostream>

using FText = std::string;

// Instantiate a new game from Bull class.
Bull BCGame;

int main(void) {
    BCGame.intro();
    return 0;
};

//Bull.h
#include <string>

using FString = std::string;

// Full class of the game.
class Bull {
    public:
        Bull();
        bool is_game_won(void) const;
        int get_current_try(void) const;
        int get_max_tries(void) const;
        int get_word_length(void) const;
        void intro(void) const;
        void reset(void);
        void play_game(void);
        bool play_again(void);
        FString generate_word(int input);
        FString get_guess(void);
    private:
        bool game_state_won;
        int current_try;
        int max_tries;
        const int WORD_LENGTH = 5;
        FString word;
};

//Bull.cpp
#include "Bull.h"
#include <iostream>

using FText = std::string;

// constructor
Bull::Bull(void) {
    reset();
}

void Bull::reset(void) {
    int MAX_TRIES = 10;
    max_tries = MAX_TRIES;
    current_try = 0;
    game_state_won = false;
    return;
}

void Bull::intro(void) const{
    std::cout << "Welcome to Bulls & Cows! \n";
    std::cout << "Guess a " << Bull::WORD_LENGTH << " letter word. For each letter that you got right\n";
    std::cout << "you get a cow. If it's in the right place, you get a bull.\n";
    std::cout << "Now, enter your first guess: ";
    return;
};

...

But I can not find what I am missing to connect both. Hope you guys can help me!

iterate through a set goes to infinite loop

i used exactly the same code in both of my files. and one is work properly while the other one (this one) goes to endless loop.

int N = 5;
int arr[5] = {3, 1, 3, 5, 6};
int main() {
    int T = 1, B = 16; 
    set<int> s;
    for (int tc = 0; tc < T; tc++) {
        s.emplace(0);
        for (auto x : arr) {
            auto end = s.end();
            for (auto it = s.begin(); it != end; it++) {
                // here's where goes to infinite loop
                // and i couldn't figure out why..
                s.emplace(*it+x); 
            }
        }
    }
    return 0;
}

below one is well working one

using namespace std;

int main() {
    int arr[5] = {3,1,3,5,6}, sum=20;
    set<int> s;
    s.emplace(sum);
    for (auto x : arr) {
        auto end = s.end();
        for (auto it = s.begin(); it != end; it++) {
            s.emplace(*it-x);
        }
    }
    return 0;
}


expected results are s = {1, 4, 7, 8, ...} all the sum of all the subset of arr. but not working properly.. i don't know why..

Are all the data members initialized to 0 or are they assigned random values by the constructor which is called automatically?

I tried to check what values are assigned to the data members when we do not call a constructor manually. I got 0 for both a and b, but I got 1 for c, so how are the data members initialized? Randomly or to 0? And if they are initialized to 0, why am I seeing 1 as the value for c?

#include<iostream>
using namespace std;

class Class
{
    public:
        int a,b,c;      
};

int main()
{
    Class obj;

    cout<<obj.a;
    cout<<"\n";
    cout<<obj.b;
    cout<<"\n";
    cout<<obj.c;

    return 0;
}

The output is 0 0 1

But I expected 0 0 0

Need explanation about KeyId/CertId/CertPathId/PassPhraseId

In onvif i come across the term KeyId/CertId/CertPathId and PassPhraseId what are these? How these are all created ?

vendredi 29 mars 2019

How to add to a collection which is already stored in a collection?

I have the following:

class SpritesheetManager{

        std::unordered_map<std::string,std::unordered_set<std::string>> _loadedFiles;

        void addFileToFileListForSheet(std::string sheetprefix,std::string filename);
}

When adding files I do this:

void SpritesheetManager::addFileToFileListForSheet(std::string sheetprefix,std::string filename){
    bool containsKey = (_loadedFiles.find(sheetprefix)!= _loadedFiles.end());

    std::unordered_set<std::string> values;
    if(!containsKey){
        _loadedFiles[sheetprefix] = values;
    }

    _loadedFiles[sheetprefix].insert(filename);
}

Is there a better way to do this?

Finding max sum contiguous subarray when atmost k elements can be omitted?

Eg- n=10
arr[]={6,-5,3,-7,6,-1,10,-8,-8, 8}
For k=0, best segment is 5-7 with sum=15. For k=2, best segment is 1-7 with sum=24.
For k=6, best segment is 1-10 with sum=33.

I think, let dp[i][j] denote the maximum segment ending at position i with at most j elements dropped. Inductively compute dp[i][j]from dp[i][j-1]. But how to keep track of elements removed from dp[i][j-1] and not to remove them again??? I am confused in dp problems. I want to know dp approach and some other approach if possible?

passing struct by reference in c++ doesnt update the value

i am passing a struct by reference to one function of a class and storing it there in a vector.

Then passing the same struct by reference to another function and performing some computation on data member of struct. This data member gets updated in the original struct but not in the ones stored in the vector.

(Sorry for any mistakes, new to c++, new to stack overflow). Please help.

//Structure description
Struct node{

    int x;
    int y;
    int cal; //value to be updated by func

};

int main(){

    treestr * tree= new treestr(); //create object
    node n={1,5,0}
    tree->insert(n);
    int node.cal=tree->func(n);
    return 0;

}

//class description
class treestr{

    insert(node&){
        //store nodes
    }

    func(node&){
        //calculations
        return node.cal;
    }

};

The cal gets updated in the main function but not in the class where I have stored.

How to use perform a select on table under schema in postgres Database?

i'm trying to perform a select operation on postgres DB table and i'm getting below error:

[etb@centos etbtest]$ ./a.out

Opened database successfully: ETBDB ERROR: relation "etb_reference.etb_member" does not exist LINE 1: SELECT * FROM etb_reference.ETB_MEMBER

how do we refer the schema name in libpq++ exec function?

i tried escaping the schema name with other escape options like ",',\ etc but it didn't help.

my code :

   try {
      connection C("dbname = ETBDB user = etbadm password = etbtest \
      hostaddr = 127.0.0.1 port = 5432");
      if (C.is_open()) {
         cout << "Opened database successfully: " << C.dbname() << endl;
      } else {
         cout << "Can't open database" << endl;
         return 1;
      }

       work wrk(C);

   result res = wrk.exec("SELECT * FROM etb_reference.ETB_MEMBER");

   for (
      pqxx::result::const_iterator row = res.begin();
      row != res.end();
      ++row)
    {

     std::cout
        << row["MEMBER_ID"].as<int>() << "\t"
        << row["SYS_CRE_DATE"].as<std::string>() << "\t"
        << row["SYS_UPD_DATE"].as<std::string>() << "\t"
        << row["MEMBER_CS"].as<std::string>() << "\t"
        << row["MEMBER_TD"].as<std::string>() << "\t"
        << row["MEMBER_ASD"].as<std::string>() << "\t"
        << row["MEMBER_ITM"].as<std::string>() << "\t"
        << std::endl;

    }
C.disconnect ();
 return 0;

   } catch (const std::exception &e) {
      cerr << e.what() << std::endl;
      return 1;
   }
}

How to declare function with argument that is a closure in C++11 in a Cuda device function?

I'm working on Cuda with C++11 (I don't think Cuda supports later C++ versions yet). I've a closure object that is passed to the function Process() which calls the closure for each iteration.

I understand that std:: functionality is generally not available in Cuda. For example, when I try to use std::function< float(uint32_t) >, I get this error:

error: calling a host function("std::function ::function< ::, void, void> ") from a global function("_NV_ANON_NAMESPACE::LargeKernel") is not allowed

What can I replace lookupFunc with so that this compiles without std::function being available? I was able to work around this by creating a function template to deduce the type of the lambda function.

This code works and shows the work around I've employed:

//using lookupFunc = std::function< float(uint32_t) >;

template< typename Lambda > // Work around with function template
__device__
void Process(float       * const outData,
             const  int32_t      locationX,
             const Lambda /* lookupFunc */ lambda)
{
    float answer = 0.f;

    for( int32_t offset = -1 ; ++offset < 1024 ; )
    {
        const float value = lambda( offset );

        answer += value;
    }

    outData[ locationX ] = answer;
}

__global__
void LargeKernel(const float * const inData,
                 float       * const outData)
{
    constexpr uint32_t cellStride = 1;
    const     int32_t  locationX  = threadIdx.x + blockDim.x * blockIdx.x;
    const auto lambda
        = [locationX, inData, cellStride](const int32_t offset)
          {
              return inData[ locationX + offset + cellStride ];
          };

    Process( outData, locationX, lambda );
}

I also tried:

using lookupFunc = float(* const)(uint32_t);

But that gives error:

error: no suitable conversion function from "const lambda ->float" to "float (*)(uint32_t)" exists

How can I declare the type of the third argument to Process() without using a template?

Is there a function to remember the state(line number) of std::getline() in ifstream

TL;DR: I want to remember the line number when using function std::getline(), so when std::getline finishes at line 33, I would like to resume my searches at line 33 forgetting about the lines before it.

I'm reading data from a text file, the text file is acting like a instance of an database. Most of my reading relies on std::getline() function, as data is ordered I know that the the next line MAY contain certain data, although when my all statements are executed it jumps back to "while (std::getline(infile, line))" function but it starts at line 2. How would I store the "std::getline" state(line number)?

I've tried using

int buffer;                 
ifstream_file.read(reinterpret_cast<char *>(&buffer), sizeof(buffer));
ifstream_file.seekg(-1 * sizeof(buffer), std::ios::cur);

although that doesn't quite work there, I can't exactly say why(sorry for that!).

That's how it all begins(rest of the code are just std::getlines())

while (std::getline(ifstream_file, line)) {

Do const class methods prevent assigning variables outside of the class?

I have solved the problem of getting this code to compile by removing the "const". However, why does it seem I cannot assign non-class members in a const class method in this specific situation? It probably is part of the class; though, I do not understand why.

I got my code to compile, but I am confused at this situation.

Below, are some declarations in the class.

using twoDList = multimap<string,string>;
twoDList SomeMultiMap;

This will work when I take off the "const". Or at least compile. Though, here I am just assigning iterators declared only in this function.

bool object::foo(string a, string b) const
{
    pair<Speaker::twoDList::iterator,Speaker::twoDList::iterator> wordRange;
    wordRange = SomeMultiMap.equal_range(a);

    object::twoDList::iterator it = wordRange.first;

    //...
    //...
    //...
}

I expected this function to compile without removing the const, but it does not compile.

How to have variadic templates with a type and a size?

Just for fun I am trying to overload a struct, one for a std::array<T,SIZE>, one for a std::vector<T>, and a std::unordered_map<T,U>. So I did the following:

  template<typename... T>
  struct Cont; 

  template<typename T, std::size_t SIZE>
  struct Cont<T,SIZE>
  {
    Cont(std::string n) : name(n){}

    std::string name;
    std::array<T,SIZE> array;
  };

  template<typename T>
  struct Cont<T>
  {
    Cont(std::string n) : name(n){}

    std::string name;
    std::vector<T> vector;
  };

  template<typename T, typename U>
  struct Cont<T,U>
  {
    Cont(std::string n) : name(n){}

    std::string name;
    std::unordered_map<T,U> unordered_map;
  };

However, when I try to compile it, I get the error expected a type, got SIZE. Which I totally understand is because typename... T is expecting a type and not a std::size_t. So I tried:

template<std::size_t SIZE, typename... T>
struct Cont;

template<typename... T>
struct Cont;

Which also doesn't work since I am then redefining and not overloading like I originally thought I was doing. I also realize, that I can do:

template<std::size_t SIZE, typename... T>
struct Cont;

However I am trying to keep this as clean as possible in the sense when I declare them I want to be able to do:

int main()
{
  Cont<int,5> myArray("myArray");
  myArray.array = {1,2,3,4,5};

  Cont<int> myVector("myVector");
  myVector.vector = {1,2,3,4};

  Cont<int,int> myMap("myMap");
  myMap.unordered_map[0] = 2;
}

Is there a way to either overload the template? (I assume this is no) or construct a template in a way that says I'm either typename... T or typename T, std::size_t SIZE?

How to hide console window while opening hidden IE COM object using C++?

I am new to C++ so please be gentle. So i created a small C++ script which will be a part of a larger program. It creates an invisible IE and navigates to home. While that part is done, it always creates a console window when it finishes execution and then in less than a second it vanishes. What do i need to change in order to make the program work in a way that the console window won't open ?

I have tried the following code in Visual Studio and it compiles correctly. I have created a new project using windows desktop wizard.

#include "StdAfx.h"

using namespace ATL;
using namespace std;

void ThrowIfFailed(HRESULT hr)
{
    if (FAILED(hr))
        throw CAtlException(hr);
}

int main()
{
    ::CoInitialize(nullptr);

    try
    {
        CComPtr<IWebBrowser2> pWebBrowser;
        HRESULT hr = ::CoCreateInstance(CLSID_InternetExplorer, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&pWebBrowser));
        ThrowIfFailed(hr);

        hr = pWebBrowser->put_Visible(VARIANT_FALSE);
        ThrowIfFailed(hr);

        hr = pWebBrowser->GoHome();
        ThrowIfFailed(hr);

        CComPtr<IDispatch> pDispatch;
        hr = pWebBrowser->get_Document(&pDispatch);
        ThrowIfFailed(hr);

    }
    catch (const CAtlException& e)
    {

    }

    ::CoUninitialize();
    return 0;
}

This is able to create an invisible IE window which shows up in Task manager. It compiles properly and doesn't have any errors. However, it does also show a black console window. I dont want that to show. Please help. Thanks.

Conditionally define a member variable depending on the existence of the type it is made of

Suppose I have a struct for data:

struct TestData {
}

and a class with a member variable:

class TestContainer {
private:
  TestData data;
};

Both are defined in a cpp file from a macro that is used in multiple test files.

Now I want to remove the data member at compile time if there is no TestData struct defined. If a test doesn't need data then there's no need to define the data member (and it would produce a warning for not being used). I thought of using std::enable_if but failed to come up with a condition. Another approach would be to define a base template class and specializations as shown in this question, but how to specialize on the existence of a type?

How can this be done?

The problem is i need the input of the string to accept a blank line

The program is supposed to receive a string, that can have blank lines, blank spaces, and break lines. So the problem is i can't use get line, because i don't know how many break lines the user will use. I tried making a do while but it didn't work, the program stops working. It was a do while, that would receive an char and using pushback insert in the string while the char was different to EOF. I don't know how else to do it, or why this do while doesn't work. This code is using get line witch doesn't accept a break line.

'''''
#ifndef INDICE_H
#define INDICE_H
#include <cstddef>

struct Indice{
    std::size_t f;
    double p;
};

#endif
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <map>
#include "Indice.hpp"

int main()
{
    std::string str;
    std::getline(std::cin, str);

    // Count the number of occurrences for each word
    std::string word;
    std::istringstream iss(str);
    std::map<std::string,Indice> occurrences;
    while (iss >> word) ++occurrences[word].f;

    //Calculate the percentual each word
    int total = 0.0;
    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        total += it->second.f;
    }

    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        it->second.p = (static_cast<double>(it->second.f))/total;
    }
    // Print the results
    for (std::map<std::string,Indice>::iterator it = occurrences.begin(); 
         it != occurrences.end(); ++it)
    {
        if(it->first.size()>2)
            std::cout << it->first << " " << it->second.f  << " "<< std::fixed << std::setprecision(2) << it->second.p << std::endl;
    }

    return 0;
}
''''

Class Template specialization for multiple types

I found a few questions that ask something similar but could not find a straight answer for my particular case. The whole syntax for Templates is very confusing to me so I may just misunderstood something.

I have a class template that is supposed to accept every type. Simple example:

template <class T>
class State {
  public:
    void set(T newState);
    T get();
  private:
    T state;
};

template <class T>
void State<T>::set(T newState){
  state = newState;
}

template <class T>
T State<T>::get(){
  return state;
}

Now I would like to have a specialised template for a group of types that adds an additional function for these types. From what I found out so far I can utilize so called type_traits but how exactly they are used to achieve this is still a mystery to me.

F.e. this specialization for the int type but instead of writing this just for the int type I would also like to allow all other int and float variants. I found std::is_arithmetic but have no Idea how to utilize it to achieve this.

template <>
class State <int> {
  public:
    void set(int newState);
    int get();
    int multiplyState(int n);
  private:
    int state;
};

void State<int>::set(int newState){
  state = newState;
}

int State<int>::get(){
  return state;
}

int State<int>::multiplyState(int n){
  return state*n;
}

C++: sizeof(member) in the definition of the class

Is the following code well-formed?

#include <cstddef>

struct Test
{
    int      member;
    static constexpr const size_t   Size1 = sizeof(member);
    static constexpr const size_t   Size2 = sizeof(decltype(member));
    static constexpr const size_t   Size3 = sizeof(Test::member);
};

The problem is sizeof(member) used in the definition of the class itself. All Size1, Size2 and Size3 initializers went fine with gcc, clang and newer MSVC. But MSVC 14 isn't happy with Size1 (the other two are ok). It says:

error C2327: 'Test::member': is not a type name, static, or enumerator

which baffles me, because member (whether qualified or not) seems a valid expression in the context of that class.

So, should I take this as a bug in older MSVC, or is such error message justified?

Is there a way to control flow of C++ code from outside?

I have a sample code :

#include<iostream>
main()
{
    int i = 10; //Line 1
    std::cout<<" i : "<<i; //Line 2
}

I want to somehow insert another statement (lets say one more std::cout) between Line-1 and Line 2.

Direct way is to change the source code and add required line. But for my source code compilation takes lot of time, so i can't afford to change the code frequently. So i want an automatic way such that i will be able to execute any statement in any function from outside so that upon hitting that function it execute my newly given statement.

I am not sure if this is possible or not. But any direction in writing the original code in such a way that my requirement can be fulfilled would be helpful.

[for debugging prupose]

How to make a type alias depending on a compile-time constant?

I want to write a class that makes use of numerical quadrature. The quadrature order defines the size of some containers that I will use. I would like to make a type alias for such containers and it has to depend on the quadrature order.

The following code shows my trials. It feels suboptimal in the sense that I have to repeat the order in the type alias definition:

#include <array>

class Quadrature
{
public:

        static constexpr unsigned int getOrder()
        {
                return 3;
        }

        // This line doesn't compile!
        //
        // using WeightsContainer = std::array<double, getOrder()>;
        //
        // g++ says "error: 'static constexpr unsigned int Quadrature::getOrder()'
        // called in a constant expression before its definition is complete"

        // This line compiles, but repeats the order. :-(
        using WeightsContainer = std::array<double, 3>;

private:

        WeightsContainer container;
};

One solution that I have found is introducing a template parameter Order. But actually I wanted to determine the quadrature order and introducing the template parameter would make it variable.

Is there a possibility to make the order a compile-time constant and use it within my type alias definition?

generate lambdas body (that invokes a callable and returns) depending on template type

I have a callable object that might return bool or void. This object needs to be wrapped in a lambda. This lambda should always return bool. If the callable object returns bool then lambda return whatever is returned by the object. Otherwise (if object returns void) lambda just invokes it and returns true.

I tried to simplify the code below as much as possible.

template<class... Params>
struct SParamsPack {};

template <class T> struct SFuncInfo {};

// in the simplified version specialization only for member function
template <class T, class R, class... FuncParams>
struct SFuncInfo<R(T::*)(FuncParams...)> {
    using Signature = std::function<bool(FuncParams...)>;
    using Ret = R;
    using Params = SParamsPack<FuncParams...>;
};

template<class T, class Func, class... Params>
SFuncInfo<Func>::Signature GenerateVoidLambda(Func f, T* pObj, SParamsPack<Params...>)
{
    return [pObj, f](Params&&... params) -> bool
    {
        std::invoke(f, pObj, std::forward<Params>(params)...);
        return true;
    };
}

template<class T, class Func, class... Params>
SFuncInfo<Func>::Signature GenerateBoolLambda(Func f, T* pObj, SParamsPack<Params...>)
{
    return [pObj, f](Params&&... params) -> bool
    {
        return std::invoke(f, pObj, std::forward<Params>(params)...);
    };
}

// bodies of both WrapMemberFunction are almost identical
template<class T, class Func, std::enable_if_t<std::is_same<typename SFuncInfo<Func>::Ret, bool>::value, bool> = true>
SFuncInfo<Func>::Signature WrapMemberFunction(Func f, T* pObj)
{
    return GenerateBoolLambda(f, pObj, SFuncInfo<Func>::Params());
}

template<class T, class Func, class = std::enable_if_t<std::is_same<typename SFuncInfo<Func>::Ret, void>::value>>
SFuncInfo<Func>::Signature WrapMemberFunction(Func f, T* pObj)
{
    return GenerateVoidLambda(f, pObj, SFuncInfo<Func>::Params());
}

//! Registers a std::function that returns bool.
template<class... Params>
void RegisterCommand(const string& id, std::function<bool(Params...)> f)
{
    // Code for registration of command.
}

//! Registers a member function pointer as a command.
template<class T, class Func>
void RegisterCommand(const string& id, Func f, T* pObj)
{
    RegisterCommand(id, CommandRegistry::WrapMemberFunction(f, pObj));
}

The user's call would look like this:

RegisterCommand("general.create", &SomeObj::OnCreate, pSomeObject);

So is there any way to make this code look nicer? Is it possible to get rid of at least of WrapMemberFunction or GenerateLambda methods?

Any other tips on how to simplify this code are much appreciated.

Move semantics: why is the destructor called on the moved instance and is that a problem?

I'm catching up with modern C++, practicing move semantics.

I made a very simple test case:

  • create an instance
  • move-construct a new instance

I noticed that when my instances are destroyed, both destructors are called:

  • the one of the move-constructed instance, where data is a valid pointer
  • the one of the original instance, where the data pointer was deleted and set to nullptr when it was moved

My code deleting a nullptr makes me uncomfortable, here are the questions:

  • is that (deleting nullptr) even a valid operation (i.e. does that result in UB; will it eventually crash my application)?
  • or is my move-constructor / move-assignement operator definition wrong?
  • I found this similar question, but it is still not clear, in particular if deleting a nullptr is a problem. Should I avoid that by checking the pointer in the destructor? If so, it feels like using move semantics causes kind of systematic wrong behavior.

My output for the test (code below) is:

Test 5
        new 0x7512b0
        move_new 0x7512b0
        delete[] 0x7512b0
        delete[] 0

The delete[] 0 output is what grinds my gears.

Here's the main:

#include <iostream>
#include "test5.h"
int main()
{
    std::cout << "Test 5" << std::endl;

    test5 rule5;
    test5 rule5move = std::move(rule5);
    // rule5 = std::move(rule5move);

    return 0;
}

and here's test5.h:

#ifndef TEST5_H
#define TEST5_H

class test5
{
public:
    test5(): data(new float[10]){
        std::cout << "\tnew " << data << std::endl;
        for (int i = 0; i < 10; i++)
            data[i] = float(i);
    }

    ~test5(){
        std::cout << "\tdelete[] " << data << std::endl;
        delete[] data;
    }

    // copy constructor
    test5(const test5& t) : data(new float[10]){
        std::cout << "\tcopy " << data << std::endl;
        std::copy(t.data, t.data + 10, data);
    }

    // copy operator
    test5& operator=(const test5& t){
        std::cout << "\tassign " << data << std::endl;
        std::copy(t.data, t.data + 10, data);
        return *this;
    }

    // move constructor
    test5(test5&& t): data(new float[10]){
        delete[] data;
        data = t.data;
        std::cout << "\tmove_new " << data << std::endl;
        t.data = nullptr;
    }
    // move operator
    test5& operator=(test5&& t){
        delete[] data;
        data = t.data;
        std::cout << "\tmove_assign " << data << std::endl;
        t.data = nullptr;
        return *this;
    }

private:
    float* data;
};

#endif // TEST5_H

C++ Deduced conflicting types in template pack with reference

I'm working on a program with following structure:

#include <iostream>
#include <string>

void fun(const std::string &text, int a, int b) { // (1)
    std::cout << text << a + b << std::endl;
}

template<typename ...Args>
void execute(void(*fun)(Args...), Args ...args) {
    fun(args...);
}

void init(const std::string &text, int a, int b) {
    execute(fun, text, a, b);
}

int main() {
    init("Fun: ", 1, 2);
    return 0;
}

and I get the error message

.code.tio.cpp:14:2: error: no matching function for call to 'execute'
        execute(fun, text, a, b);
        ^~~~~~~
.code.tio.cpp:9:6: note: candidate template ignored: deduced conflicting types for parameter 'Args' (<const std::__cxx11::basic_string<char> &, int, int> vs. <std::__cxx11::basic_string<char>, int, int>)
void execute(void(*fun)(Args...), Args ...args) {
     ^
1 error generated.

I can fix the error by removing the reference in line (1):

void fun(const std::string text, int a, int b) {

but I want to pass the values by reference and not by value. The function template

template<typename ...Args>
void execute(void(*fun)(Args...), Args ...args)

must not be changed. How can I fix this so that text is passed by reference, execute is not changed and init is also not changed if possible?

Pause and resume a thread from another thread in a multi threaded environment in C++ technical suggestions

I would like to practice in a multi threading environment and I would like to create a program for an imaginary scenario when the program cyclically save the produced data to prevent data loss into a file in case of a crash. So basically in a multi threaded environment one thread is saving data cyclically into a file and when a crash happens and the program is restarted it will load back the data from this file and can keep going. So I am wondering what direction should look into? I am also wondering about design patterns regarding this matter.

Also I would like to pause this cyclical save thread from another thread, but leave the other threads going, for like a scenario when a shutdown is happening in the program to not save the data.

Thanks in advance.

lambda with conversion function to pointer to function with c++ linkage

C++ standard has a below statement:

The closure type for a non-generic lambda-expression with no lambda-capture whose constraints (if any) are satisfied has a conversion function to pointer to function with C++ language linkage (10.5) having the same parameter and return types as the closure type’s function call operator.

To understand the statement much better, I used the cppinsights to see what the clang compiler says for the below function.

#include <iostream>

using test = void (*)(int);

int main()
{
    test t = [](int arg) { std::cout << arg << std::endl; };
}

cppinsights translates the function as:

#include <iostream>

using test = void (*)(int);

int main()
{

  class __lambda_7_11
  {
    public: inline void operator()(int arg) const
    {
      std::cout.operator<<(arg).operator<<(std::endl);
    }

    public: using retType_7_11 = void (*)(int);
    inline operator retType_7_11 () const
    {
      return __invoke;
    }

    private: static inline void __invoke(int arg)
    {
      std::cout.operator<<(arg).operator<<(std::endl);
    }


  } __lambda_7_11{};

  using FuncPtr_7 = test;
  FuncPtr_7 t = static_cast<void (*)(int)>(__lambda_7_11.operator __lambda_7_11::retType_7_11());
}

As usual, the compiler generates an anonymous class with operator() overloaded along with "conversion function to pointer to function" as specified by the standard.

What I don't understand is that why a "static __invoke" function is generated and the "conversion function" is internally calling "__invoke" (directly as a function pointer) without any parameter which is expected by "__invoke"?

jeudi 28 mars 2019

How to make a variable always equal to the result of some calculations?

In math, if z = x+y/2, then z will always change whenever we replace the value of x and y. Can we do that in programming without having to specifically updating z whenever we change the value of x and y?

I mean something like that won't work, right?

int x;
int y;
int z{x + y};
cin >> x;
cin >> y;
cout << z;

For loop doesn't print all the details of the second vector element

I'm creating a database for a University project, I've come across an issue, the it prints the first element and the associating details for that agent, but for the second agent, only their name and status are printed, not their location or salary.

I've shortened my code to just display the agent name and location only the first element prints as expected, the second element does not (only prints the name.

Any advice would be greatly appreciated, thank you.

I've tried stepping through the code but nothing stands out, I'm only three months into C++

Main

string name;
    string status;
    int baseSalary = 0;
    vector<agent> members;
    location destination;


     for (int i = 0; i < maxAgents; i++)
     {
    cout << "Enter agent name: " << endl;
        cin >> name;
        cout << "Enter agent status: " << endl;
        cin >> status;
        members.push_back({ name, status, baseSalary });
    }


    for (int j = 0; j < maxAgents; j++)
    {
        if (members[j].getAgentStatus() == "Active")
        {
            destination.changeLocation(members, maxAgents);
cout << "\nAgent Name: " << members[j].getAgentName();
            cout << "\nAgent location: " << members[j].getAgentLocation();
        }
    }

location.cpp

agent location::changeLocation(vector<agent> &member, int size)
{
    srand((unsigned int)time(NULL));

    for (int i = 0; i < size; i++)
    {
        if (member[i].getAgentStatus() == "Active")
        {
            int location = rand() % 5 + 1;
            switch (location)
            {
            case 1:
                member[i].setAgentLocation("Russia");
                member[i].setSalary(45000);
                break;
            case 2:
                member[i].setAgentLocation("Middle-East");
                member[i].setSalary(60000);
                break;
            case 3:
                member[i].setAgentLocation("Turkey");
                member[i].setSalary(28000);
                break;
            case 4:
                member[i].setAgentLocation("USA");
                member[i].setSalary(40000);
                break;
            case 5:
                member[i].setAgentLocation("North Korea");
                member[i].setSalary(70000);
                break;
            }
        }
        return member[i];
    }
}

Agent name: input

Agent Location: Randomly generated via destination.changeLocation(members, maxAgents).

Should .at() be used over [] in std::vector or std::array?

This is related to this post that talked about .at() vs [] in std::vector. I just want to ask if .at() should be used over the bracket operators? Take the following code example:

#include <vector>
#include <iostream>

void print(const std::vector<int> &v)
{
  for(int i = 0; i < v.size(); ++i)
  {
    std::cout << v.at(i) << " ";
  }
  std::cout << std::endl;
}

int main()
{
  std::vector<int> test = {1,2,3,4};
  print(test);
}

I would not print a vector this way, I would used for(const auto &e : v) and print out every element as that is guaranteed to not go outside the bounds of the vector. However let's say for a minute we are teaching new students about for loops.

Say we change the second argument in our for loop to v.size() + 1. .at(i) will crash and give us a meaningful runtime error std::out_of_range. However if we change .at(i) to be v[i] the program runs fine and prints out an extra number for me. I'm running this on Ubuntu 18.04 on Window's, I thought the program would crash when I did that however it didn't.

So the question stands, should we be using .at() instead of [] when accessing our containers?

C++ Reduce Redundancy

I have many C++ functions in a DLL that I made specifically for Excel to call.

I frequently pass to these functions as parameters OLE VARIANTs that contain SafeArrays.

I wrote a function to act as a guard to ensure that a passed VARIANT actually contains a SafeArray and that the array is of the proper type for the occasion, both in terms of datatype and number of dimensions.

If those three criteria are satisfied the function returns a pointer to the first element and also has two out parameters to return the number of elements in each dimension (note: I only care about 1d and 2d SafeArrays).

Here is the function:

PVOID SafeArrayDataPointer(VARIANT &v, const long &ArrayType, const long &ArrayDims, long &Elems1D, long &Elems2D) {

    SAFEARRAY* pSafeArray = NULL;

    if ( V_VT(&v) & VT_ARRAY ) {

        if ( ArrayType != (V_VT(&v) & VT_TYPEMASK) ) return NULL;

        pSafeArray = V_ARRAY(&v);
        if ( ArrayDims != pSafeArray->cDims ) NULL;

        switch (ArrayDims) {
        case 2:
            Elems1D = (pSafeArray->rgsabound)[1].cElements;
            Elems2D = (pSafeArray->rgsabound)[0].cElements;
            break;
        case 1:
            Elems1D = (pSafeArray->rgsabound)[0].cElements;
            Elems2D = 0;
            break;
        default: 
            Elems1D = 0;
            Elems2D = 0;
            break;
        }

        return pSafeArray->pvData;

    } else return NULL;

}

This function works well and allows me to conveniently grab the data pointer and to get the number of elements in each dimension by calling like this (assuming vData is a VARIANT passed from Excel:

pDataArray = (VARIANT*) SafeArrayDataPointer(vData, VT_VARIANT, 2, Elems1D, Elems2D); if (pDataArray == NULL) goto error1;

However, there are two things that I do not like about this:

1.) Since the function returns a PVOID I have to cast to the relevant pointer type... but this is redundant as I've already specfied in the second argument what type of array must be contained in the VARIANT. For example in a different situation I may need to make sure that the array is of long values:

pDataArray = (long*) SafeArrayDataPointer(vData, VT_I4, 1, Elems1D, Junk); if (pDataArray == NULL) goto error1;

Again, this works fine, but it is redundant. I would much prefer some mechanism that allows the function to return the correct type of pointer. And I'm hoping this can be done without templates.

2.) I can't figure out how to NOT have the Junk parameter in the second example where I specify that the array must be 1d. Obviously, in such a case, there are no elements in the second dimension.

How to write the constructor for a template class that wraps a container where the container can be both an array or a vector?

I wish to have a general template class that allows the user to pass the container to use:

template<class Container>
struct Sum
{
  Container m_terms;
...

Other classes will derive from that, for example,

class MySum : public Sum<std::vector<int>>
{
...

or

class MySum4 : public Sum<std::array<int, 4>>
{
...

The containers need to be initialized from the constructor. My idea at first was to use std::initializer_list, for example,

MySum ms{1, 2, 3, 4};

which would require the following constructors to be added:

template<class Container>
struct Sum
{
  Container m_terms;

  Sum(std::initializer_list<typename Container::value_type> const& il) :
    m_terms(il) { }
...

class MySum : public Sum<std::vector<int>>
{
  using Sum<std::vector<int>>::Sum;
...

but then how can I get MySum4 to work too? An array doesn't take a std::initializer_list<>.

Here is more complete code that shows the compiler error: https://wandbox.org/permlink/CZW3YaKdInwZZD8e

How to save an object with string variables to a binary file in C++?

I'm working on a project for my programming class, and I have to save an object to a file in binary format. The problem I'm facing is that the object has string variables in it. When I write the object to the file and read the data into another object, the receiving object gets the correct strings, but closing the program and rerunning it and rereading the data into the object shows that the strings are not correctly read.

I tried writing the size of the object in the binary file before writing the object to the file, but no matter how big the strings are, the size of the object stays the same.

The object:

class Song
{
    unsigned int file_size;
    string artist,
           song_name;

public:
    //input song data
    void input()
    {
        cout << "Artist: ";
        cin >> artist;
        cout << "Song: ";
        cin >> song_name;
        cout << "File size: ";
        cin >> file_size;
    }
};

The reading and writing:

Song x, y;
unsigned int file_size_x;

x.input( );  //input song data

file_size_x = sizeof(x);

//write size of song object, and the song object
file.write(reinterpret_cast<char *>(&file_size_x), sizeof(file_size_x));
file.write(reinterpret_cast<char *>(&x), sizeof(x));

//read size of song object, and put song data into another song object
file.seekg(0, ios::beg);
file.read(reinterpret_cast<char *>(&file_size_x), sizeof(file_size_x));
file.read(reinterpret_cast<char *>(&y), file_size_x);
y.print( );

Results before closing program:

Enter the artist: TestArtist
Enter the song: TestSong
Enter the file size: 2

TestArtist, TestSong, 2

Results after reopening program (no input, just rereading data from file):

 @ Ç@   ,   m  ╩çv, 2

new to c++ doubly link list advice/corrections please

I'm currently working on making a Racko card game using doubly link list, but I am still new to c++ and doubly link list are going over my head a bit, at least how I am required to write it.

The Card Class

This class is responsible for storing information on a card for the game. A Card is a doubly-linked node with both a previous and next pointer to other Cards. Note that in the test, the constructor is called with different numbers of arguments. This is because both prev and next have default parameter values of nullptr (read 5.9 in the book). In addition to the parameterized constructors, this class should have methods for accessing and setting its fields.

The Deck Class

This class is responsible for holding decks of cards in the Racko game. We will have separate decks for the discard pile and the draw pile. For most purposes, a Deck is a stack linked together by Cards with the one caveat that you can also insert into any position. This class should have the following additional methods:

MakeFullDeck () Creates a starting Racko deck of all 60 cards. Push () Creates a new Card from the passed in value and puts it on top of the Deck. Discard () Similar to Push but takes in a Card* instead of making a new Card. Draw () Removes the Card from the top of the Deck and returns it. Peek () Returns the value of the Card on top of the Deck without removing the Card. Shuffle () Rearranges the Cards in the Deck. You can choose how the Deck gets rearranged. InsertAt () Inserts a Card at the given position, starting from 0.

I am working of a test.cpp test case file that I need to pass with my code by doing "make clean test". I marked out the classes I am not working on and I have already gotten my card.cpp class to pass its test, but I'm stuck on the deck.cpp test case. the test case file is below. I'm actually stuck on the deck.cpp and I haven't been able to figure out the proper way to write the code as a doubly linked list and really need some help. The card class is supposed to be the equivalent to a node class that you would back when traditionally doing linked list, but my instructions where very specific.

#define CATCH_CONFIG_MAIN

#include <set>

#include "catch/catch.hpp"
#include "../card.hpp"
#include "../deck.hpp"
/*#include "../hand.hpp"
#include "../player.hpp"
#include "../game.hpp"
*/
TEST_CASE("Test card class")
{
    Card* twelve = new Card(12);
    REQUIRE(twelve->GetValue() == 12);
    Card* one = new Card(1, twelve);
    Card* two = new Card(2, twelve, one);
    one->SetPrev(two);
    twelve->SetNext(two);
    REQUIRE(twelve->GetNext()->GetValue() == 2);
    REQUIRE(one->GetPrev()->GetValue() == 2);
    REQUIRE(twelve->GetNext()->GetPrev()->GetValue() == 12);
    REQUIRE(one->GetPrev()->GetNext()->GetValue() == 1);
}


TEST_CASE("Test deck basics")
{
    // create deck
    Deck deck;
    REQUIRE(deck.Peek() == -1);
    deck.Push(1);
    deck.Push(2);
    deck.Push(3);
    deck.Push(4);
    deck.Push(5);
    deck.Push(6);
    Card* six = deck.Draw();
    REQUIRE(six->GetValue() == 6);
    REQUIRE(six->GetNext() == nullptr);
    REQUIRE(six->GetPrev() == nullptr);

    REQUIRE(deck.Peek() == 5);

    deck.Discard(six);
    REQUIRE(deck.Peek() == 6);
}

/*
TEST_CASE("Test full deck")
{
    Deck deck;
    deck.MakeFullDeck();

    //check for fullDeck    
    std::set<int> seen;
    bool correctCards = true;
    int numberOfCards = 0;
    Card* nextCard = deck.Draw();
    while(nextCard != nullptr)
    {
        numberOfCards++;
        int cardValue = nextCard->GetValue();
        if((cardValue < 1) || (cardValue > 60) || !seen.insert(cardValue).second)
        {
            correctCards = false;
            break;
        }
        nextCard = deck.Draw();
    }
    REQUIRE((correctCards && (numberOfCards == 60)));
}
*/

/*
TEST_CASE("Test shuffling")
{
    Deck unshuffledDeck;
    Deck shuffledDeck;
    unshuffledDeck.MakeFullDeck();
    shuffledDeck.MakeFullDeck();
    shuffledDeck.Shuffle();

    bool deckShuffled = false;

    Card* fromUnshuffled;
    Card* fromShuffled;
    for(int comparisonIndex = 0; comparisonIndex < 60; comparisonIndex++)
    {
        fromUnshuffled = unshuffledDeck.Draw();
        fromShuffled = shuffledDeck.Draw();
        if(fromUnshuffled->GetValue() != fromShuffled->GetValue())
        {
            deckShuffled = true;
            break;
        }   
    }
    REQUIRE(deckShuffled);
}
*/

/*
TEST_CASE("Testing user hand functions")
{
    Hand myHand;

    for (int i = 10; i > 0; --i)
    {
        myHand.AddToHand(new Card(i));
    }

    REQUIRE(myHand.HasRacko());

    Card* twenty = new Card(20);
    Card* two = myHand.SwapOutCard(twenty, 2);
    REQUIRE(!myHand.HasRacko());
    REQUIRE(two->GetValue() == 2);

    Card* foo = myHand.SwapOutCard(two, 1);
    REQUIRE(foo->GetValue() == 1);
    Card* bar = myHand.SwapOutCard(twenty, 10);
    REQUIRE(bar->GetValue() == 10);
}
*/

/*
TEST_CASE("Player")
{
    Hand paw;
    for (int i = 10; i > 0; --i)
    {
         paw.AddToHand(new Card(i));
    }

    Player player1("Snuka", paw);
    REQUIRE(player1.GetName() == "Snuka");
    REQUIRE(player1.IsComputer() == false);

    REQUIRE(player1.ShowHand() == "1: 1\n2:  2\n3:   3\n4:    4\n5:     5\n6:      6\n7:       7\n8:        8\n9:         9\n10:          10\n");

    std::string turnPrompt = player1.TurnPrompt();
    REQUIRE("Snuka's turn" == turnPrompt);

    Card* discard = new Card(20);
    player1.SwapOutCard(discard, 3);
    REQUIRE(player1.ShowHand() == "1: 1\n2:  2\n3:                    20\n4:    4\n5:     5\n6:      6\n7:       7\n8:        8\n9:         9\n10:          10\n");

    // Create empty player and add details
    Player player2;
    player2.SetName("Sophie");
    player2.SetHand(paw);
}
*/

/*
TEST_CASE("Game basics")
{
    // create game with 2 players
    std::vector<Player> players;
    Player player1;
    player1.SetName("Snuka");
    player1.SetIsComputer(true);
    players.push_back(player1);
    Player player2;
    player2.SetName("Sophie");
    player2.SetIsComputer(true);
    players.push_back(player2);

    Game game(players);

    // test show hand
    REQUIRE(game.GetPlayer(1)->ShowHand() != "");
    REQUIRE(game.GetPlayer(2)->ShowHand() != "");

    // test show discard value
    REQUIRE(game.ShowTopOfDiscardPile() > 0);

    // make sure that an empty deck refills by shuffling the discard pile
    for (int i = 0; i < 60; ++i)
    {
        Card* card = game.DrawFromDeck();
        game.Discard(card);
    }

    game.DoNextTurn(); // Quick check to ensure that simple runtime errors don't exist
    REQUIRE(!game.IsGameOver());

    Hand winningHand;

    for (int i = 10; i > 0; --i)
    {
        winningHand.AddToHand(new Card(i));
    }

    game.GetPlayer(2)->SetHand(winningHand);

    game.DoNextTurn();
    REQUIRE(game.IsGameOver());
}
*/

/*
TEST_CASE("Test computer decision")
{
    Hand hand;

    for (int i = 10; i > 0; --i)
    {
        if (i == 5)
        {
            hand.AddToHand(new Card(3));
        }
        else
        {
            hand.AddToHand(new Card((i) * 6));
        }
    }

    bool isComputer = true;
    Player player1("Snuka", hand, isComputer);
    REQUIRE(player1.IsComputer() == true);

    REQUIRE(player1.MakeChoice(31) == "p"); // discard pile is good card
    REQUIRE(player1.MakeChoice(10) == "d"); // pile was bad, draw from the deck
    REQUIRE(player1.MakeChoice(1) == "p"); // discard pile is good card
    REQUIRE(player1.MakeChoice(60) == "p"); // discard pile is good card
    REQUIRE(player1.HasRacko() == false); // discard pile is good card

}
*/

// Compile & run:
// make clean test

card.hpp:

#ifndef CARD_HPP
#define CARD_HPP
#include <iostream>
#include <string>

class Card
{
    private:
        int value;
        Card* prev;
        Card* next;
    public:
        Card(int value, Card* prev = nullptr, Card* next = nullptr);
        void SetNext(Card* next);
        void SetPrev(Card* prev);
        int GetValue();
        Card* GetNext();
        Card* GetPrev();
};
#endif

card.cpp:

#include "card.hpp"

Card::Card(int value, Card* prev, Card* next)
{
    this->value = value;
    this->prev = prev;
    this->next = next;
}

void Card::SetNext(Card* next)
{   
    this->next = next;
}

void Card::SetPrev(Card* prev)
{
    this->prev = prev;
}

int Card::GetValue()
{
    return value;
}

Card* Card::GetNext()
{
    return next;
}

Card* Card::GetPrev()
{
    return prev;
}

deck.hpp:

#ifndef DECK_HPP
#define DECK_HPP
#include "card.cpp"
#include <iostream>
#include <string>

class Deck
{
    private:
        Card* top;
        const int NUMBER_OF_CARDS_IN_RACKO_DECK = 60;
        int numberOfCardsInDeck;
    public:
        Deck();
        void MakeFullDeck();
        void Push(int value);
        void Discard(Card* card);
        Card* Draw();
        int Peek();
        void Shuffle();
        void InsertAt(Card* card, int index);
};
#endif

deck.cpp:

#include "deck.hpp"

Deck::Deck()
{
    Card* top =  nullptr;
    int numberOfCardsInDeck = 0;

}

void Deck::MakeFullDeck()
{
    //Creates a starting Racko deck of all 60 cards.
    for(int i = 1; i < NUMBER_OF_CARDS_IN_RACKO_DECK; ++i)
    {
        Card* card = new Card(i, nullptr, nullptr);
        numberOfCardsInDeck++;
        card->SetPrev(nullptr);
        card->SetNext(this->top);
        if(this->top != nullptr)
        {
            card = this->top->GetPrev();
        }else
        {
            this->top = card;
        }
    }
}

void Deck::Push(int value)
{
    //Creates a new Card from the passed in value and puts it on top of the Deck.
    Card* newCard = new Card(value, nullptr, nullptr);
    newCard->SetPrev(nullptr);
    newCard->SetNext(this->top);
    if(this->top != nullptr)
    {
        newCard = this->top->GetPrev();
    }else
    {
        this->top = newCard;
    }
}

void Deck::Discard(Card* card)
{
    //Similar to Push but takes in a Card* instead of making a new Card.
    card->SetPrev(nullptr);
    card->SetNext(this->top);
    if(card == nullptr)
    {
        return;
    }

    if(card != nullptr)
    {
        card = this->top->GetPrev();
    }else
    {
        this->top = card;
    }

}

Card* Deck::Draw()
{
    //Removes the Card from the top of the Deck and returns it.

}

int Deck::Peek()
{
    //Returns the value of the Card on top of the Deck without removing the Card.
}

void Deck::Shuffle()
{
    //Rearranges the Cards in the Deck. You can choose how the Deck gets rearranged.
}

void Deck::InsertAt(Card* card, int index)
{
    //Inserts a Card at the given position, starting from 0.
}

Any assistance would be appropriated as I am at a loss on how to write the code correctly at this point for the deck.cpp. Any corrections and advise is much appreciated.

How do you generate a random number in C++?

I have been trying to generate a random number from 0 to 29. I've tried different methods from different sources to no avail.

What is the correct initializer for a non-static 2D array?

Visual Studio allows: int a[3][3] = { 0 }; for BOTH local variable and non-static class variable. However, GCC only allows this for local variables, but requires int a[3][3] = { {0} }; for class variable initialization. Is GCC too restrictive or VS to permissive?

#include <iostream>
using namespace std;

class InitArray {
 public:
   InitArray();
   void PrintArray() const;
 private:
   int a[3][3] = { 0 };       // compiles in Visual Studio 2017, but not GCC
                              // modify to = { {0} }; to compile in GCC
InitArray::InitArray() {
   PrintArray();
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         a[i][j] = 1;
      }
   }
}

void InitArray::PrintArray() const {
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }
}

int main() {
   InitArray A;
   A.PrintArray();
   int a[3][3] = {0};          // OK in BOTH compilers
   for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
         cout << a[i][j] << " ";
      }
      cout << endl;
   }

   return 0;
}

The following code, codifiying an algebraic-group-type sometimes doesn't compile

I'm working on a modelling a algebraic group on C++, over a class of modular integers (simpliying):

    template<unsigned int N>
    struct modint_t {
    private:
       unsigned int m_i{};
    // now I implement all operators of int except those about bitwise
    public:
    // the three constructors by default
    // explicit constructor from ints
    //
    // operator <  same as between integers but only in their range
    // operator >  These comparators are not agreed with the operations
    // operator <= of the ring of modular integers.
    // operator >= But they are helping with the work. 
    // operator == it fully agrees with the modular integers ring
    // operator != it fully agrees with the modular integers ring
    // operator = Both assignations by default
    //
    // binary operators +,+=,-,-=,*,*=,^,^= (the two las are 
    //                                       exponentiation)
    // unary operators (or like operators) -, ~, !, CB,CBm1,mCB,mCBm1
    //                                     inv, invert
    // ~ and CBm1 are de complement to the Module minus 1
    // a.mCBm1() := a = a.CBm1(); a.mCBm1 := a = ~a;  
    // CB and - are the complement to de Module
    // a.mCB() := a = a.CB(); a.mCB() == !a;
    // a.inv()*a == modint(int(1)) == a*a.inv();
    // a.invert() := a = a.inv();
    //
    // explicit operator int() return a copy of m_i;
    // 
    // operators++(),operator--(),operators++(int),operator--(int)
    // next()const ,prev()const ,mnext(),mprev()
    // the increment and decrement are circulars and they are agree with
    // comparators operators
    };

Then I code a modint_cartprod_t, a type that represent a ring of cartesian product of several modular integer rings (very much simplified):

    template<unsigned N_0,unsigned ... N_s>
    struct modint_cartprod_t{
        using base_t = std::tuple<modint_t<N_0>,modint<N_s>...>;
    private:
        base_t elem{};
    // all idem as in modint_t template, it is a ring. Some more
    // constructors from list of integers etc. Helping classes and 
    // functions. I use fold expresions, except for prev(), next()... that 
    // I use an static_for class with recursion in the operator()
    };
    // concat of modint_cartprod_t s
    // extern product of integer and one modint_t or modint_cartprod_t
    // to modelling an algebraic structure of module.

As I want modelling others groups than the direct product of cyclic groups, I code a class without data member, only static operations to conform other operations, as, for example, dihedral groups (semi direct products) or quaternion group (by cohomology) and much others.

    template<group_name gn,unsigned N_0,unsigned ... N_s>
    struct {
        static modint_cartprod_t 
        direct_product(
            modint_cartprod_t a,modint_cartprod_t a
        ) {return (a+b);}

        static modint_cartprod_t 
        semi_direct_product(
            modint_cartprod_t a,modint_cartprod_t a
        ) {/* operations with an action */}

        modint_cartprod_t operator(modint_cartprod_t,modint_cartprod_t);
        // intern operation

        // neutre() and others if the neutre element exists 
        // operator-() and others if the inverse of the intern operation
        // exists
    }

The problem is in this point, for :

    template<unsigned N>
    struct binop_t<group_name::Dih,uint,2,N> {
    static constexpr
modint_cartprod_t Dih_product(modint_cartprod_t a,modint_cartprod_t b) 
{
    const UIntType i{a.get_int<0>()};/// Module 2 Error HERE
    const UIntType k{a.get_int<1>()};/// Module N Error HERE

    const UIntType j{b.get_int<0>()};/// Module 2 Error HERE
    const UIntType m{b.get_int<1>()};/// Module N Error Here

    if (j%2_u8==0) {
        const modint_cartprod_t R{i+j,m+k};
        return R;
    } else {
        const modint_cartprod_t R{i+j,m+(N-k)};
        return R;
    }
}
    };

This indicated function doesn't compile with the following error message from compiler mingw gcc8.2 (nuwen distro):

C:\Windows\system32\cmd.exe /C C:/MinGW/bin/make.exe -j8 SHELL=cmd.exe -e -f Makefile "----------Building project:[ grupos_finitos - Debug ]----------" make.exe[1]: Entering directory 'C:/Users/julia/Dropbox/GitHub/tfg_grupos_finitos/grupos_finitos' C:/MinGW/bin/g++.exe -c "C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/main.cpp" -g -O0 -Wall -std=c++17 -o ./Debug/up_up_TFG_GruposFinitos_src_FiniteGroups_main.cpp.o -I. -I. In file included from C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/main.cpp:11: C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp: In static member function 'static constexpr tfg::binop_t<(tfg::group_name)6, unsigned char, 2, N>::modint_cartprod_t tfg::binop_t<(tfg::group_name)6, unsigned char, 2, N>::Dih_product(tfg::binop_t<(tfg::group_name)6, unsigned char, 2, N>::modint_cartprod_t, tfg::binop_t<(tfg::group_name)6, unsigned char, 2, N>::modint_cartprod_t)': C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:543:29: error: expected primary-expression before ')' token UIntType i = a.get_int<0>();/// Module 2 ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:544:34: error: expected primary-expression before ')' token const UIntType k {a.get_int<1>()};/// Module N ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:546:24: error: expected primary-expression before ')' token auto j {b.get_int<0>()};/// Module 2 ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:547:30: error: expected primary-expression before ')' token const auto m {b.get_int<1>()};/// Module N ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp: In static member function 'static constexpr tfg::binop_t<(tfg::group_name)10, unsigned char, 2, N>::modint_cartprod_t tfg::binop_t<(tfg::group_name)10, unsigned char, 2, N>::Dic_product(tfg::binop_t<(tfg::group_name)10, unsigned char, 2, N>::modint_cartprod_t, tfg::binop_t<(tfg::group_name)10, unsigned char, 2, N>::modint_cartprod_t)': C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:608:24: error: no match for 'operator+=' (operand types are 'tfg::modint_cartprod_t::modint_idx<1>' {aka 'tfg::modint_t'} and 'int') sr.get_modint<1>() += (N/2); ~~~~~~~~~~~~~~~~~~~^~~~~~~~ In file included from C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/main.cpp:9: C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/modint_t.hpp:202:19: note: candidate: 'const tfg::modint_t& tfg::modint_t::operator+=(const tfg::modint_t&) [with UIntType = unsigned char; UIntType N = 2]' const modint_t & operator += (const modint_t & b) { ^~~~~~~~ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/modint_t.hpp:202:19: note: no known conversion for argument 1 from 'int' to 'const tfg::modint_t&' In file included from C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/main.cpp:11: C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp: In static member function 'static constexpr tfg::binop_t<(tfg::group_name)35, UIntType, p, q>::modint_cartprod_t tfg::binop_t<(tfg::group_name)35, UIntType, p, q>::GDih_action(tfg::binop_t<(tfg::group_name)35, UIntType, p, q>::modint_cartprod_t, tfg::binop_t<(tfg::group_name)35, UIntType, p, q>::modint_cartprod_t)': C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:666:33: error: expected primary-expression before ')' token const UIntType i{a.get_int<0>()}; ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:667:33: error: expected primary-expression before ')' token const UIntType j{a.get_int<1>()}; ^ C:/Users/julia/Dropbox/GitHub/TFG_GruposFinitos/src/FiniteGroups/binop_t.hpp:669:33: error: expected primary-expression before ')' token const UIntType k{b.get_int<0>()}; ^ make.exe[1]: * [grupos_finitos.mk:97: Debug/up_up_TFG_GruposFinitos_src_FiniteGroups_main.cpp.o] Error 1 make.exe: * [Makefile:5: All] Error 2 make.exe[1]: Leaving directory 'C:/Users/julia/Dropbox/GitHub/tfg_grupos_finitos/grupos_finitos' ====26 errors, 10 warnings====

I don't understand:

error: expected primary-expression before ')' token UIntType i = a.get_int<0>();/// Module 2 ^ The code of get_int<>() is:

    template<typename UIntType,UIntType N_0,UIntType ... N_s>
    struct modint_cartprod_t {
        using std::get;
        template<size_t k>
    inline constexpr
    UIntType
    get_int() const {
        return UIntType(get<k>(elem));
    }
    };

In others binop of groups this function compiles without signal of error.

I don't know that I can do to compile the code. I don't know really where is the error.

I you need the code, say me, and I put in GitHub all the code and I give you the link.

The variable 'pos' is being used without being initialized

I have a bug in my code. How can I deal with it? It can't compile successfully, but I can't find anything wrong.

  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.
  • I am a newbie, the first time I use this website, I don't know what else to say but it seems to have a word limit so I have to add some meaningless text, I am very sorry.

Day.h

#pragma once
#include<iostream>
#include<string>
typedef unsigned ud;
using std::string;
class Day
{
public:
    Day() = default;
    Day(string a) {
        decltype(a.size()) pos;
        if (a.find("Jan") != string::npos)
            month = 1;
        else if (a.find("Feb") != string::npos)
            month = 2;
        else if (a.find("Mar") != string::npos)
            month = 3;
        else if (a.find("Apr") != string::npos)
            month = 4;
        else if (a.find("May") != string::npos)
            month = 5;
        else if (a.find("Jun") != string::npos)
            month = 6;
        else if (a.find("Jul") != string::npos)
            month = 7;
        else if (a.find("Aug") != string::npos)
            month = 8;
        else if (a.find("Sep") != string::npos)
            month = 9;
        else if (a.find("Oct") != string::npos)
            month = 10;
        else if (a.find("Nov") != string::npos)
            month = 11;
        else if (a.find("Dec") != string::npos)
            month = 12;
        else {
            pos = a.find_first_not_of("123456789");
            month = stoi(a.substr(0, pos));
        }
        pos++;
        auto now = a.find_first_not_of("123456789", pos);
        day = stoi(a.substr(pos, now - pos));
        pos = now + 1;
        year = stoi(a.substr(pos, a.size() - pos));
    }
    ud get_year() {
        return year;
    }
    ud get_month() {
        return month;
    }
    ud get_day() {
        return day;
    }
    std::ostream& print(std::ostream& os) {
        os << year << ' ' << month << ' ' << day;
        return os;
    }
private:
    ud year;
    ud month;
    ud day;
    bool iszm(char x) {
        return (x >= 'A'&&x <= 'z');
    }
};

main.cpp

#include"pch.h"
#include<iostream>
#include<forward_list>
#include<deque>
#include<vector>
#include<string>
#include<list>
#include<array>
#include<cstdlib>
#include"Day.h"
using namespace std;
int main()
{
Day tmp("March 27,2019");
    tmp.print(cout);
return 0;
}

Difference between make_unique and make_unique with reference_wrapper in c++

struct Foo{}; What is the difference std::make_unique and std::make_unique> ?

Passing lambas as callbacks to C functions

Suppose I have a C function

typedef void (* callback_t)(void* data);
register_callback(callback_t callback, void* data);

and I want to pass a lambda as the callback.

What's the idiomatic way to do this...

  1. When the lambda captures nothing?
  2. When the lambda has captures (by value, by reference etc.)?

How to fix "Variable declaration in condition must have an initializer"

I am writing a program that counts the number of vowels that the user inputs but it is giving me the error "Variable declaration in condition must have an initializer". How do you fix it?

#include <iostream>
using namespace std;

int isVowel(char c) 
{
  char Vowels[] = {'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
  if (c in Vowels)
    return true;
}

int main()
{
  int n;
  int numVowel = 0;
  char c;

  cin >> n;

  for (int i = 0; i < n; ++i)
  {
    cin >> c;
    if (isVowel(c))
      numVowel++;
  }

  cout << "Number of vowels = " << numVowel << endl;

  return 0;
}

Need help fixing "pointer being freed was not allocated" error

I'm implementing a Rope data structure for a homework assignment and I'm having problems with my destructor. I'm getting an malloc: *** error for object 0x10056ce50: pointer being freed was not allocated error. I went through the function calls and it doesn't seem like the delete operator's being called twice. Thanx for any help! Code for the Rope destructor and Rope nodes is below:

class Node{
public:
    Node() : left{NULL}, right{NULL}, parent{NULL}, weight{0} {}
    Node* left;
    Node* right;
    Node* parent;
    int weight;
    std::string value;
};

void Rope::destroy_rope(Node* p) {
  if (p) {
    destroy_rope(p->left);
    destroy_rope(p->right);
    delete p; # error comes from this statement
  }
  size_ = 0;
  p = NULL;
}

Rope::~Rope(){
  destroy_rope(root);
}

mercredi 27 mars 2019

std::enable_if and std::conditional How to implement same functionality using c++98

In My project , std::enable_if and std::conditional is used . I have to support old GCC_VERSION. Could you please help me to implement std::enable_if and std::conditional 's functionality in C++98 ?

template<typename T>
using is_char = typename std::enable_if<sizeof (T) == sizeof (char)>::type;



template <typename ObjType,
            typename PtrType,
            typename CharType =
                typename std::conditional<std::is_const<PtrType>::value,
                                          const typename ObjType::char_type,
                                          typename ObjType::char_type>::type,
            typename = is_char<PtrType> >
    CharType* char_ptr_cast(PtrType* p)
    { return reinterpret_cast<CharType*>(p); }

What is the difference between two join statements in the code?

In the below code, there are two joins (of course one is commented). I would like to know what is the difference between when join is executed before the loop and when join is executed after the loop?

#include <iostream>
#include <thread>
using namespace std;

void ThreadFunction();

int main()
{
    thread ThreadFunctionObj(ThreadFunction);
    //ThreadFunctionObj.join();
    for (int j=0;j<10;++j)
    {
        cout << "\tj = " << j  << endl;
    }
    ThreadFunctionObj.join();
    return 0;
}

void ThreadFunction()
{
    for (int i=0;i<10;++i)
    {
        cout << "i = " << i  << endl;
    }
}

Exit Status -1 on C++ Program

When executed, my code gives an exit status -1. I can show the input if it makes any difference. Can anybody find why this is happening?

INPUT:

6

N 10

E 2

S 3

W 4

S 5

E 8

I have already looked at the 2D integer array, and the variables in my code, looking for uninitialized ones, but I found no such errors. Can anybody see why I am getting exit status -1?

#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int main() {
  ofstream fout("mowing.out");
  ifstream fin("mowing.in");
  int n; fin >> n;
  int ans = 0;
  int field[2003][2003];
  for (int i = 0; i < 2003; i++) {
    for (int j = 0; j < 2003; j++) {
      field[i][j] = 0;
    }
  }
  int xloc = 1001, yloc = 1001, time = 0;
  for (int i = 0; i < n; i++) {
    char dir; int steps;
    fin >> dir >> steps;
    if (dir == 'N') {
      for (int j = 1; j < steps; j++) {
        yloc++;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    if (dir == 'S') {
      for (int j = 1; j < steps; j++) {
        yloc--;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    if (dir == 'W') {
      for (int j = 1; j < steps; j++) {
        xloc--;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    else {
      for (int j = 1; j < steps; j++) {
        xloc++;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
  }
  if (ans == 0) fout << -1 << "\n";
  else fout << ans << "\n";
  return 0;
}

What is a good way to do inter-thread communication in c++11

So there seems to be a fairly basic thing that I don't understand about multithreading and that is how threads would communicate, and most importantly send data between each other.

For example, say you have 5 tcp connections on 5 different threads, every connection would then send a number to the server and the server would send back all those 5 numbers added together. How would one in normal c++11 communicate those numbers between the threads?

getline(cin, string) reading from ifstream instead of command line

I initialized an ifstream and opened a file from argv[1], then closed the ifstream when I finished dealing with that file. Later, I try to use getline with cin, but for some reason it begins to read from the file opened in ifstream. How can I fix this? This only happens on terminal in mac and in xcode, when my friend tested it on cygwin, it worked fine.

string arg = (string)argv[1];
ifstream fin(arg);

if(arg == "--help" || arg == "-h"){
    cout << "help message\n";
    return 0;
}

string full;
while(getline(fin, full)){
    //do stuff
}
fin.close();


string f2;
while(getline(cin, f2)){
    //do stuff
}

How to preserve TCP message boundary reading

i am trying to write tcp client server program to have message oriented communication. my message size is always 1040 bytes with 16 bytes header included.

following is the code snippet.

class connection
{
....

#define BUFFER_SIZE 65535

        uint8_t buffer[BUFFER_SIZE + BUFFER_SIZE];
        std::size_t rem_buff = BUFFER_SIZE;
        std::size_t avail_size = 0;
        uint8_t *buffer_write = buffer;
        uint8_t *buffer_reader = buffer;
        Header mh;
        long count = 0;

        bool read_header = true;
};

void connection::read()
{
    bool conn_terminated = false;
    std::size_t read_bytes = 0;

    if (rem_buff > 0) {
        assert((buffer_write + rem_buff) <= (buffer + BUFFER_SIZE));
        assert(buffer_write >= buffer_reader);
        read_bytes = utils::read(handle(), buffer_write, rem_buff, conn_terminated, false);
        if (read_bytes > 0) {
            rem_buff -= read_bytes;
            buffer_write += read_bytes;
            avail_size = buffer_write - buffer_reader;
            std::cout << "read_bytes : " << read_bytes
                << " avail_size : " << avail_size << ", rem_buff : " << rem_buff << std::endl;
        } else if (conn_terminated) {
            std::cout << "connection terminated" << std::endl;
            return;
        }
        if (avail_size < 1) {
            return;
        }
    }
    do {
        if (read_header) {
            if (avail_size > sizeof(Header)) {
                // header is ready
                read_header = false;
                mh = *(reinterpret_cast<Header*>(buffer_reader));

                buffer_reader += sizeof(Header);
                avail_size -= sizeof(Header);
                std::cout << "payload : " << mh.length()
                    << ", avail_size : " << avail_size
                    << std::endl;
                if (mh.length() > 1024) {
                    std::cout << "count : " << count << std::endl;
                }
            } else if (rem_buff == 0) {
                // there is no space left to read complete header
                memmove(buffer, buffer_reader, avail_size);

                // reinit all pointers
                buffer_reader = buffer;
                buffer_write = buffer_reader + avail_size;
                rem_buff = BUFFER_SIZE - avail_size;
                std::cout << "move1: avail_size : " << avail_size << ", rem_buff : " << rem_buff << std::endl;
                break;
            } else {
                // header is not complete
                break;
            }
        }

        if (!read_header) {
            if (avail_size >= mh.length()) {
                ++count;
                buffer_reader += mh.length();
                avail_size -= mh.length();
                read_header = true;
            } else if (avail_size < mh.length()) {
                // TODO: still not handling partial payload read
                if (rem_buff == 0) {
                    // there is no space left to read complete header
                    memmove(buffer, buffer_reader, avail_size);

                    // reinit all pointers
                    buffer_reader = buffer;
                    buffer_write = buffer_reader + avail_size;
                    rem_buff = BUFFER_SIZE - avail_size;
                    std::cout << "move2: avail_size : " << avail_size << ", rem_buff : " << rem_buff << std::endl;
                }
                break;
            }
        }
    } while (avail_size > 0);
}

randomly, that is, sometimes after 1000 messages or sometimes 30000 messages suddenly i get a very huge payload length and reading completely stops.

payload : 1024, avail_size : 1039
move1: avail_size : 15, rem_buff : 65520
read_bytes : 6225 avail_size : 6240, rem_buff : 59295
payload : 45680032226158504, avail_size : 6224