C++STL映射键和值工作不正常

C++ STL map keys and values not working properly

本文关键字:不正常 工作 键和值 映射 C++STL      更新时间:2023-10-16

我开发了一个程序,在这个程序中,我接受来自系统本身的stl映射的键和值。

我想完成以下任务。我的密钥从0到1000不等。在向键插入值之前,我必须检查映射中是否有相同的键。如果是,我必须将key增加1,并为该key赋值。我正在按以下方式努力。但是我没有成功。

map<int, Values> items;
Values connection (inet_ntoa(Clientaddr.sin_addr),ntohs(Clientaddr.sin_port),inet_ntoa(Servaddr.sin_addr),ntohs(Servaddr.sin_port));
for(unsigned int key=0;key<=1000;key++)
{
map<int,Values>::const_iterator itemsIterator=items.find(key);
if(itemsIterator==items.end())
{
items.insert(pair<int, Values> (key, connection));
}
else
{
cout<<"already exist";
key++;
}
}

现在您正在将连接与所有未使用的密钥配对。你也在做一些我不太明白的事情,如果key存在于地图中,你会在哪里加倍递增。这应该可以解决这两个问题:

map<int, Values> items;
Values connection (inet_ntoa(Clientaddr.sin_addr),ntohs(Clientaddr.sin_port),inet_ntoa(Servaddr.sin_addr),ntohs(Servaddr.sin_port));
for(unsigned int key=0;key<=1000;key++)
{
map<int,Values>::const_iterator itemsIterator=items.find(key); //try to find the key in the map
if(itemsIterator==items.end()) //if the key doesn't currently exist in the map
{
items.insert(pair<int, Values> (key, connection)); //add it to the map with the connection
break; //and exit the loop
}
else //the key already exists, try the next one in the next pass of the for loop
{
cout<<"already exist";
}
}

我在您提供的代码片段中看到了四个缺陷。

首先,您将map定义为具有key_typeint,而在循环中使用密钥类型unsigned int。虽然这不是一个错误,但会使代码变得不那么清晰。因此,您应该决定key_type是int还是unsigned int。在循环中,最好指定key_type,而不是显式指定某些积分类型。

所以我会把循环的控制语句写成

for ( std::map<int, Values>::key_type key = 0; key <= 1000; key++ )

另外,如果关键帧已经存在于贴图中,则在循环中增加两次关键帧。

for(unsigned int key=0;key<=1000;key++)
{
//...
else
{
cout<<"already exist";
key++;
}
}

它在控制语句本身和else的复合语句中增加。

第三个缺陷是您没有在语句中调用函数连接

items.insert(pair<int, Values> (key, connection));

在该语句中,表达式connection具有指向函数的指针类型。我认为你必须调用函数,才能得到由该函数计算的值。

第四个缺陷是语句的语法错误

Values connection (inet_ntoa(Clientaddr.sin_addr),ntohs(Clientaddr.sin_port),inet_ntoa(Servaddr.sin_addr),ntohs(Servaddr.sin_port));

目前尚不清楚这是一个函数调用还是一个函数声明。

所以我会将代码片段重写为

std::map<int, Values> items;
for( std::map<int, Values>::key_type key = 0; key <= 1000; key++ )
{
std::map<int, Values>::const_iterator itemsIterator = items.find( key );
if( itemsIterator == items.end() )
{
items.insert( pair<int, Values>( key,  connection( /*arguments of the function*/ ) ) );
}
else
{
cout << key << " already exists";
}
}