【发布时间】:2015-03-22 19:29:25
【问题描述】:
我想检查一个字符串是否在一个将字符串向量作为值保存的映射的值中
typedef std::map<std::string, std::vector<string>> ClusterDescription;
std::map<std::string, std::vector<string>> clusterDescription;
std::vector<string> vec1 = {"11", "22", "33"};
std::vector<string> vec2 = {"44", "55"};
std::vector<string> vec3 = {};
std::string key1 = "1";
std::string key2 = "2";
std::string key3 = "3";
clusterDescription.insert(std::make_pair(key1, vec1));
clusterDescription.insert(std::make_pair(key2, vec2));
clusterDescription.insert(std::make_pair(key3, vec3));
std::string ID = "44";
for (ClusterDescription::iterator it = clusterDescription.begin(); it != clusterDescription.end(); ++it)
{
std::vector<std::string> clusterMembers = it->second;
if(std::find(clusterMembers.begin(), clusterMembers.end(), ID) != clusterMembers.end())
{
std::cout<< " I received an msg, from the wrong head "<< std::endl; //FIXME:
break;
}
else
{
std::cout<< " I have not been included in any cluster yet "<< std::endl; //FIXME:
std::cout<< " sending joinmode msg "<< std::endl;
break;
}
}
这里的代码适用于以下值:11、22、33。但在其他情况下它失败了。我错过了什么?
【问题讨论】:
-
您在第一次迭代后退出了 for 循环,因此只分析了地图的第一个元素。
-
@cross:你为什么不期待呢?这是您的代码所做的,我们所能看到的只是您的代码,而不是您想要的代码。因此,无法通过阅读来判断您的意图。
标签: c++ c++11 stdvector stdstring stdmap