C++STL映射键和值工作不正常
C++ STL map keys and values not working properly
我开发了一个程序,在这个程序中,我接受来自系统本身的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";
}
}
相关文章:
- 不确定要在我的main中放入什么才能使我的代码正常工作
- C++中的memset函数工作不正常
- 为什么 HeapFree() 不能正常工作?
- 如果不在窗口 10 中声明名为 openCV 的 openCV namedWindow,QT 图像显示将无法正常工作
- 通用线程池类工作不正常
- 循环仅对第一行正常工作.其他行不受 for 的影响
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- C++自定义删除运算符不能正常工作?
- 为什么使用 exec() 重新启动程序不能正常工作?
- C++:返回本地对象,但不能正常工作
- 名为DLL的C++windows服务程序工作不正常
- C++-循环中的If语句工作不正常
- 为什么带lcov的codecov在Travis上不能正常工作,而在我当地的Linux Mint上却不能正常工作
- While循环和if/else语句工作不正常
- 为什么sizeof函数在这里不能正常工作
- 异步操作的 Asio 处理程序在其同步对应项正常工作时不会调用
- C++:最大数组值函数工作不正常
- 图像上的按钮不正常工作在QT
- 透明SDL2游戏(WIN32色键不正常工作)
- Qt 5.3 QSystemTrayIcon不正常工作[Linux]