开发者

How to use map::end from map::find in C++

开发者 https://www.devze.com 2023-01-31 08:44 出处:网络
I want to use the C++ map function, map::find, to determine if a specific string is within a map. I know that find returns map::end but I am not sure on how to use it. So if the same string exists in

I want to use the C++ map function, map::find, to determine if a specific string is within a map. I know that find returns map::end but I am not sure on how to use it. So if the same string exists in both names_ and info_, I want it to print that string to the screen.

In my header:

std::vector<std::string>names_;
std::map<std::string, unsigned int> info_;

In the .cpp (THIS CODE IS WRONG):

for(unsigned int i=0;i<names_.size();i++){
    std::map<std::string, unsigned int>::iterator it;
    it = info_.find(names_[i]);
    if info_.find(names_[i]开发者_开发问答) != info_.end()
        std::cout << names_[i] << std::endl; 
}

What I am doing wrong in the .cpp code snipet? I know it is something with iterators.


It should be:

for(unsigned int i=0;i<names_.size();i++){
    if (info_.find(names_[i]) != info_.end())
        std::cout << names_[i] << std::endl; 
}


Apart from anything else:

if info_.find(names_[i]) != info_.end()

should be:

if ( info_.find(names_[i]) != info_.end() )

In C++ (and C) conditions tested by ifs and whiles must be enclosed in parens.


After the obvious fix of enclosing the if expression if brackets mentioned in the other answers, the code works.

#include <iostream>
#include <map>
#include <vector>

int main() {
  std::vector<std::string>names_;
  std::map<std::string, unsigned int> info_;
  names_.push_back("a");
  names_.push_back("b");
  names_.push_back("c");
  info_["a"] = 123;
  info_["c"] = 123;
  info_["d"] = 456;
  for(unsigned int i=0;i<names_.size();i++){
      std::map<std::string, unsigned int>::iterator it;
      if (info_.find(names_[i]) != info_.end())
          std::cout << names_[i] << std::endl;
  }
}

Output:

a
c

Isn't that what you asked for?

0

精彩评论

暂无评论...
验证码 换一张
取 消