Reputation: 330
int main(){
int n;
cin>>n;
char *str[40];
str=new char [10000][40]; //I don't know how to initialize this array
std::map<char*,int> system;
int i,j;
//solving Question 4C @ Codeforces
for(i=0;i<n;i++){
cin>>str[i];
}
for(i=0;i<n;i++){
int count=0;
for(std::map<char*,int>::iterator iter=system.begin();iter!=system.end();iter++){
if(strcmp(iter->first,str[i])==0){
count=++iter->second;
}
else if(strcmp(str[i],iter->first)>0){
break;
}
}
if(count==0){
system[str[i]]=1;
cout<<"OK"<<endl;
}
else{
char *strint;
strint=new char[5];
strint=convert(count);
strcat(str[i],strint);
cout<<str[i]<<endl;
}
}
}
Question: http://codeforces.com/problemset/problem/4/C
I am looking for a way that I could put the char array as an element of the map to help solving the scenario, however, I ended up with either screwing up the map.insert function when I declare str[n][40] as str, system as , (Could somebody please explain why map.insert(str[i],1) won't work in this case? It would be sweet to clarify the concepts) or in this case, fails to initialize the char*str[40] array.
I wonder what is the legit way to do this?
Upvotes: 2
Views: 2772
Reputation: 118350
char *str[40];
str=new char [10000][40]; //I don't know how to initialize this array
str
is an array. You can assign something to values in an array, but arrays themselves cannot be assigned to. You are probably trying to do:
char *str[40];
for (size_t i=0; i<40; ++i)
str[i]=new char [10000];
Still, in modern C++ one rarely needs to do new
and delete
in the first place; instead modern C++ code uses containers. Speaking of containers:
std::map<char*,int> system;
This is not going to lead to anything good. A std::map
literally compares key by their values. So:
char *foo1=new char[40];
strcpy(foo1, "foo");
system[foo1]=0;
char *foo2=new char[40];
strcpy(foo2, "foo");
auto iter=system.find(foo2);
Do you think that find()
here, will find this element? Of course not, because it's a different pointer value.
Although maps that use raw pointers as keys are valid C++, it's not very obvious how to use them correctly.
In conclusion, you should spend more time studying and learning how to use various containers. Here, std::vector
should be used instead of futzing around with new
and delete
. And std::string
should be used instead of char *
as the map key. You'll be surprisd to learn that the end result will be smaller and easier to read, and understand.
Upvotes: 4