c++ - std::set 使用 char * 类型查找行为

标签 c++ c++11 visual-c++ stdset

我有以下代码行:

const char *values[] = { "I", "We", "You", "We"};
std::set<const char*> setValues;

for( int i = 0; i < 3; i++ ) {

    const char *val = values[i];
    std::set<const char*>::iterator it = setValues.find( val );

    if( it == setValues.end() ) {
        setValues.insert( val );
    }
    else {
        cout << "Existing value" << endl;
    }
}

有了这个,我试图在 set 中插入非重复值,但不知何故代码没有点击打印现有元素,并且插入了重复值。

这里有什么问题?

最佳答案

您应该为 const char* 定义 less 谓词并传递到 set 模板以使 set 对象与指针一起正常工作:

  struct cstrless {
    bool operator()(const char* a, const char* b) {
      return strcmp(a, b) < 0;
    }
  };
  std::set<const char*, cstrless> setValues;

关于c++ - std::set 使用 char * 类型查找行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38655928/

相关文章:

c++ - CodeBlocks 构建不正确

c++ - 虚拟类的非虚拟版本

c++ - 使用显式构造函数返回不可复制的不可移动对象

c++ - 如何在容器项目的字段上创建迭代器?

c++ - qmobilityglobal.h : No such file or directory

c++ - boost::asio::ip::tcp::resolver::iterator 是做什么的?

android - 加载 .so 文件在某些​​ Android 设备上崩溃

string - 将 System::String^ 转换为 cv::String

c++ - 尝试链接 boost::filesystem 以调试 MSVC11 项目时出现链接器错误

c++ - 毫秒 mpi 错误 : unable to allocate launching block