In g++ , element access operator for const std::vector&lt;> is defined as follows: (/usr/include/c++/7.1.1/bits/stl_vector.h)  /**    *  @brief  Subscript access to the data contained in the %vector.    *  @param __n The index of the element for which data should be    *  accessed.    *  @return  Read-only (constant) reference to data.    *    *  This operator allows for easy, array-style, data access.    *  Note that data access with this operator is unchecked and    *  out_of_range lookups are not defined. (For checked lookups    *  see at().)    */   const_reference   operator[](size_type __n) const _GLIBCXX_NOEXCEPT   { __glibcxx_requires_subscript(__n); return *(this-&gt;_M_impl._M_start + __n);   }   But the following code compiles with no problem using g++ -c const-vector.cpp -Wall -pedantic  #include &lt;vector&gt;  void sum(const std::vector&lt;int&gt;&amp; data){   int *ptr;   ptr = (int*) &amp;data[0];   if (data.size()&gt;2)      for (unsigned int i=1;i&lt;data.size();i++)        ptr[0]+=ptr[i]; return;}   So I'm changing the contents of the vector passed by const reference.  According to  , operator[] is overloaded:  reference       operator[]( size_type pos ); const_reference operator[]( size_type pos ) const;   In which case compiler will take the second overload?
4671
What are the proper uses of:   static_cast dynamic_cast const_cast reinterpret_cast C-style cast (type)value Function-style cast type(value)   How does one decide which to use in which specific cases?
94076
How can I represent the  (i.e, vec(A))? I am talking about this simple operator:
87286
Just reading about the cross product. It says here: $$A\times B= \{(x,y)|x\in A, y\in B\}$$ Does this mean that the result of $A\times B$ is a new set of ordered pairs? If so, what happens if both A and B share a common member? What would the result be, since an ordered pair cannot include duplicates?    Edit: Quoting the free textbook I'm looking at online,     If we are given that A is a set and no other information about A, then there is no   ordering to the elements of A. Thus, we cannot speak of “the second element of the set A”   unless we have specified an ordering of the elements of A. If we wish to regard A as ordered in some way, then we specify this fact explicitly: “The elements of A are ordered a, b, c,” or “A = (a, b, c).” The latter notation replaces the braces with parentheses and designates that A is ordered, left to right, as indicated. We call this an ordered set. An ordered set is also called a linear order. Various other names are also used: list, vector, string, word — all with no repeated elements. Of course, you’ve seen repeated elements in vectors, for example the point in the plane at the coordinates (1,1). That’s fine, it’s just not an ordered set.       Why is it okay to specify a set S = {a, b, c, a} where the element a has been repeated,   but it is not okay to have repeated elements in an ordering of S?   When we say S  =   {a, b, c, a}, we know that S contains just the three elements a, b and c.  If we were to talk   about the ordered set (a, b, c, a) it would not make sense because it would say that the   element a is in two places at once: the first position and the last position.
122587
I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.  The custom list defines an iterator;  class Iterator: public std::iterator&lt;std::forward_iterator_tag, T&gt; {     // ... }  Iterator begin() {     return (Iterator(root)); }  Iterator end() {     return (Iterator(NULL)); }   with the appropriate operators overloaded.   Ideally, I would like to do this;  class Foo { public:     Foo() {         std::list&lt;int&gt; x;         std::vector&lt;int&gt; y;         custom_list&lt;int&gt; z;          iter = x.begin(); // OR         iter = y.begin(); // OR         iter = z.begin();          // ...     }; private:     std::iterator&lt;int&gt; iter; };   But obviously these are all iterators of different types. I can assume all the containers are of the same type however.  Is there an elegant way to solve this problem?
27126
I think I've declared a Vector with an object correctly.  But, I don't know how to access it's members when looping with Iterator.  In my code, the line --->>  cout &lt;&lt; " " &lt;&lt; *Iter;  How do I print the contents of the members?  Like *Iter.m_PackLine ???  Not sure if I used the correct terminology, but appreciate the help!  Thanks  class CFileInfo {   public:       std::string m_PackLine;       std::string m_FileDateTime;       int m_NumDownloads; };  void main() {   CFileInfo packInfo;    vector&lt;CFileInfo, CFileInfo&amp;&gt; unsortedFiles;   vector&lt;CFileInfo, CFileInfo&amp;&gt;::iterator Iter;    packInfo.m_PackLine = "Sample Line 1";   packInfo.m_FileDateTime = "06/22/2008 04:34";   packInfo.m_NumDownloads = 0;   unsortedFiles.push_back(packInfo);    packInfo.m_PackLine = "Sample Line 2";   packInfo.m_FileDateTime = "12/05/2007 14:54";   packInfo.m_NumDownloads = 1;   unsortedFiles.push_back(packInfo);   for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ )  {     cout &lt;&lt; " " &lt;&lt; *Iter; // !!! THIS IS WHERE I GET STUMPED     // How do I output values of the object members?   } }  // end main
5014
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.   Basically I have three questions:   Why use pointers over normal variables? When and where should I use pointers? How do you use pointers with arrays?
81177
What is the difference between a const_iterator and an iterator and where would you use one over the other?
99037
I see this from time to time and want to know what it is. I did try google, but its filtering out the characters from the search. I have a few books that don't reference it either.   FWIW, I remember in pascal that is was the assignment operator.   Can anybody point me to the MSDN or similar page?
31381
The following code says that passing the map as const into the operator[] method discards qualifiers: #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;string&gt;  using namespace std;  class MapWrapper { public:     const int &amp;get_value(const int &amp;key) const {         return _map[key];     }  private:     map&lt;int, int&gt; _map; };  int main() {     MapWrapper mw;     cout &lt;&lt; mw.get_value(42) &lt;&lt; endl;     return 0; }  Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const? MapWrapper.cpp:10: error: passing const std::map&lt;int, int, std::less&lt;int&gt;, std::allocator&lt;std::pair&lt;const int, int&gt; &gt; &gt; as this argument of  _Tp&amp; std::map&lt;_Key, _Tp, _Compare, _Alloc&gt;::operator[](const _Key&amp;)  [with _Key = int, _Tp = int, _Compare = std::less&lt;int&gt;,  _Alloc = std::allocator&lt;std::pair&lt;const int, int&gt; &gt;] discards qualifiers
113958
I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use std::vector instead of std::map even if you were to use the container for lookups only and not iterating.  What is the real reason behind this?  Obviously the lookup performance of std::map cannot be worse than std::vector (although it may differ in nanoseconds/microseconds) so does it have something to do with memory usage?  Does std::vector fare any better/worse than std::map in fragmenting the virtual address space?  I am using the STL library that comes along with Visual Studio (i.e. Microsoft's implementation).  Does that make any difference compared to other implementations?
46741
In some code I've inherited, I see frequent use of size_t with the std namespace qualifier.  For example:  std::size_t n = sizeof( long );   It compiles and runs fine, of course.  But it seems like bad practice to me (perhaps carried over from C?).  Isn't it true that size_t is built into C++ and therefore in the global namespace?  Is a header file include needed to use size_t in C++?  Another way to ask this question is, would the following program (with no includes) be expected to compile on all C++ compilers?  size_t foo() {     return sizeof( long ); }
3552
According to the documentation of the == operator in ,      For predefined value types, the   equality operator (==) returns true if   the values of its operands are equal,   false otherwise. For reference types   other than string, == returns true if   its two operands refer to the same   object. For the string type, ==   compares the values of the strings.   User-defined value types can overload   the == operator (see operator). So can   user-defined reference types, although   by default == behaves as described   above for both predefined and   user-defined reference types.   So why does this code snippet fail to compile?  bool Compare&lt;T&gt;(T x, T y) { return x == y; }   I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types?  Edit: Thanks, everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct.  But, in case I'm using a reference type, would the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?  Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test&lt;B&gt;(new B(), new B()) is called:  class A { public static bool operator==(A x, A y) { return true; } } class B : A { public static bool operator==(B x, B y) { return false; } } class Test { void test&lt;T&gt;(T a, T b) where T : A { Console.WriteLine(a == b); } }
106919
I need to call a const function from a non-const object. See example  struct IProcess {    virtual bool doSomeWork() const = 0L; }; class Foo : public IProcess {       virtual bool doSomeWork() const {     ...   } };  class Bar { public:    const IProcess&amp; getProcess() const {return ...;}    IProcess&amp; getProcess() {return ...;}     void doOtherWork {     getProcess().doSomeWork();           } };   Calling   getProcess().doSomeWork();   will always results in a call to  IProcess&amp; getProcess()   Is there another way to call  const IProcess&amp; getProcess() const    from a non constant member function? I have so far used  const_cast&lt;const Bar*&gt;(this)-&gt;getProcess().doSomeWork();   which does the trick but seems overly complicated.    Edit: I should mention that code is being refactored and eventually only one function will remain.  const IProcess&amp; getProcess() const    However, currently there is a side effect and the const call may return a different instance of IProcess some of the time.  Please keep on topic.
54600
I am trying to open a spectral file and move bands of data from GDAL to OpenCV's Mat data structures. As of now I am just trying to make sure that I can correctly access each band using GDAL and pull the pixel data.   So I want to explain what I think the following code is doing and if I am wrong(must be) then please correct me. It opens the file and loads the dataset. Then I get raster band 1 assigned to currentBand. The float pointer is then made to point at enough memory for one line of pixel data. RasterIO gets this data and places it in the newly allocated space. I then traverse the array printing the value that has been placed in each element.  (Code in c++)  GDALDataset  *dataset; GDALRasterBand *currentBand; int blockXSize, blockYSize; GDALAllRegister(); dataset = (GDALDataset *) GDALOpen( specImag-&gt;filename.c_str(), GA_ReadOnly );  currentBand = dataset-&gt;GetRasterBand(1); currentBand-&gt;GetBlockSize(&amp;blockXSize, &amp;blockYSize);  float *fScanline; fScanline = (float *) CPLMalloc(sizeof(float)*specImag-&gt;widthx);  currentBand-&gt;RasterIO( GF_Read, 0, 0, specImag-&gt;widthx, 1,                           fScanline, specImag-&gt;widthx, 1, GDT_Float32, 0, 0 );   for(int i=0; i&lt;specImag-&gt;widthx; i++){         std::cout &lt;&lt; "Data Point ";         printf("%d", i);         std::cout &lt;&lt; " is: ";         printf("%d", fScanline[i]);         std::cout &lt;&lt; std::endl;     }   (the code is not complete and will not run as is)  When I run the code I get the same number (ex. 421076 or 4210432) for every element in the array. If I wait a little bit and run the program again I get a different number than the prevous run but still the same in each element.   What am i missing when it comes to accessing the pixel/data in each band?
43864
The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc &amp; g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):  char **a; const char** b = a;   I can understand and accept this. The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness ().  char **a; const char* const* b = a;   However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast?  To clarify: 1) Why does this generate a warning in C?  It should be entirely const-safe, and the C++ compiler seems to recognize it as such. 2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function:  void f(const char* const* in) {   // Only reads the data from in, does not write to it }   And I wanted to invoke it on a char**, what would be the correct type for the parameter?
35378
For example:  int a = 12; cout &lt;&lt; typeof(a) &lt;&lt; endl;   Expected output:  int
36521
I want to examine the contents of a std::vector in GDB, how do I do it?  Let's say it's a std::vector&lt;int&gt; for the sake of simplicity.