c++ - 恒定的正确性

标签 c++ vector iterator constants const-iterator

在 printMessage 中,如果您使用索引访问常量类的 vector ,它可以正常工作,但不能使用迭代器(*itr)。如果迭代器被声明为constant_iterator,那么它就可以正常工作。

为什么?

在这两种情况下,我都在读取数据而不是修改 vector 。有人可以透露一些信息吗?

 #include <iostream> 
 #include <vector>
 #include <sstream>

 //Set this define to enable the block to compile.
 #define WILL_WORK 1
 #define WILL_NOT_WORK !WILL_WORK

 class TestMessage
 {
 public:
  TestMessage(){};
  typedef std::vector<int>  TestVec;
  typedef std::vector<int>::iterator TestItr;
  //The const iterator will work
  //typedef std::vector<uint32_t>::const_iterator TestItr;
  typedef std::vector<int>::size_type TestSize;
  TestVec m_testVector;
 };


 void printMessage(const TestMessage & tmessage)
 {
  std::ostringstream asciiMessage;

  asciiMessage << tmessage.m_testVector.size() << ",";

 #if WILL_NOT_WORK

 //This will not work
 // MS Visual Studio
 // error C2440: 'initializing' : cannot convert from
 // 'std::_Vector_const_iterator<_Ty,_Alloc>' to
 //     'std::_Vector_iterator<_Ty,_Alloc>'
 // GCC 
 // error: conversion from
 // '__gnu_cxx::__normal_iterator<const int*,
 //                               std::vector<int, std::allocator<int> > >'
 // to non-scalar type
 // '__gnu_cxx::__normal_iterator<int*,
 //                               std::vector<int, std::allocator<int> > >'
 // requested

  for (TestMessage::TestItr itr = tmessage.m_testVector.begin();
       itr != tmessage.m_testVector.end();
       ++itr)
  {
   asciiMessage << *itr;
  }

 #endif 

 #if WILL_WORK

  // This will work
  for(TestMessage::TestSize index = 0;
      index < tmessage.m_testVector.size();
      ++index)
  {
   asciiMessage << tmessage.m_testVector[index] << ",";
  }

 #endif

  asciiMessage << std::endl;

  std::cout << asciiMessage.str();
 }

 int main()
 {
  TestMessage message;
  message.m_testVector.push_back(10);
  message.m_testVector.push_back(20);
  message.m_testVector.push_back(30);
  message.m_testVector.push_back(40);
  printMessage(message);
  return 0;
 }

最佳答案

有 2 个不同的 [] 运算符。一位常量,一位非常量。

const-[] 运算符返回 const 引用,因此索引处的值无法更改。

普通迭代器是非常量的,这意味着编译器可能认为您可以更改 vector 。毕竟,您可以将迭代器传递给函数,然后编译器无法保证被调用的函数不会更改迭代器/vector 的内容。

因此,还有一个const_iterator。 const_iterator 不能用于更改 vector 中的值。这可以由编译器直接检查。 如果将 const_iterator 传递给函数,编译器只能假设被调用函数的行为应如此,即不更改 const_iterator 指向的位置。

关于c++ - 恒定的正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2247098/

相关文章:

C++闭包创建

c++ - 流类的基类

c++ - 迭代器删除(迭代器在前,迭代器在后)在 Visual C++ 2010 Express 下不起作用

c++ - C++ 集合中的迭代器

c++ - 如何检查 C++ STL vector 中存在的值并将函数应用于 vector 的每个元素?

c++ - 比 C++ 中的 OpenCV 库更快地获取总帧数和 FPS

c++ - 错误 C2664 : 'int wsprintfW(LPWSTR,LPCWSTR,...)' : cannot convert argument 1 from 'char [15]' to 'LPWSTR'

apache-flex - 将绘制的flash/flex UIComponent导出到基于矢量的打印文件的方法

c++ - string[] 还是 vector<string>?

java - 公开内部集合项时应该使用 Iterator 还是 Iterable?