dimanche 29 janvier 2017

templates - expected unqualified-id before numeric constant

I have code that looks like this:

template <int Rows>
struct A {
    std::array<int, Rows*Rows> array;


    template <int X, int Y>
    int at(int x, int y) const {
        return array[X*x + Y*y];
    }
};


template <int Dim>
struct B {
    void dosomething(A<Dim> value) {
        auto x = value.at<0, 0>(0, 0);
    }
};

The compiler (gcc 6.3 and clang 3.9) complain about the line

auto x = value.at<0, 0>(0, 0);

with error: expected unqualified-id before numeric constant

I guess I have some ambiguity here, but I can't figure out how to resolve it. Also it is important that A and B are templates otherwise the error doesn't show up.

Some help and hints about what the compiler is really complaining about and how it could be fixed would be great.

Tuple of vectors and push back

I have a vector of tuples, I would like to push_back() each value from another tuple into the corresponding vector in the "vectors tuple". The create() function in the code is where I would like to do this.

template<typename...Fields>
class ComponentManager
{
  using Index = int;
public:
  /**
   * Provides a handle to a component
   **/
  struct ComponentHandle {
    static constexpr Index Nil = -1;
    bool nil() { return index == Nil; }
    const Index index;
  };

  ComponentHandle lookup(Entity e) { 
    return ComponentHandle{get(m_map,e,-1)}; 
  }

  template<int i>
  auto get(ComponentHandle handle) {
    return std::get<i>(m_field)[handle.index];
  }

  ComponentHandle create(Entity e, Fields ...fields) {
    m_entity.push_back(e);
    // m_fields.push_back ... ???
  }

private:
  std::vector<Entity>                m_entity;
  std::tuple<std::vector<Fields>...> m_field;
  std::map<Entity,Index>             m_map;
};

Game of Circles Algorithm

I have an algorithm problem that I want to solve. I have tried to solve it with dynamic approche but it didn't get all answers right

Coach Fegla suggested the following game: An even number (N) of contestants are chosen and asked to stand in a circle, where each contestant is given an ID. There is a number of ropes. The contestants need to be matched in pairs where each pair carry a rope without any two ropes intersecting. The cost of matching 2 people i and j is (ID[i] + ID[j])2, where ID[i] is the ID of the student standing in position i in the circle. And the cost of the entire circle is the sum of the costs of all pairs.

What is the minimum circle cost to match them in N/2 pairs so that no 2 ropes intersect?

Input The input starts with a single integer T on the first line, denoting how many test-cases are in the input.

Each test-case is given on 2 lines, the first one has a single integer N denoting the number of students in this test-case. The second line consists of N space separated integers, representing the IDs of the students in a clockwise order of their position in the circle.

Output For each test-case print one line that has an integer that is the minimum circle match cost for that test-case.

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

int t[201];
int N;
long long int minCout[201][201];

int minimum(int d,int f)
{
    if(d>=f)
        return 0;
    if(minCout[d][f]!=-1)
        return minCout[d][f];
    long long int coutMin=20000000000000000;
    for(int i=d+1;i<=f;i++)
    {
        if((i-d)%2==1)
        {
            int curValue=pow(t[d]+t[i],2)+minimum(d+1,i-1)+minimum (i+1,f);
            if(curValue<coutMin)
                coutMin=curValue;
        }
    }
    minCout[d][f]=coutMin;
    return coutMin;
}


int main()
{
    ifstream myfile;
    myfile.open ("game.in");
    int test;
    myfile>>test;
    for(int i=0;i<test;i++)
    {
        myfile>>N;
        for(int j=0;j<N;j++)
            myfile>>t[j];

        for(int j=0;j<N;j++)
            for(int k=0;k<N;k++)
                minCout[j][k]=-1;

        cout<<minimum(0,N-1)<<endl;
    }
    myfile.close();
}

this are the test given to me

input

2

2

1 2

4

1 2 1 2

output

9

18

Can you please help me find an exemple that don't work with my algorithm I have done many exemple in paper and I didn't find an exemple that don't work. Or can you tell me the error in my algorithm and what méthode to use when solving such problem.

How can I hash a std::regex?

I need to hash a class which has a std::regex as a member which is initialized from a string in the class' constructor.

To get a good hash for the class, I could either store the hash of the pattern string in the constructor or -- the preferred way -- compute a hash of the regex itself. Is this possible (preferrably without boost)?

More precisely: I would like to calculate

std::hash<std::regex>{}(m_regex);

where m_regex is of type std::regex, but the template specialization for std::regex does not exist.

Thanks very much for your help.

How to initialize all members of a fixed-size array to the same, changeable value [duplicate]

This question already has an answer here:

First have a look at How to initialize all members of an array to the same value.

I like mouviciel's answer, but I find myself in a situation where the size of a fixed-size array needs to be changed very often in the code.

Which alternatives, if any, do I have (besides initializing it manually or using a for loop)?

Should I pass allocator as a function parameter? (my misunderstanding about allocator)

After I am studying about allocator for a few days by reading some articles
(cppreference and Are we out of memory) ,
I am confused about how to control a data-structure to allocate memory in a certain way.

I am quite sure I misunderstand something,
so I will divide the rest of question into many parts to make my mistake easier to be refered.

Here is what I understand so far ...

Snippet

Suppose that fb() is an existing function that generate a list of B from a list of BPrototype.
fb() is used in B() constructor:-

class B{
    public: std::vector<B> fb(){
        std::vector<BPrototype> prototypes = getPrototypes();
        std::vector<B> result;                     //#X
        for(int n=0;n<prototypes.size();n++){
            //construct real object  (BPrototype->B)
            result.push_back(makeItBorn(prototypes[n])); 
        }
        return result;
    }
    std::vector<B> bField;    //#Y
    public: B(){
        this->bField=fb();    //#Y  ; "fb()" is called only here
    }
    //.... other function, e.g. "makeItBorn()" and "getPrototypes()"
};

From the above code, std::vector<B> currently uses a generic default std::allocator.

For simplicity, from now on, let's say there are only 2 allocators (beside the std::allocator) ,
which I may code it myself or modify from somewhere :-

  • HeapAllocator
  • StackAllocator

Part 1 (#X)

This snippet can be improved using a specific type allocator.
It can be improved in 2 locations. (#X and #Y)

std::vector<B> at line #X seems to be a stack variable,
so I should use stack allocator :-

std::vector<B,StackAllocator> result;   //#X

This tends to yield a performance gain. (#X is finished.)

Part 2 (#Y)

Next, the harder part is in B() constructor. (#Y)
It would be nice if the variable bField has an appropriate allocation protocol.

Just coding the caller to use allocator explicitly can't achieve it, because the caller of constructor can only do as best as :-

std::allocator<B> bAllo;   
B* b = bAllo.allocate(1);   

which does not have any impact on allocation protocol of bField.

Thus, it is duty of constructor itself to pick a correct allocation protocol.

Part 3

I can't know whether an instance of B will be constructed as a heap variable or a stack variable.
It is matter because this information is importance for picking a correct allocator/protocol.

If I know which one it is (heap or stack), I can change declaration of bField to be:-

std::vector<B,StackAllocator> bField;     //.... or ....
std::vector<B,HeapAllocator> bField;     

Unfortunately, with the limited information (I don't know which it will be heap/stack, it can be both),
this path (using std::vector) leads to the dead end.

Part 4

Therefore, the better way is passing allocator into constructor:-

MyVector<B> bField; //create my own "MyVector" that act almost like "std::vector"
public: B(Allocator* allo){
    this->bField.setAllocationProtocol(allo);  //<-- run-time flexibility 
    this->bField=fb();   
}

It is tedious because callers have to pass an allocator as an additional parameter,
but there are no other ways.

Question

  • Where do I start to go wrong, how?
  • How can I improve the snippet to use appropriate allocator (#X and #Y)?
  • When should I pass allocator as a parameter?

It is hard to find a practical example about using allocator.

Another vector iterator not dereferencable issue

I've currently reached an issue where attempting to use an auto-for iterator loop is failing, but is not due to an invalid usage (e.g. using end() incorrectly).

With this code, the at() usage works fine, but the iterator one fails (regardless of auto or manual specification):

size_t  sz = cfg_profiles.size();
for ( size_t i = 0; i < sz; i++ )
{
        responses[id]->str_vect.emplace_back(cfg_profiles.at(i).profile_name);
}
for ( auto& prf : cfg_profiles )
{
        responses[id]->str_vect.emplace_back(prf.profile_name);
}

cfg_profiles is a std::vector<config_profile>, where config_profile is a struct containing strings, a string vector, and a 'deep-copy' assignment constructor. It was populated earlier by the same library (and file).

I've tracked the issue down to the container proxy being missing, as pictured - though I have no idea how it's been able to get into this state:

vector

I can guarantee the vector is not being modified elsewhere, as this is running in a std::thread created by, and member of, the owning class.

I tried making a minimal, reproducible form in a new project without success - is there any reason the vector could get into this state, or somewhere obvious I should be looking?