Please don’t confuse with the title as it was already asked by someone but for a different context
The below code in Visual C++ Compiler (VS2008) does not get compiled, instead it throws this exception:
std::ifstream input (fileName);
while (input) {
string s;
input >> s;
std::cout << s << std::endl;
};
But this code compiles fine in cygwin g++. Any thoughts?
tmlen
8,1744 gold badges31 silver badges83 bronze badges
asked Oct 27, 2009 at 14:49
0
Have you included all of the following headers?
<fstream>
<istream>
<iostream>
<string>
My guess is you forgot <string>
.
On a side note: That should be std::cout
and std::endl
.
answered Oct 27, 2009 at 15:07
sbisbi
217k45 gold badges254 silver badges439 bronze badges
12
Adding to @sbi answer, in my case the difference was including <string>
instead of <string.h>
(under VS 2017).
See the following answer: similar case answer
answered Mar 9, 2018 at 11:35
Guy AvrahamGuy Avraham
3,3723 gold badges40 silver badges49 bronze badges
In addition to what others said. The following code was necessary in my application to compile succesfully.
std::cout << s.c_str() << std::endl;
Another work-around to this is go to project properties -> General -> Character Set and choose «Ues Multi-Byte Character Set» (You won’t need to use c_str() to output the string)
There’s disadvantages to using MBCS so if you plan to localize your software, I’d advize against this.
answered Oct 24, 2018 at 16:10
Nick DelbarNick Delbar
1012 silver badges9 bronze badges
include <string>
Try including string header file along with <iostream>
file.
It will work in some compilers even without the <string>
because settings for different compilers are different and it is the compiler that is responsible for reading the preprocessor files that start with ‘#’ symbol to generate a obj file.
answered Aug 30, 2018 at 16:04
2
The problem occurs in Visual Studio 2005 but works in Vc++6.0
rx_fastset.h
struct SortedAppender
{
typedef Std:: output_iterator_tag iterator_category;
typedef BASE value_type;
typedef ptrdiff_t difference_type;
typedef BASE* pointer;
typedef BASE& reference;
sortedAppender(FastSet& fastSet): m_fastSet(fastSet) {}
sortedAppender& operator=(value_type v) { m_fastSet.sortedAppend(v); return *this;}
sortedAppender& operator*() { return *this; }
sortedAppender& operator++() { return *this; }
sortedAppender& operator++(int) { return *this; }
FastSet& m_fastSet;
};
rx_vist.cpp
inline
void SetUnion(const NodeIdSet& leftSet, const NodeIdSet& rightSet, NodeIdSet& unionSet)
{
assert(unionSet.empty());
std:: set_union(leftSet.begin(), leftSet.end(),
rightSet.begin(), rightSet.end(),
NodeIdSet:: sortedAppender(unionSet));
}
I am getting the following errors..
rx_vist.cpp
c:program filesmicrosoft visual studio 8vcincludealgorithm(3815) : error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘RX:: FastSet<BASE>:: sortedAppender’ (or there is no acceptable conversion)
with
[
BASE=RX::NodeId
]
c:arx_fastset.h(63): could be ‘RX::FastSet<BASE>:: sortedAppender &RX:: FastSet<BASE>:: sortedAppender:: operator =(unsigned int)’
with
[
BASE=RX::NodeId
]
while trying to match the argument list ‘(RX::FastSet<BASE>:: sortedAppender, RX::FastSet<BASE>:: sortedAppender)’
with
[
BASE=RX::NodeId
]
c:program filesmicrosoft visual studio 8vcincludealgorithm(3850) : see reference to function template instantiation ‘_OutIt std:: _Set_union<std:: _Vector_const_iterator<_Ty,_Alloc>,std::_Vector_const_iterator<_Ty,_Alloc>,_OutIt>(_InIt1,_InIt1,_InIt2,_InIt2,_OutIt,std::_Range_checked_iterator_tag)’ being compiled
with
[
_OutIt=RX::FastSet<RX::NodeId>:: sortedAppender,
_Ty=RX::NodeId,
_Alloc=std::allocator<RX::NodeId>,
_InIt1=std::_Vector_const_iterator<RX::NodeId,std::allocator<RX::NodeId>>,
_InIt2=std::_Vector_const_iterator<RX::NodeId,std::allocator<RX::NodeId>>
]
c:arx_vist.cpp(77) : see reference to function template instantiation ‘RX::FastSet<BASE>:: sortedAppender std:et_union<std::_Vector_const_iterator<_Ty,_Alloc>,std::_Vector_const_iterator<_Ty,_Alloc>,RX::FastSet<BASE>:: sortedAppender>(_InIt1,_InIt1,_InIt2,_InIt2,_OutIt)’ being compiled
with
[
BASE=RX::NodeId,
_Ty=RX::NodeId,
_Alloc=std::allocator<RX::NodeId>,
_InIt1=std::_Vector_const_iterator<RX::NodeId,std::allocator<RX::NodeId>>,
_InIt2=std::_Vector_const_iterator<RX::NodeId,std::allocator<RX::NodeId>>,
_OutIt=RX::FastSet<RX::NodeId>:: sortedAppender
]
c:program filesmicrosoft visual studio 8vcincludealgorithm(3815) : error C2582: ‘operator =’ function is unavailable in ‘RX::FastSet<BASE>:: sortedAppender’
with
[
BASE=RX::NodeId
]
Any help in this would be grateful.
title | description | ms.date | f1_keywords | helpviewer_keywords | ms.assetid | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|
/permissive- (Standards conformance) |
Reference guide to the Microsoft C++ /permissive- (Standards conformance) compiler option. |
12/14/2022 |
|
|
db1cc175-6e93-4a2e-9396-c3725d2d8f71 |
/permissive-
(Standards conformance)
Specify standards conformance mode to the compiler. Use this option to help you identify and fix conformance issues in your code, to make it both more correct and more portable.
Syntax
/permissive-
/permissive
Remarks
The /permissive-
option is supported in Visual Studio 2017 and later. /permissive
is supported in Visual Studio 2019 version 16.8 and later.
You can use the /permissive-
compiler option to specify standards-conforming compiler behavior. This option disables permissive behaviors, and sets the /Zc
compiler options for strict conformance. In the IDE, this option also makes the IntelliSense engine underline non-conforming code.
The /permissive-
option uses the conformance support in the current compiler version to determine which language constructs are non-conforming. The option doesn’t determine if your code conforms to a specific version of the C++ standard. To enable all implemented compiler support for the latest draft standard, use the /std:c++latest
option. To restrict the compiler support to the currently implemented C++20 standard, use the /std:c++20
option. To restrict the compiler support to the currently implemented C++17 standard, use the /std:c++17
option. To restrict the compiler support to more closely match the C++14 standard, use the /std:c++14
option, which is the default.
The /permissive-
option is implicitly set by the /std:c++latest
option starting in Visual Studio 2019 version 16.8, and in version 16.11 by the /std:c++20
option. /permissive-
is required for C++20 Modules support. Perhaps your code doesn’t need modules support but requires other features enabled under /std:c++20
or /std:c++latest
. You can explicitly enable Microsoft extension support by using the /permissive
option without the trailing dash. The /permissive
option must come after any option that sets /permissive-
implicitly.
By default, the /permissive-
option is set in new projects created by Visual Studio 2017 version 15.5 and later versions. It’s not set by default in earlier versions. When the option is set, the compiler generates diagnostic errors or warnings when non-standard language constructs are detected in your code. These constructs include some common bugs in pre-C++11 code.
The /permissive-
option is compatible with almost all of the header files from the latest Windows Kits, such as the Software Development Kit (SDK) or Windows Driver Kit (WDK), starting in the Windows Fall Creators SDK (10.0.16299.0). Older versions of the SDK may fail to compile under /permissive-
for various source code conformance reasons. The compiler and SDKs ship on different release timelines, so there are some remaining issues. For specific header file issues, see Windows header issues below.
The /permissive-
option sets the /Zc:referenceBinding
, /Zc:strictStrings
, and /Zc:rvalueCast
options to conforming behavior. These options default to non-conforming behavior. You can pass specific /Zc
options after /permissive-
on the command line to override this behavior.
In versions of the compiler beginning in Visual Studio 2017 version 15.3, the /permissive-
option sets the /Zc:ternary
option. The compiler also implements more of the requirements for two-phase name look-up. When the /permissive-
option is set, the compiler parses function and class template definitions, and identifies dependent and non-dependent names used in the templates. In this release, only name dependency analysis is performed.
Environment-specific extensions and language areas that the standard leaves up to the implementation aren’t affected by /permissive-
. For example, the Microsoft-specific __declspec
, calling convention and structured exception handling keywords, and compiler-specific pragma
directives or attributes aren’t flagged by the compiler in /permissive-
mode.
The MSVC compiler in earlier versions of Visual Studio 2017 doesn’t support all C++11, C++14, or C++17 standards-conforming code. Depending on the version of Visual Studio, the /permissive-
option may not detect issues in some aspects of two-phase name lookup, binding a non-const reference to a temporary, treating copy init as direct init, allowing multiple user-defined conversions in initialization, or alternative tokens for logical operators, and other non-supported conformance areas. For more information about conformance issues in Visual C++, see Nonstandard Behavior. To get the most out of /permissive-
, update Visual Studio to the latest version.
How to fix your code
Here are some examples of code that is detected as non-conforming when you use /permissive-
, along with suggested ways to fix the issues.
Use default
as an identifier in native code
void func(int default); // Error C2321: 'default' is a keyword, and // cannot be used in this context
Look up members in dependent base
template <typename T> struct B { void f() {} template <typename U> struct S { void operator()(){ return; } }; }; template <typename T> struct D : public B<T> // B is a dependent base because its type // depends on the type of T. { // One possible fix for non-template members and function // template members is a using statement: // using B<T>::f; // If it's a type, don't forget the 'typename' keyword. void g() { f(); // error C3861: 'f': identifier not found // Another fix is to change the call to 'this->f();' } void h() { S<int> s; // C2065 or C3878 // Since template S is dependent, the type must be qualified // with the `typename` keyword. // To fix, replace the declaration of s with: // typename B<T>::template S<int> s; // Or, use this: // typename D::template S<int> s; s(); } }; void h() { D<int> d; d.g(); d.h(); }
Use of qualified names in member declarations
struct A { void A::f() { } // error C4596: illegal qualified name in member // declaration. // Remove redundant 'A::' to fix. };
Initialize multiple union members in a member initializer
union U { U() : i(1), j(1) // error C3442: Initializing multiple members of // union: 'U::i' and 'U::j'. // Remove all but one of the initializations to fix. {} int i; int j; };
Hidden friend name lookup rules
A declaration outside a class can make a hidden friend visible:
// Example 1 struct S { friend void f(S *); }; // Uncomment this declaration to make the hidden friend visible: // void f(S *); // This declaration makes the hidden friend visible using type = void (*)(S *); type p = &f; // error C2065: 'f': undeclared identifier.
Use of literal nullptr
can prevent argument dependent lookup:
// Example 2 struct S { friend void f(S *); }; void g() { // Using nullptr instead of S prevents argument dependent lookup in S f(nullptr); // error C3861: 'f': identifier not found S *p = nullptr; f(p); // Hidden friend now found via argument-dependent lookup. }
You can enable the hidden friend name lookup rules independently of /permissive
by using /Zc:hiddenFriend
. If you want legacy behavior for hidden friend name lookup, but otherwise want /permissive-
behavior, use the /Zc:hiddenFriend-
option.
Use scoped enums in array bounds
enum class Color { Red, Green, Blue }; int data[Color::Blue]; // error C3411: 'Color' is not valid as the size // of an array as it is not an integer type. // Cast to type size_t or int to fix.
Use for each in native code
void func() { int array[] = {1, 2, 30, 40}; for each (int i in array) // error C4496: nonstandard extension // 'for each' used: replace with // ranged-for statement: // for (int i: array) { // ... } }
Use of ATL attributes
Microsoft-specific ATL attributes can cause issues under /permissive-
:
// Example 1 [uuid("594382D9-44B0-461A-8DE3-E06A3E73C5EB")] class A {};
You can fix the issue by using the __declspec
form instead:
// Fix for example 1 class __declspec(uuid("594382D9-44B0-461A-8DE3-E06A3E73C5EB")) B {};
A more complex example:
// Example 2 [emitidl]; [module(name="Foo")]; [object, local, uuid("9e66a290-4365-11d2-a997-00c04fa37ddb")] __interface ICustom { HRESULT Custom([in] longl, [out, retval] long*pLong); [local] HRESULT CustomLocal([in] longl, [out, retval] long*pLong); }; [coclass, appobject, uuid("9e66a294-4365-11d2-a997-00c04fa37ddb")] class CFoo : public ICustom {};
Resolution requires extra build steps. In this case, create an IDL file:
// Fix for example 2 // First, create the *.idl file. The vc140.idl generated file can be // used to automatically obtain a *.idl file for the interfaces with // annotation. Second, add a midl step to your build system to make // sure that the C++ interface definitions are outputted. // Last, adjust your existing code to use ATL directly as shown in // the atl implementation section. -- IDL FILE-- import "docobj.idl"; [object, local, uuid(9e66a290-4365-11d2-a997-00c04fa37ddb)] interface ICustom : IUnknown { HRESULT Custom([in] longl, [out,retval] long*pLong); [local] HRESULT CustomLocal([in] longl, [out,retval] long*pLong); }; [ version(1.0), uuid(29079a2c-5f3f-3325-99a1-3ec9c40988bb) ] library Foo { importlib("stdole2.tlb"); importlib("olepro32.dll"); [version(1.0), appobject, uuid(9e66a294-4365-11d2-a997-00c04fa37ddb)] coclass CFoo { interface ICustom; }; } -- ATL IMPLEMENTATION-- #include <idl.header.h> #include <atlbase.h> class ATL_NO_VTABLE CFooImpl : public ICustom, public ATL::CComObjectRootEx<CComMultiThreadModel> { public:BEGIN_COM_MAP(CFooImpl) COM_INTERFACE_ENTRY(ICustom) END_COM_MAP() };
Ambiguous conditional operator arguments
In versions of the compiler before Visual Studio 2017 version 15.3, the compiler accepted arguments to the conditional operator (or ternary operator) ?:
that are considered ambiguous by the Standard. In /permissive-
mode, the compiler now issues one or more diagnostics in cases that compiled without diagnostics in earlier versions.
Common errors that may result from this change include:
-
error C2593: 'operator ?' is ambiguous
-
error C2679: binary '?': no operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)
-
error C2678: binary '?': no operator found which takes a left-hand operand of type 'A' (or there is no acceptable conversion)
-
error C2446: ':': no conversion from 'B' to 'A'
A typical code pattern that can cause this issue is when some class C
provides both a non-explicit constructor from another type T
and a non-explicit conversion operator to type T
. The conversion of the second argument to the third argument’s type is a valid conversion. So is the conversion of the third argument to the second argument’s type. Since both are valid, it’s ambiguous according to the standard.
// Example 1: class that provides conversion to and initialization from some type T struct A { A(int); operator int() const; }; extern bool cond; A a(42); // Accepted when /Zc:ternary or /permissive- is not used: auto x = cond ? 7 : a; // A: permissive behavior prefers A(7) over (int)a // Accepted always: auto y = cond ? 7 : int(a); auto z = cond ? A(7) : a;
There’s an important exception to this common pattern when T represents one of the null-terminated string types (for example, const char *
, const char16_t *
, and so on) and the actual argument to ?:
is a string literal of corresponding type. C++17 has changed semantics from C++14. As a result, the code in example 2 is accepted under /std:c++14
and rejected under /std:c++17
or later when /Zc:ternary
or /permissive-
is used.
// Example 2: exception from the above struct MyString { MyString(const char* s = "") noexcept; // from char* operator const char* () const noexcept; // to char* }; extern bool cond; MyString s; // Using /std:c++14, /permissive- or /Zc:ternary behavior // is to prefer MyString("A") over (const char*)s // but under /std:c++17 this line causes error C2445: auto x = cond ? "A" : s; // You can use a static_cast to resolve the ambiguity: auto y = cond ? "A" : static_cast<const char*>(s);
You may also see errors in conditional operators with one argument of type void
. This case may be common in ASSERT-like macros.
// Example 3: void arguments void myassert(const char* text, const char* file, int line); // Accepted when /Zc:ternary or /permissive- is not used: #define ASSERT_A(ex) (void)((ex) ? 1 : myassert(#ex, __FILE__, __LINE__)) // Accepted always: #define ASSERT_B(ex) (void)((ex) ? void() : myassert(#ex, __FILE__, __LINE__))
You may also see errors in template metaprogramming, where conditional operator result types may change under /Zc:ternary
and /permissive-
. One way to resolve this issue is to use std::remove_reference
on the resulting type.
// Example 4: different result types extern bool cond; extern int count; char a = 'A'; const char b = 'B'; decltype(auto) x = cond ? a : b; // char without, const char& with /Zc:ternary const char (&z)[2] = count > 3 ? "A" : "B"; // const char* without /Zc:ternary
Two-phase name look-up
When the /permissive-
option is set, the compiler parses function and class template definitions, identifying dependent and non-dependent names used in templates as required for two-phase name look-up. In Visual Studio 2017 version 15.3, name dependency analysis is performed. In particular, non-dependent names that aren’t declared in the context of a template definition cause a diagnostic message as required by the ISO C++ standards. In Visual Studio 2017 version 15.7, binding of non-dependent names that require argument-dependent look-up in the definition context is also done.
// dependent base struct B { void g() {} }; template<typename T> struct D : T { void f() { // The call to g was incorrectly allowed in VS2017: g(); // Now under /permissive-: C3861 // Possible fixes: // this->g(); // T::g(); } }; int main() { D<B> d; d.f(); }
If you want legacy behavior for two-phase lookup, but otherwise want /permissive-
behavior, add the /Zc:twoPhase-
option.
Windows header issues
The /permissive-
option is too strict for versions of the Windows Kits before Windows Fall Creators Update SDK (10.0.16299.0), or the Windows Driver Kit (WDK) version 1709. We recommend you update to the latest versions of the Windows Kits to use /permissive-
in your Windows or device driver code.
Certain header files in the Windows April 2018 Update SDK (10.0.17134.0), the Windows Fall Creators Update SDK (10.0.16299.0), or the Windows Driver Kit (WDK) 1709, still have issues that make them incompatible with use of /permissive-
. To work around these issues, we recommend you restrict the use of these headers to only those source code files that require them, and remove the /permissive-
option when you compile those specific source code files.
These WinRT WRL headers released in the Windows April 2018 Update SDK (10.0.17134.0) aren’t clean with /permissive-
. To work around these issues, either don’t use /permissive-
, or use /permissive-
with /Zc:twoPhase-
when you work with these headers:
-
Issues in
winrt/wrl/async.h
C:Program Files (x86)Windows Kits10Include10.0.17134.0winrtwrlasync.h(483): error C3861: 'TraceDelegateAssigned': identifier not found C:Program Files (x86)Windows Kits10Include10.0.17134.0winrtwrlasync.h(491): error C3861: 'CheckValidStateForDelegateCall': identifier not found C:Program Files (x86)Windows Kits10Include10.0.17134.0winrtwrlasync.h(509): error C3861: 'TraceProgressNotificationStart': identifier not found C:Program Files (x86)Windows Kits10Include10.0.17134.0winrtwrlasync.h(513): error C3861: 'TraceProgressNotificationComplete': identifier not found
-
Issue in
winrt/wrl/implements.h
C:Program Files (x86)Windows Kits10include10.0.17134.0winrtwrlimplements.h(2086): error C2039: 'SetStrongReference': is not a member of 'Microsoft::WRL::Details::WeakReferenceImpl'
These User Mode headers released in the Windows April 2018 Update SDK (10.0.17134.0) aren’t clean with /permissive-
. To work around these issues, don’t use /permissive-
when working with these headers:
-
Issues in
um/Tune.h
C:ProgramFiles(x86)Windows Kits10include10.0.17134.0umtune.h(139): error C3861: 'Release': identifier not found C:Program Files (x86)Windows Kits10include10.0.17134.0umtune.h(559): error C3861: 'Release': identifier not found C:Program Files (x86)Windows Kits10include10.0.17134.0umtune.h(1240): error C3861: 'Release': identifier not found C:Program Files (x86)Windows Kits10include10.0.17134.0umtune.h(1240): note: 'Release': function declaration must be available as none of the arguments depend on a template parameter
-
Issue in
um/spddkhlp.h
C:Program Files (x86)Windows Kits10include10.0.17134.0umspddkhlp.h(759): error C3861: 'pNode': identifier not found
-
Issues in
um/refptrco.h
C:Program Files (x86)Windows Kits10include10.0.17134.0umrefptrco.h(179): error C2760: syntax error: unexpected token 'identifier', expected 'type specifier' C:Program Files (x86)Windows Kits10include10.0.17134.0umrefptrco.h(342): error C2760: syntax error: unexpected token 'identifier', expected 'type specifier' C:Program Files (x86)Windows Kits10include10.0.17134.0umrefptrco.h(395): error C2760: syntax error: unexpected token 'identifier', expected 'type specifier'
These issues are specific to User Mode headers in the Windows Fall Creators Update SDK (10.0.16299.0):
-
Issue in
um/Query.h
When you use the
/permissive-
compiler switch, thetagRESTRICTION
structure doesn’t compile because of thecase(RTOr)
memberor
.struct tagRESTRICTION { ULONG rt; ULONG weight; /* [switch_is][switch_type] */ union _URes { /* [case()] */ NODERESTRICTION ar; /* [case()] */ NODERESTRICTION or; // error C2059: syntax error: '||' /* [case()] */ NODERESTRICTION pxr; /* [case()] */ VECTORRESTRICTION vr; /* [case()] */ NOTRESTRICTION nr; /* [case()] */ CONTENTRESTRICTION cr; /* [case()] */ NATLANGUAGERESTRICTION nlr; /* [case()] */ PROPERTYRESTRICTION pr; /* [default] */ /* Empty union arm */ } res; };
To address this issue, compile files that include
Query.h
without the/permissive-
option. -
Issue in
um/cellularapi_oem.h
When you use the
/permissive-
compiler switch, the forward declaration ofenum UICCDATASTOREACCESSMODE
causes a warning:typedef enum UICCDATASTOREACCESSMODE UICCDATASTOREACCESSMODE; // C4471
The forward declaration of an unscoped
enum
is a Microsoft extension. To address this issue, compile files that includecellularapi_oem.h
without the/permissive-
option, or use the/wd
option to silence warning C4471. -
Issue in
um/omscript.h
In C++03, a conversion from a string literal to
BSTR
(which is a typedef towchar_t *
) is deprecated but allowed. In C++11, the conversion is no longer allowed.virtual /* [id] */ HRESULT STDMETHODCALLTYPE setExpression( /* [in] */ __RPC__in BSTR propname, /* [in] */ __RPC__in BSTR expression, /* [in][defaultvalue] */ __RPC__in BSTR language = L"") = 0; // C2440
To address this issue, compile files that include omscript.h without the
/permissive-
option, or use/Zc:strictStrings-
instead.
To set this compiler option in the Visual Studio development environment
In Visual Studio 2017 version 15.5 and later versions, use this procedure:
-
Open your project’s Property Pages dialog box.
-
Select the Configuration Properties > C/C++ > Language property page.
-
Change the Conformance mode property value to Yes (/permissive-). Choose OK or Apply to save your changes.
In versions before Visual Studio 2017 version 15.5, use this procedure:
-
Open your project’s Property Pages dialog box.
-
Select the Configuration Properties > C/C++ > Command Line property page.
-
Enter the /permissive- compiler option in the Additional Options box. Choose OK or Apply to save your changes.
To set this compiler option programmatically
- See xref:Microsoft.VisualStudio.VCProjectEngine.VCCLCompilerTool.AdditionalOptions%2A.
See also
MSVC Compiler Options
MSVC Compiler Command-Line Syntax
Hi everyone, I’m new to C++. I’ve been assigned the following tasks.
1. Choose any two random numbers in the range 3 to 9.
2. Find position of these random numbers for each row.
3. Swap these two random numbers for each row.
4. Display new vector after swapping.
I tried to solve it but error occurred.
Error:
error C2679: binary ‘<<‘: no operator found which takes a right-hand operand of type ‘std::vector<int,std::allocator<_Ty>>’ (or there is no acceptable conversion)
I don’t know how to fix it. Hopefully someone can help me. Thank you
|
|
Here:
|
|
The type of it is std::vector<std::vector<int>>::iterator, so the type of *it is std::vector<int>.
Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.
Because you have a vector of vectors, your iterators are pointing to an entire vector of values, not a single value … so the << operator won’t know how to output them.
Perhaps you would like to explain exactly how you think «your» code works?
I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.
HiHelios,
Are you sure the rest of the code in the loop does what you think it does? What it really does is not swap two numbers. It’s swapping two vectors; two rows, if you will.
Can’t I use iter_swap() function to swap numbers?
Hilastchance,
I think it would be easier to advise if you gave us VERBATIM the bit of your assignment BEFORE what you have quoted: we are only getting a very confused story and it is unclear what you are being asked.
Sorry for inconvenience. I was given a task to generate two random numbers between 3 to 9.
For example: first random number = 5 and second random number = 9.
Then, I need to find the position of these random number for each row vector as follow:
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> first random number = position 5, second random number = position 1
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> first random number = position 5, second random number = position 9
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> first random number = position 1, second random number = position 6.
Then, swap these random numbers for each row
{ 9, 8, 7, 6, 5, 4, 3, 2, 1 } —> { 5, 8, 7, 6, 9, 4, 3, 2, 1 }
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } —> { 1, 2, 3, 4, 9, 6, 7, 8, 5 }
{ 5, 4, 3, 2, 1, 9, 8, 7, 6 } —> { 9, 4, 3, 2, 1, 5, 8, 7, 6 }
You need to deal with each vec[i] in turn, not the whole of vec.
I presume you know whether the number refers to the value or its position.
Last edited on
Hi lastchance,
You need to deal with each vec[i] in turn, not the whole of vec.
Does it mean I need to deal with each column not each row.
Sorry for asking. A bit confusing..
Does it mean I need to deal with each column not each row.
You need to deal with both.
sarah1993 wrote: |
---|
Does it mean I need to deal with each column not each row. |
You need to deal with the i’th row (that, is, vec[i]) inside the i loop.
|
|
needs to be
|
|
with a whole mass of other changes from vec to vec[i] below it.
For your final output either move it outside the i loop, or just do one row vector at a time.
Your random numbers are currently in the range 3 to 11, not 3 to 9.
Last edited on
Hi lastchance and helios, thank you for your advise.
I’ve improved this codes based on your explanation and it worked. Thank you so much for helping. I really appreciated it.
Topic archived. No new replies allowed.
mariellla 0 / 0 / 1 Регистрация: 05.09.2016 Сообщений: 55 |
||||||||||||
1 |
||||||||||||
09.03.2017, 13:51. Показов 5387. Ответов 3 Метки нет (Все метки)
Нужно создать класс List для представления простого списка. list.h
list.cpp
uselist.cpp
__________________
0 |
GbaLog- Любитель чаепитий 3734 / 1793 / 563 Регистрация: 24.08.2014 Сообщений: 5,998 Записей в блоге: 1 |
||||||||||||
09.03.2017, 14:07 |
2 |
|||||||||||
В list.h поключите Добавлено через 1 минуту
А зачем эта проверка? Добавлено через 4 минуты
#endif LIST_H_ Так тоже нельзя…
И где метод
for (int i = 0; !list.isempty(); i++) Ни разу не выполнится… Добавлено через 17 секунд
#endif LIST_H_ Так тоже нельзя…
И где метод
for (int i = 0; !list.isempty(); i++) Ни разу не выполнится…
0 |
mariellla 0 / 0 / 1 Регистрация: 05.09.2016 Сообщений: 55 |
||||||||||||
09.03.2017, 18:19 [ТС] |
3 |
|||||||||||
Кое что исправила.. list.h
list.cpp
uselist.cpp
0 |
GbaLog- Любитель чаепитий 3734 / 1793 / 563 Регистрация: 24.08.2014 Сообщений: 5,998 Записей в блоге: 1 |
||||
09.03.2017, 18:46 |
4 |
|||
Тут падает, потому что инкремент префиксный.
1 |
Hey Spiceworks Users,
I couldn’t find a C/C++ Programming group when choosing a group for this question, so I apologize in advance.
I am having to go through someone’s sloppy code and convert a program that was made in Visual Studio 6 to be useable in Visual Studio 2010, and I’ve hit this wall that I can’t seem to get over.
Here is the error I’m getting…
-
c:\program files\microsoft visual studio 10.0\vc\include\utility(217): error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘const CFGArray’ (or there is no acceptable conversion)
1> c:\work\pb\library\vc++\config.h(22): could be ‘CFGArray &CFGArray::operator =(CFGArray &)’
1> while trying to match the argument list ‘(CFGArray, const CFGArray)’
1> c:\program files\microsoft visual studio 10.0\vc\include\utility(215) : while compiling class template member function ‘std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(const std::pair<_Ty1,_Ty2> &)’
1> with
1> [
1> _Ty1=CString,
1> _Ty2=CFGArray
1> ]
1> c:\work\pb\library\vc++\config.cpp(39) : see reference to class template instantiation ‘std::pair<_Ty1,_Ty2>’ being compiled
1> with
1> [
1> _Ty1=CString,
1> _Ty2=CFGArray
1> ]
Here is, what I think, is the relevant code…
Config.h
-
class CFGArray : public CArray<cfgValue, cfgValue>{
public:
CFGArray();
CFGArray(const CFGArray ©);
CFGArray& operator= (CFGArray&); // This is line Line 22
};
Config.cpp
-
CFGArray::CFGArray(){this->RemoveAll();}
CFGArray::CFGArray(const CFGArray ©){
this->RemoveAll();
int i;
for(i = 0; i < copy.GetSize(); ++i)
this->Add(copy[i]);
}
CFGArray& CFGArray::operator= (CFGArray& rhs){
if (this != &rhs) {
int i;
this->RemoveAll();
for(i = 0; i < rhs.GetSize(); ++i)
this->Add(rhs[i]);
}
return *this;
}
Any idea how I can fix this?
13 Years Ago
Hi!
I try to implement a matrix template class which inherits the vector of vectors.
The message I get: «error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘const Vector<T> *’ (or there is no acceptable conversion)» (When I call the alternate matrix constructor, at the line «this = &h;».)
Any thoughts…? Thanks a lot in advance.
vectorTemplate.h:
#ifndef _VECTOR_TEMPLATE_H
#define _VECTOR_TEMPLATE_H
#include <iostream>
#include <fstream>
//#include "complex.h"
template<class T>
class Vector
{ private:
int num; // Number of elements
T* pdata; // Pointer to the data
void Init(int Num); // private function since user should not call it
// only for the member functions to call
public:
Vector(); // default constructor
Vector(int Num); // alternate constructor
Vector(const Vector& v); // copy constructor
~Vector(); // destructor
int GetNum() const; // access function
Vector<T>& operator= (const Vector<T>& v); // overloaded assignment operator
T& operator[] (int i) const; // overloaded array access operator
template<class T> friend std::istream& operator>>(std::istream& is, Vector<T>& v);// keyboard input
template<class T> friend std::ostream& operator<<(std::ostream& os, Vector<T>& v);// screen output
template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v);// file input
template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v);// file output
};
// default constructor
template<class T>
Vector<T>::Vector() : num(0), pdata(0) {}
// initialise data, called by the constructors
template<class T>
void Vector<T>::Init(int Num)
{
num = Num;
if (num <= 0)
pdata = 0; // Object construction failed!
else
pdata = new T[num]; // Allocate memory for vector
}
// alternate constructor
template<class T>
Vector<T>::Vector(int Num)
{
Init(Num);
}
// copy constructor
template<class T>
Vector<T>::Vector(const Vector& copy) {
Init(copy.GetNum()); // allocate the memory
// copy the data members
if (pdata) for (int i=0; i<num; i++) pdata[i]=copy.pdata[i];
}
// destructor
template<class T>
Vector<T>::~Vector()
{
delete [] pdata; // free the dynamic memory
}
// assignment operator
template<class T>
Vector<T>& Vector<T>::operator=(const Vector& copy)
{
if (this == ©) return *this; // Can't copy self to self (that is v = v
// in main is dealt with)
delete [] pdata; // delete existing memory
Init(copy.GetNum()); // create new memory then copy data
if (pdata) for (int i=0; i<copy.GetNum(); i++) pdata[i] = copy.pdata[i];
return *this;
}
// array access operator
template<class T>
T& Vector<T>::operator[](int i) const
{
if (i < 0)
i = 0; // Range error causes index to equal 0
// should really throw an exception
return pdata[i];
}
// return the size of the vector
template<class T>
int Vector<T>::GetNum() const
{
return num;
}
// keyboard input
template<class T>
std::istream& operator>>(std::istream& is, Vector<T>& v) {
int Num;
std::cout << "input the size for the vectorn";
is >> Num;
// create a temporary Vector object of correct size
Vector<T> temp(Num);
// input the elements
std::cout << "input the vector elementsn";
for (int i=0; i<Num; i++) is >> temp[i];
// copy temp into v
v = temp;
// return the stream object
return is;
}
// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Vector<T>& v)
{
int Num;
// read size from the file
ifs >> Num;
// create a temporary Vector object of correct size
Vector<T> temp(Num);
// input the values
for (int i=0; i<Num; i++) ifs >> temp[i];
// copy temp into v
v = temp;
// return the file stream object
return ifs;
}
// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Vector<T>& v)
{
if (v.pdata) {
os << "The vector elements aren";
for (int i=0; i<v.GetNum(); i++) os << v[i] << "n";
}
return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Vector<T>& v)
{
if (v.pdata) {
ofs << "The vector elements aren";
for (int i=0; i<v.GetNum(); i++) ofs << v[i] << "n";
}
return ofs;
}
#endif
matrixTemplate.h:
#ifndef _MATRIX_TEMPLATE_H
#define _MATRIX_TEMPLATE_H
#include <iostream>//
#include <fstream>//
#include "vectorTemplate.h"
//#include "complex.h"
template<class T>
class Matrix : public Vector< Vector<T> >{
public:
Matrix(); // default constructor, uses default constructor for v
Matrix(int Nrows, int Ncols); // alternate constructor
//T& operator() (int i, int j) const; // function call overload (-,-)
template<class T> friend Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2); // overload * for matrix multiplication
template<class T> friend std::istream& operator>>(std::istream& is, Matrix<T>& m);// keyboard input
template<class T> friend std::ostream& operator<<(std::ostream& os, Matrix<T>& m);// screen output
template<class T> friend std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m);// file input
template<class T> friend std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m);// file output
};
template<class T>
Matrix<T>::Matrix() : Vector< Vector<T> >()/*, nrows(0), ncols(0)*//*, Vector() */{}// default constructor, uses default constructor for v
template<class T>
Matrix<T>::Matrix(int Nrows, int Ncols) : Vector< Vector<T> >(Nrows)/*Vector< Vector<T> >()*//*, nrows(Nrows)*//*, ncols(Ncols)*//*, Vector(Nrows)*/ // alternate constructor
{
for (int i = 0; i < Nrows; i++)
{
/*const Vector<T>* d = new Vector<T>(Ncols);
this[i] = d;*/
Vector<T>* d = new Vector<T>(Ncols);
const Vector<T> h = *d;
this[i] = &h;
//this[i] = new Vector<T>(Ncols);
//this[i] = *(new Vector<T>(Ncols));//this[i] = &(*(new Vector<T>(Ncols)));//this[i] = *(new Vector<T>(Ncols));
}
}
template<class T>
Matrix<T> operator*(const Matrix<T>& m1, const Matrix<T>& m2)
// overload * for matrix multiplication
{
if (m1[0].GetNum() == m2.GetNum())
{
Matrix<T> m3(m1.GetNum() , m2[0].GetNum());
for (int i = 0; i < m1.GetNum(); i++)
{
for (int j = 0; j < m2[0].GetNum(); j++)
{
for (int k = 0; k < m1[0].GetNum(); k++)
{
if (k == 0) m3[i][j] = m1[i][k] * m2[k][j];
else m3[i][j] = m3[i][j] + m1[i][k] * m2[k][j];
}
}
}
return m3;
}
else
{
std::cout << "input matrices are not multicablen";
return m1;
}
}
//screen input
template<class T>
std::istream& operator>>(std::istream& is, Matrix<T>& m) {
int Nrows, Ncols;
// input the size of the matrix
std::cout << "input num of rows and columnsn";
is >> Nrows >> Ncols;
// create a temporary matrix of the correct size
Matrix<T> temp(Nrows, Ncols);
std::cout << "input the matrix elementsn";
for (int i=0; i<Nrows; i++)
{
for (int j=0 ; j<Ncols; j++)
{std::cout << "hi";
is >> temp[i][j];std::cout << "ha";
}
}
// copy temp to m
m = temp;
return is;
}
// file input
template<class T>
std::ifstream& operator>>(std::ifstream& ifs, Matrix<T>& m)
{
int Nrows, Ncols;
// read size from the file
ifs >> Nrows >> Ncols;
// create a temporary Matrix object of correct size
Matrix<T> temp(Nrows, Ncols);
// input the values
for (int i=0; i<Nrows; i++)
for (int j=0 ; j<Ncols; j++) ifs >> temp[i][j];
// copy temp to m
m = temp;
// return the file stream object
return ifs;
}
// screen output
template<class T>
std::ostream& operator<<(std::ostream& os, Matrix<T>& m)
{
if (m.GetNum() > 0) {
os << "The matrix elements aren";
for (int i=0; i<m.GetNum(); i++)
{
if (m[0].GetNum() > 0)
{
for (int j=0; j<m[0].GetNum(); j++)
{
os << m[i][j] << "n";
}
}
}
}
return os;
}
// file output
template<class T>
std::ofstream& operator<<(std::ofstream& ofs, Matrix<T>& m)
{
if (m.GetNum() > 0) {
ofs << "The matrix elements aren";
for (int i=0; i<m.GetNum(); i++)
{
if (m[0].GetNum() > 0)
{
for (int j=0; j<m[0].GetNum(); j++)
{
ofs << m[i][j] << "n";
}
}
}
}
return ofs;
}
#endif
Recommended Answers
Can you explain why did you wrote this absolutely senseless expression:
this[i] = &h
? If you want inheritedoperator[]
, write(*this)[i]
…
Jump to Post
It’s of no importance. What did you want to do there — that is a question.
Jump to Post
All 5 Replies
ArkM
1,090
Postaholic
13 Years Ago
Can you explain why did you wrote this absolutely senseless expression: this[i] = &h
? If you want inherited operator[]
, write (*this)[i]
…
13 Years Ago
Can you explain why did you wrote this absolutely senseless expression:
this[i] = &h
? If you want inheritedoperator[]
, write(*this)[i]
…
I tried many combinations (some of them are still there as comments), among them this[i] = new Vector<T>(Ncols);
too. (*this)[i] = new Vector<T>(Ncols);
is not working either.
ArkM
1,090
Postaholic
13 Years Ago
It’s of no importance. What did you want to do there — that is a question.
daviddoria
334
Posting Virtuoso
Featured Poster
13 Years Ago
Why post 500 lines of code? Can you simplify the code to < 20 lines so we can look at it?
xth
0
Newbie Poster
12 Years Ago
how did you solve the problem?
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
-
June 9 2004, 08:38
- IT
- Cancel
За что мне следует благодарить судьбу, так это за то, что уберегла от интимной близости с STL. Целый час бился головой об ошибку компилятора:
error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘std::basic_string
[Error: Irreparable invalid markup (‘<_elem,_traits,_ax>’) in entry. Owner must fix manually. Raw contents below.]
За что мне следует благодарить судьбу, так это за то, что уберегла от интимной близости с STL. Целый час бился головой об ошибку компилятора:
error C2679: binary ‘=’ : no operator found which takes a right-hand operand of type ‘std::basic_string<_Elem,_Traits,_Ax>::iterator’ (or there is no acceptable conversion)
with
[
_Elem=char,
_Traits=std::char_traits<char>,
_Ax=std::allocator<char>
]
Моя взяла, но голова кровоточит и шрамы не рубцуются.
Чур меня, чур! Совсем необязательно постигать красоту через строительство Беломорканала. Вообще, после C# во временном возвращении к макросам и шаблонам C++ важнее всего прилагательное «временное».
Hello everyone,
I am finishing up my Olympic Game program and I have encountered a problem when I use my swap function to switch the Athlete who won the medal. It happens when I assign gold = swap(gold, comp[a]). I will receive an error saying, «c2679 binary = no operator found which takes a right-hand operand of type void». I have done an operator overload for‘=’. Here is my code.
Main.cpp---------------------------------------------------
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
#include<vector>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
#include"OylmpicGames.h"
void displayTitle()
{
cout<<"************** OYLMPIC GAMES ***************"<<endl;
}
vector<string> setUpGames(Athletes player)
{
const int SIZE=4;
string a[SIZE]={"track","shooting","hockey",""};
static vector<string> listOfEvents(a, a+SIZE);
cout << "Uma testingn";
for(int t=0; t<listOfEvents.size(); t++)
{
cout<<listOfEvents[t]<<endl;
}
cout << "Uma testingn";
std::vector<string>::iterator location;
location = std::find(listOfEvents.begin(), listOfEvents.end(), player.sportName);
if(location == listOfEvents.end())
{
cout<<"----------The event was added to the list---------------"<<endl;
listOfEvents.push_back(player.sportName);
return listOfEvents;
}
else
{
cout<<"----------A match was found------------"<<endl;
string nothing = "";
return listOfEvents;
}
cout<<"The list of events vector"<<endl;
for(int t=0; t<listOfEvents.size(); t++)
{
cout<<listOfEvents[t]<<endl;
}
cout<<"---------------------------------------------"<<endl;
}
void getResults(vector <Athletes> comp )
{
Athletes gold;
Athletes silver;
Athletes bronze;
srand(time(0));
cout<<"***************"<<comp[0].sportName<<"****************"<<endl;
cout<<"======================================================"<<endl;
if(comp.size()>=4)
{
for(int j=0; j<comp.size(); j++)
{
comp[j].compNum=(rand() % 1000)+1;
}
gold=comp[0];
silver=comp[1];
bronze=comp[2];
for(int a=0; a<comp.size(); a++)
{
if(gold.compNum<= comp[a].compNum)
{
gold = swap(gold, comp[a]);
//CAUSING ERROR C2679!!!
}
else if(comp[a].compNum<gold.compNum && comp[a].compNum >= silver.compNum)
{
silver = swap(silver, comp[a]); //CAUSING ERROR C2679!!!
}
else if(comp[a].compNum<gold.compNum && comp[a].compNum < silver.compNum && comp[a].compNum >= bronze.compNum)
{
bronze = swap(bronze, comp[a]); //CAUSING ERROR C2679!!!
}
else if(a==(comp.size()-1))
{
cout<<"Gold Medalist "<<gold.name<<endl;
cout<<"Silver Medalist "<<silver.name<<endl;
cout<<"Bronze Medalist "<<bronze.name<<endl;
}
else
{}
}
}
else if(comp.size()==3)
{
for(int j=0; j<comp.size(); j++)
{
comp[j].compNum=(rand() % 1000)+1;
}
gold=comp[0];
silver=comp[1];
for(int a=0; a<comp.size(); a++)
{
if(gold.compNum<= comp[a].compNum)
{
gold = swap(gold,comp[a]);
//CAUSING ERROR C2679!!!
}
else if(comp[a].compNum<gold.compNum && comp[a].compNum >= silver.compNum)
{
silver = swap(silver, comp[a]); //CAUSING ERROR C2679!!!
}
else if(a==(comp.size()-1))
{
cout<<"Gold Medalist "<<gold.name<<endl;
cout<<"Silver Medalist "<<silver.name<<endl;
}
else
{}
}
}
else if(comp.size()==2)
{
for(int j=0; j<comp.size(); j++)
{
comp[j].compNum=(rand() % 1000)+1;
}
gold=comp[0];
for(int a=0; a<comp.size(); a++)
{
if(gold.compNum<= comp[a].compNum)
{
gold = swap(gold, comp[a]);
//CAUSING ERROR C2679!!!
}
else if(a==(comp.size()-1))
{
cout<<"Gold Medalist "<<gold.name<<endl;
}
else
{}
}
}
else if(comp.size()==1)
{
gold=comp[0];
}
}
Athletes swap(Athletes medal, Athletes comp)
{
Athletes temp;
temp = medal;
medal=comp;
comp=temp;
return medal;
}
void playGames(vector <string> eventList, vector <Athletes> player)
{
vector <Athletes> numberOfPlayers;
vector <Athletes> alternatePlayers;
cout<<"============LET THE GAMES BEGIN=========== "<<endl;
for(int i=0; i<eventList.size(); i++)
{
for(int j=0; j<player.size(); j++)
{
if(eventList[i] == player[j].sportName)
{
numberOfPlayers.push_back(player[j]);
if(j == (player.size() - 1)&&(player.size()<=6))
{
getResults(numberOfPlayers);
}
else if(numberOfPlayers.size()>6)
{
for(int a=0; a<6; a++)
{
Athletes p;
alternatePlayers.push_back(p);
}
}
}
}
}
}
int main()
{
vector <string> result;
displayTitle();
ifstream openFile("TextFile.txt");
Athletes listOfPlayers[10][25];
vector< string > listOfEvents;
string qLine;
while(!openFile.eof())
{
int countryNumber;
int playersNumber;
string name;
string sport;
string country;
openFile>>countryNumber;
for(int i=0; i<countryNumber;i++)
{
getline(openFile,country, ' ');
openFile>>playersNumber;
for(int j=0; j<playersNumber; j++)
{
getline(openFile, name, ' ');
getline(openFile, sport,'n');
listOfPlayers[i][j].setValue(name, sport, country);
static vector<Athletes> realPlayers;
cout<<"Name of the country "<<country<<endl;
cout<<"Name of the Player "<<name<<endl;
cout<<"Name of the sport "<<sport<<endl;
result = setUpGames(listOfPlayers[i][j]);
realPlayers.push_back(listOfPlayers[i][j]);
if(i == (countryNumber-1) && j == (playersNumber - 1))
{
playGames(result, realPlayers);
}
}
}
openFile.close();
}
system("PAUSE");
return 0;
}
Open in new window