vendredi 1 mai 2020

How can i convert string to variable

I have a function in which i am receiving a string values .

Based on the value i want to create a variable.

Template<typename T>
void func( std::string str , T value )
{
    if( str == "int" )
     {
          int val = value;

     }

     if( str == "double" )
     {
          double val = value;

     }

    if( str == "string" )
     {
          std:string val = value;

     }    
}

is it possible to automate this function , instead of having lot of if conditions ?

How to Break out of Recursion Search after desired value found?

I am trying to solve a Competitive Programming problem, and I have created a method that returns a paired vector seen below:

bool warning = false;
vector<pair <int,int>> search(vector <pair <int,int>> vi){
    vector <pair <int,int>>m;
    if (warning){
        return m;
    }
    bool alg = false;
    if (vi.size() == 1){
        m = vi;
        warning = true;
    }
    for (int i = 0; i < vi.size()-1; i++){
        if (vi[i].second >= vi[i+1].first){
            alg = true;
            //auto it = vi.begin() + i;
            //auto it1 = vi.begin() + i + 1;
            vector <int> b{vi[i].first, vi[i].second, vi[i+1].first, vi[i+1].second};
            sort(b.begin(), b.end());
            vi.push_back(make_pair(b[0],b[3]));
            vi.erase(vi.begin() + i);
            vi.erase(vi.begin() + i);
            sort(vi.begin(), vi.end());
            //cout << "round one";
            search(vi);
            break;
        }
    }
    if (!alg){
        warning = true;
        m = vi;
        sort(vi.begin(), vi.end());
    }
}

Basically when I reach the bottom statement, I want to return the paired vector, and immediately exit out of the code, as that is what I am trying to achieve.

Thank you

Efficient adjacency list representation in C++

The standard representation of an adjacency list for weighted graphs in C++ is an array of vectors of pairs is often (ie. vector<pair<int, int>> adj[N]). I don't have any issues with this when I know the size of N at compile time, and if N isn't too big. However, when N is only known at run-time (a variable), I have to resort to making N the upper bound of the adjacency list size. I often run into segmentation faults where, if I am not mistaken, the array max_size is exceeded. For example, I am currently encountering this problem with the bounds N <= 3000*2999/2 (about 45000000).

Below is an example with Prim's MST algorithm in which I get a Segmentation Fault. How can I avoid this? Should I consider other data types? Thanks!

Edit: I could just use a vector and initialize it with a loop from 1 to n, but I'm wondering if there's a more efficient way.

int prims(int n, vector<vector<int>> edges, int start) {
vector<pair<int, int>> adj[45000000];
for(vector<int> edge : edges){
    adj[edge[0]].push_back({edge[2], edge[1]});
    adj[edge[1]].push_back({edge[2], edge[0]});
}
vector<bool> visited;
for(int i=0; i<n; i++){
    visited.push_back(false);
}
int dist = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push({0, start});
while(!pq.empty()){
    pair <int, int> p = pq.top();
    pq.pop();
    // cout << "top is " << p.second << "\n";
    if(visited[p.second]) continue;
    visited[p.second] = true;
    dist += p.first;
    for(pair<int, int> j : adj[p.second]){
        if(!visited[j.second]){
            pq.push(j);
        }
    }
}
return dist; }

Segmentation fault 11 DFS maze solution

What seems to be the error? it keeps returning segmentation fault 11. this is supposed to be a solution to a maze using DFS. ............................... ...............................

std::vector<MazeNode> solveDFS(Maze &a_maze){   
MazeNode* nextNode = a_maze.getFirstNode(); 
std::vector<MazeNode> nodes; 
std::stack<MazeNode*> nodesPtr;

nextNode->setVisited();//set origin as visited 
nodesPtr.push(a_maze.getFirstNode());//add origin to stack
nodes.push_back(*a_maze.getFirstNode());//first node added to vector
//cout << a_maze.getFirstNode() << endl;

while(!nodesPtr.empty()){
MazeNode* TopStack = nodesPtr.top();
if(canTravel(TopStack->getDirectionNode(directions::NORTH))){
   nextNode = TopStack->getDirectionNode(directions::NORTH); 
   nextNode->setVisited(); 
   nodesPtr.push(nextNode);
   nodes.push_back(*nextNode);  
}

else if(canTravel(TopStack->getDirectionNode(directions::WEST))){
   nextNode = TopStack->getDirectionNode(directions::WEST); 
   nextNode->setVisited(); 
   nodesPtr.push(nextNode);
   nodes.push_back(*nextNode);
}

else if(canTravel(TopStack->getDirectionNode(directions::SOUTH))){
   nextNode = TopStack->getDirectionNode(directions::SOUTH); 
   nextNode->setVisited(); 
   nodesPtr.push(nextNode);
   nodes.push_back(*nextNode);
}

else if(canTravel(TopStack->getDirectionNode(directions::EAST))){
   nextNode = TopStack->getDirectionNode(directions::EAST); 
   nextNode->setVisited(); 
   nodesPtr.push(nextNode);
   nodes.push_back(*nextNode);
}

else{
    nodesPtr.pop();
}
}
return nodes;
}

How does a custom compare function in std::map in C++ works?

I was trying to write some code for lexicographical sort and came across this sample code:

#include <cctype>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <vector>

using std::string;
using std::transform;
using std::map;
using std::cout;

struct Compare {
    bool operator() (const string& s0, const string& s1) const {

    cout << "in compare\n";
        // construct all lowercase versions of s0 and s1
        string str0(s0.length(),' ');
        string str1(s1.length(),' ');
        transform(s0.begin(), s0.end(), str0.begin(), tolower);
        transform(s1.begin(), s1.end(), str1.begin(), tolower);

        if  (!str0.empty() and !str1.empty() and str0.front()==str1.front()) {
            // do a standard lexicographic sort if the first character is the same
        cout << "s0=" << s0 << " s1=" << s1 << " s0 < s1=" << (s0 < s1)  << std::endl;
            return s0 < s1;
        } else {
        cout << "str0=" << str0 << " str1=" << str1 << " str0 < str1=" << (str0 < str1) << std::endl;
            // otherwise, do a case-insensitive lexicographic sort using the lowercased strings
            return str0 < str1;
        }
    }
};


typedef map<string, int, Compare> word_count;

int main(){
    word_count wc;
   auto words = { "t2 13 121 98", "r1 box ape bit", "b4 xi me nu", "br8 eat nim did", "f3 52 54 31" };

    for (auto word : words) {
        cout << "word=>" << word << '\n';
        wc[word]++;
    }

    for(auto elem : wc)
        cout << elem.first << '\n';

    return 0;
}

The code works pretty much how I want it to work. I am just trying to understand the compare function. On first insert no comparison is one (obviously). On 2nd insert the compare function is called three times. This is the part that I don't understand. The closest I have come to understand this is that it is due to the way map is implemented (red-black tree). One of the link that gave some explanation was a comment here.

Could someone please explain this in detail? Thanks.

returning lambda that captures reference [duplicate]

In Cpp primer 5th Ed. p 393

If the function returns a lambda, then - for the same reasons that a function must not return a reference to a local variable - that lambda must no contain reference captures.

#include <iostream>
using namespace std;

auto foo(ostream &os) {
    auto f = [&os]() -> std::ostream& { os << "Hello World !" << endl; return os;};
    f();
    return f;
}
void main() {
    foo(cout);
    auto f = foo(cout);
    system("pause");
    f();
}

This code compiles without warning in msvc 2019. It also appears to run fine. The captured os referes to std::cout which exists outside of foo's scope. Is f() Undefined behaviour ? If yes, is auto f = foo(cout); also undefined behaviour (that is, the returning and assigning of the lambda) ?

C++ program to find sum of N numbers using while loop

Im a newbie in C++, so when im trying to run this code the compiler throws an error

while_st_2.cpp:18:1: error: expected class-name at end of input ~ ^

Can u please tell me how i can fix this, what does the expected class name at the end of input mean?

`#include <iostream>
// program to sum the numbers from 1 to N, taking N as input
int main ()
{
        int  val=1, sum=0, N=0;
        std::cout << "Enter N " << std::endl;
        std::cin >> N ;
        //while loop to compute the sum of N natural numbers
        while(val <= N) {
                sum += val; // assigns sum + val to sum
                ++val; // add 1 to val
        }
        std::cout << "The sum of " <<  N << " natural numbers inclusive is " << sum << std::endl;
        return 0;
}  
`