Getting compilation error using Map in C++ STL? - c++

Using MAP in the below program generate some compiler errors . Not getting what they mean.
#include <iostream>
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
char maze [61][61], q;
int n , m , i , j , x , y;
map < char , char > left ;
map < char , char > right ;
char orient ;
int main(){
left ['N'] = 'W' ;
left ['E'] = 'S';
left['S'] = 'E';
left['W'] = 'N';
right['N'] = 'E';
right['E'] = 'S';
right['S'] = 'W';
right['W'] = 'N';
scanf( "%d %d" , &n , &m) ;
for ( i = 0 ; i < n ; i++)
scanf("%s", maze[i]);
scanf("%d %d" , &x ,&y);
orient = 'N' ;
x = x - 1 ; y = y - 1 ;
return 0 ;
}
Getting compiltaion errors like :
prog.cpp: In function ‘int main()’:
prog.cpp:15:1: error: reference to ‘left’ is ambiguous
left['N'] = 'W';
prog.cpp:9:21: note: candidates are: std::map<char, char> left
map < char , char > left ;
In file included from /usr/include/c++/4.8/ios:42:0,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from prog.cpp:1: /usr/include/c++/4.8/bits/ios_base.h:916:3:
note: std::ios_base& std::left(std::ios_base&)
left(ios_base& __base)
What is the mistake can you please point out and what does it mean ??
For more details :
http://ideone.com/CqBiS0

Functions with name left and right already exists in ios header. They are IO manipulators.
So, this is why you should use explicit namespace resolution instead of just writing using namespace std. And, of course, you should avoid using global variables.

In the iostream header, there's a symbol named left. Luckily, it's under the std namespace. Unfortunately, you are using namespace std, so both your map and the symbol from the iostream header are now referenced by "left" - which creates this ambiguity.
To resolve this, either:
1. Rename your map, or
2. Remove the "using namespace std" statement, and use the prefix std:: where it's required.

Here's your culprit:
using namespace std;
This drags the standard library's std::left into the global namespace, where it conflicts with your own left in the same namespace. Get rid of it, and add std:: to any names from the standard library you're using. Dumping the entirety of a large namespace into the global namespace is a recipe for name conflicts like this one.
Also, you probably don't want to use global variables; they are fraught with more perils than just namespace pollution. Moving the variables inside main will also fix this particular error. I suggest you do both, and make both habits.

Related

Change alias after declaration

I'm quite new in C++ programming. So I tried to define an alias and change it later, but I'm not sure if it is possible and (if it's possible) how to do it:
using Alpha = Alphabet::DNA
//I don' need the Alpha here, but I have to define it before the scope,
//because afaik if I define it inside the scope,
//it'll be lost outside the scope
for(int i = 0 ; i < argc ; ++i){
if(argv[i] == "-d"){
Alpha = Alphabet::DNA;
}else if(argv[i] == "-r"){
Alpha = Alphabet::RNA;
}
}
Sequence<Alpha> seq;
I need to do this because I only know from the arguments which Alpha I have to use. Alphabet is already a namespace and DNA and RNA are "subtypes" of it.
Sequence is just a template class representing the sequence of molecules fro DNA or RNA.
Thanks for your help
The answer is NO.
For every type (alias or not), cpp compiler have to determine its "real type" in compile time.
For instance,
constexpr int N = 3;
using FixedBitset = std::bitset<N>;
is valid. While
int N = 3;
using FixedBitset = std::bitset<N>;
is definitely invalid because the value N cannot be checked out in compile time.

why my code is giving undeclared variable error?

include "stdafx.h"
#include <vector>
#include <iostream>
std::vector<int> biggest;
std::vector<int>vector1;
std::vector<int>vector2;
int main(){
biggest = [vector2[0],0]; //wrong initialization
for (int apply = 0; apply < (vector2.size()); apply++) {
if (biggest[0] < vector2[apply + 1]) {
biggest[0] = vector2[apply + 1];
biggest[1] = apply + 1;
}
}
Error C2065 'apply': undeclared identifier.why this error is occurring as i have already defined apply variable in for loop. error should be in initialization of biggest(vector).why wrong compiler code?
even intellisense is not giving me error is it a visual studio bug?
apply is in scope in the for loop body, so be assured, the error is not there. But you are aware that apply is out of scope after the loop body?
I'm only answering this because your use of
vector2.size() - 1
will give you hell if vector2 is empty, as the above will wrap around to a large unsigned value and your program will fail spectacularly! Use
for (int apply=0; apply + 1 < vector2.size(); apply++) {
instead.

incompatible implicit declaration of built-in function 'malloc'

My program is
#include <iostream>
char * grabNumber ( char * begin )
{
// Interpret *begin as the start of a double and add the characters to a
// string retstr
char * begincpy = begin;
int foundDot = 0;
while ((*begin >= '0' && *begin <= '9') || *begin == '.')
{
if (*begin == '.')
{
if (foundDot == 0) foundDot = 1;
else break;
}
++begin;
}
long n = begin - begincpy; // # of characters parsed
char * retstr = malloc(sizeof(char) * (n + 1)); // string to be returned
for (long k = 0; k < n; ++k) retstr[k] = *begincpy++;
retstr[n] = '\0';
return retstr;
}
int main()
{
char str [] = "abc3.14def";
std::cout << grabNumber(str+3); // should print "3.14"
return 0;
}
and the errors I'm getting are
Line 20: warning: incompatible implicit declaration of built-in
function 'malloc' Line 21: error: 'for' loop initial declaration used
outside C99 mode
corresponding to the 2 lines
char * retstr = malloc(sizeof(char) * (n + 1)); // string to be returned
for (long k = 0; k < n; ++k) retstr[k] = *begincpy++;
See: http://codepad.org/c2tNGFEo
Also, is there a way that I can cut down on the redundancy of my algorithm, because it's checking for a . twice in each iteration of the while loop, and yet I can't think of a cleaner way to handle the fact that I need to stop the loop if we've run into a second .
I'm guessing you are trying to write C++ as you have included iostream and used std::cout. However the error message shows you are using a C compiler. I also guess that you wrote gcc myprogram.c. To get C++ compilation you either need to write g++ instead of gcc, or rename your file to have a .cc extension. (Preferably both).
To use malloc you need #include <cstdlib>.
Also you may need using namespace std; or using std::malloc; after that; and you will need to cast the value returned by malloc because C++ does not implicitly convert from void * to other pointer types.
However malloc is rarely used in C++ as it does not initialize non-trivial objects properly. Consider changing this code to:
char * retstr = new char[n+1];
then you won't need any extra includes.
But this is still a weak design as you are now relying on the caller to free the memory. In fact your main function has a memory leak as it does not free the memory.
In C++ it is better style to have memory managed by a container class that knows about memory management; so the programmer can't make any mistakes. (Incase you are wondering, this usually doesn't introduce any inefficiency and may even speed things up).
A much better approach would be to #include <string>, make the function return std::string, and change the last five lines of your function to:
return { begincpy, begin };
or if using a pre-C++11 compiler,
return std::string(begincpy, begin);
Let's start by observing that you are not writing C, you are writing C++. You should fix your compilation/project settings so you compile your files using the C++ compiler instead of the C compiler. This will fix the compilation error about the for loop also, as that is not valid in C before C-99.
Secondly, the first warning is actually due to a missing include. In C you would #include <stdlib.h> in C++ you'd #include <cstdlib> to get the definitions from the C standard library.

Undeclared Identifier with all the right includes

Everytime I try to build the program I get this error:
error C2065: 'DepositoFresco' : undeclared identifier
This happens with every instance I create of DepositoFresco, DepositoNormal and Deposito. DepositoNormal and DepositoFresco are subclasses of Deposito (virtual class). I have all the right includes so I don't know what's causing this.
The error occurs in the class 'Armazem' where I instantiate several of these to insert in vectors and such. Here's the code:
Armazem::Armazem(int nF, int nN, int nPF, int nPN, int distMaxi, int distMini) : depositos(), distancia(), graphStlPath <Deposito*, int>() {
distMax = distMaxi;
distMin = distMini;
for (int i = 0; i < nF; i++) {
DepositoFresco* df = new DepositoFresco(random(1, 20), (float)random(1000, 10000), nPF);
depositos[i] = df;
}
for (int j = nF; j < nF + nN; j++) {
DepositoNormal* dn = new DepositoNormal(random(1, 20), (float)random(1000, 10000), nPN);
depositos[j] = dn;
}
preencherMatriz();
}
Also, Armazem is a subclass to another template class called GraphStlPath but I don't think the problem is here.
EDIT: Here are the includes:include "Deposito.h"
include "DepositoFresco.h"
include "DepositoNormal.h"
include "graphStlPath.h"
include <vector>
include <map>
include <stdlib.h>
include <stdio.h>
include <time.h>
include <typeinfo>
include <iostream>
include <fstream>
include <string>
Any help finding the problem is really apreciated.
My psychic debugging powers tell me that you have a cycle in your includes, and header guards or #pragma once are kicking in, making code disappear for the compiler.
That, or you are not respecting namespaces. But the first one is more likely.

Runtime error in C++ with eigen library, any suggestions?

I am new to C++ and eigen library. I am trying to code some simple stuff, but do not know where I am going wrong. Here is my code:
#include<iostream>
#include<Eigen\Dense>
#include<cmath>
#include<fstream>
using namespace std;
using namespace Eigen;
int main (int argc, char* argv[])
{
int n = 200;
Matrix<double, Dynamic,1> u_n;
u_n.setZero(n,1);
Matrix<double, Dynamic,1> u_n_minus_one;
u_n_minus_one.setZero(n,1);
Matrix<double, Dynamic,1> u_n_plus_one;
u_n_plus_one.setZero(n,1);
std::ofstream fileWriter ("Values.txt");
assert(fileWriter.is_open());
float r=2;
float F=100;
for (int t=0;t<=5;t=t+1)
{
u_n_plus_one (0,0) =0;
//source of error
u_n_plus_one.block(1,0,n-1,0) = pow(r,2)*( u_n.block(1,0,n-2,0)+ u_n.block(3,0,n,0)) + 2*(1-pow(r,2))*u_n.block(1,0,n-1,0)-u_n_minus_one.block(1,0,n-1,0);
//source of error
u_n_plus_one (floor(n/2),0)=F;
u_n_plus_one (n-1,0) =0 ; //corrected from (n,0) to (n-1,0)
u_n_minus_one = u_n ;
u_n = u_n_plus_one ;
//writing values to file
if (remainder(t, 10) == 0)
{
fileWriter<<u_n.transpose()<<std::endl;
}
}
fileWriter.close();
}
I am trying to declare a few matrices (though they are vectors). Then I am doing operations on blocks of matrices, and finally writing the results to the file. I did not get any compile time error, but program crashes during run.
I tried debugging the code and the error seem to lie within //source of error statements. Can someone help me with this?
As the page on Block operations says, matrix.block(i,j,p,q) denotes the block with p rows and q columns starting at the (i,j) entry. I think that u_n.block(3,0,n,0) in the program is supposed to refer to the block starting at the (3,0) entry and ending at the (n,0) entry, but in fact it refers to the block starting at the (3,0) entry and of size (n,0). The block starting at the (3,0) entry and ending at the (n,0) entry is denoted by u_n.block(3,0,n-2,1) or u_n.segment(3,n-2) or u_n.tail(n-2); see the link mentioned at the start.