Domanda

This is a code snippet from a pretty simple program I am writing. I am fairly new to C++, but have background in Java, so I may have preconceptions as to how printing values should work. My problem is when I do this line:

cout << "Please enter the weight for edge " << verticies[i] << endl;

I get an error message saying that the operands do not match the designated operator for <<. Basically it is saying I can't do cout << verticies[i].

Why does this happen?

Here is the code:

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    string verticies[6] = { "AB", "AC", "AD", "BC", "BD", "CD" };
    int edges[6];

    for (int i = 0; i < 6; i++)
    {
        cout << "Please enter the weight for edge " << verticies[i] << endl;
    }

    system("PAUSE");

    return 0;
}
È stato utile?

Soluzione

Try including <string>, should be enough

Altri suggerimenti

You have to include header <string> that contains the definition of the class std::basic_string including std::string

It is this header where the operator << is defined.

Also consider to use class std::map insted of the arrays. For exmple

std::map<std::string, int> verticies = 
{ 
   { "AB", 0 }, { "AC", 0 }, { "AD", 0 }, { "BC", 0 }, { "BD", 0 }, { "CD", 0 } 
};

If the code will not be compiled then explicitly specify std::pair in the initializer list. For example

{ std::pair<std::string, int>( "AB", 0 ), std::pair<std::string, int>( "AC", 0 ), ...}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top