amazon

5.4.12

Visual Studio error C2676, C2679

Visual Studioでコンパイルしたらこんなエラーが出た。
error C2676: 二項演算子 '==' : 'std::string' は、この演算子または定義済の演算子に適切な型への変換の定義を行いません。(新しい動作; ヘルプを参照)
error C2679: 二項演算子 '!=' : 型 'std::string' の右オペランドを扱う演算子が見つかりません (または変換できません)。
std::stringで==や!=の比較演算子がオーバーロードされてないということらしい。


Macのg++だと問題なくコンパイル出来たファイルなのだが・・・、と思っていたが、
#include <string>
を追加していなかったのが原因。

ところで、Macのg++でコンパイルできてしまうのは自動的にstringがインクルードされているからなのだろうか?

18.2.12

std::vectorでIndexOf

c++のstd::vectorはindexofのような関数がない。
std::vectorで、指定した要素が含まれているか調べ、
含まれていたらそのインデックス番号(何番目の要素か)を返す関数を作ってみた。

以下の例では、std::vector<std::string>の中にtargetが含まれるか調べ、
含まれているインデックスのベクトル(std::vector<int>)を返している。

#include <vector>
#include <algorithm>
#include <iostream>

std::vector<int> indexOf( std::vector< std::string > strvec, std::string target ){
    std::vector< int > rt;
    std::vector< std::string >::iterator it = strvec.begin();
    while( strvec.end() != ( it = std::find( it, strvec.end(), target ) ) ){
        rt.push_back( std::distance( strvec.begin(), it ) );
        it++;
    }
    if( rt.empty() ) std::cout << target << " was not found." << std::endl;
    return rt;
}

16.1.12

Visual Studioのフォームアプリケーションで、コンソールに標準出力(printf, std::cout等)を表示する方法


Visual Studioでのフォームアプリケーションは標準では、コンソールにが表示されない。
それゆえデバッグにprintfやstd::coutが使えないのが難点。

そこで、コンソール(コマンドプロンプト)を開きそこへ標準出力(printfやstd::cout)できるようにした。
以下がフォームアプリケーションのメイン プロジェクト ファイルに書き加えた例。
赤字部分がその簡易マクロと追加した行。

// MyProgram.cpp : メイン プロジェクト ファイルです。

#include "stdafx.h"
#include "Form1.h"
#include <stdio.h>
#include <windows.h>
#include <iostream>

#define OPENCONSOLE(fp) { if (!::AttachConsole(ATTACH_PARENT_PROCESS)) ::AllocConsole(); freopen_s(&fp, "CON", "w", stdout);}
#define CLOSECONSOLE(fp) {fclose(fp); ::FreeConsole();}

using namespace MyProgram

[STAThreadAttribute]
int main(array$lt;System::String ^> ^args){
FILE *fp;
OPENCONSOLE(fp);

// コントロールが作成される前に、Windows XP ビジュアル効果を有効にします
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);

// メイン ウィンドウを作成して、実行します
Application::Run(gcnew Form1());

std::cout<<"これでコンソールに表示される"<<std::endl;
CLOSECONSOLE(fp);
return 0;
}