2016-03-08 64 views
1

我創建了一個遊戲意味着年輕觀衆,我試圖篩選出褻瀆和冒犯名黑名單進攻句子

#include <iostream> 
#include <vector> 

bool isBanned(std::string text) { 
    std::vector bannedSent = { 
     "Profanity1", 
     "Profanity2", 
     "Profanity3", 
     "Profanity4" 
    }; 
    for(auto &i : bannedSent) { 
     if(text == i) { return true; } 
    } 
    return false; 
} 

我得到一個編譯器錯誤談論「模板參數」,上線與std::vector,這是什麼意思?

+2

您忘記指定矢量的類型,即:'std :: vector ' –

+1

您可以使用佔位符輕鬆地替換令人討厭的文本以達到本示例的目的。 –

+2

對於一個人來說,我有一個非常具體的東西,就像「希特勒沒有做錯什麼」一樣。 –

回答

1

如果要std::vector<std::string>

bool isBanned(std::string text) { 
    std::vector<std::string> bannedSent = { 
    ... 
    } 
} 
7

您需要提供模板參數到矢量。因爲你持有的字符串,你需要聲明它是這樣的:

std::vector<std::string> bannedSent = { 
    "Gosh", 
    "Golly", 
    "Jeepers", 
    "Troll" 
}; 
+0

我不會接受這個,因爲「唐納德特朗普」的評論,保持政治不爲此 –

+4

我的道歉。考慮到你的問題的政治參考,我認爲這樣會很好。 – paddy

+1

這幾點會教你,呃@paddy? ;)+1 – erip

1

既然你包括C++ 11的標籤,你也可以使用any_of()

#include <vector> 
#include <string> 
#include <algorithm> 

bool isBanned(const std::string & text) 
{ 
    const std::vector<std::string> bannedSent = { 
     "Profanity1", 
     "Profanity2", 
     "Profanity3", 
     "Profanity4", 
    }; 
    return std::any_of(bannedSent.begin(), bannedSent.end(), [text](std::string &s){return s == text; }); 
} 
+1

爲什麼不使用'std:find'? – Ferruccio

+0

@Ferruccio:我懷疑這樣會更有效率(或者,如果lambda採用引用的方式)。 'std :: find'需要爲找到的字符串創建一個迭代器,但你並不需要這麼做。當然,檢查'text'是否以'Profanity'開始,然後如果它以1和4之間的數字結束將會更有效率;} – MSalters

3

最簡單的解決方案實際上是不是來指定類型。編譯器已經有一個體面的想法,你已經知道了關鍵字:

auto bannedSent = { 
    "Profanity1", 
    "Profanity2", 
    "Profanity3", 
    "Profanity4" 
}; 
for(auto i : bannedSent) { ... 

附帶的好處是:避免這種在每次調用構建4個std::string對象。

請注意,您之前使用過auto& i。這是一個錯誤,你不打算改變bannedSent

+0

Nice KISS解決方案。 – erip

+0

要小心這個。 bannedSet類型不會是'vector ',而是'initializer_list' – purpletentacle