![](/img/trans.png)
[英]Binary search giving me error saying forcing value to bool 'true' or 'false'
[英]Why is below program giving me error when I am assigning true or false to a vector of type bool?
我在TopCoder上遇到問題 ,無法在無環有向圖中找到最長的路徑。 我已經使用了bool類型的vector來訪問頂點。 但這給了我這些錯誤(在下面的代碼中突出顯示):
error: no match for ‘operator=’ (operand types are ‘std::vector<bool>’ and ‘bool’)
visited[cur_ver]=true;
error: no match for ‘operator==’ (operand types are ‘std::vector<bool>’ and ‘bool’)
if(visited[i]==false)
這是我的代碼:
#include<bits/stdc++.h>
using namespace std;
class Circuits{
vector<int>adj[51];
vector<int>cost[51];
vector<int>T[51];
vector<bool>visited[51];
vector<int>dist[51];
int glm=0;
public:
void topological_sorting(int cur_ver,int n){
visited[cur_ver]=true; //error 1
for(int i=0;i<adj[cur_ver].size();i++){
if(visited[i]==false) //error 2
topological_sorting(i);
}
T.insert(T.begin(),cur_ver);
}
void Longest_Path(int s,int n){
for(int i=0;i<=n;i++)
dist[i]=NINF;
dist[s]=0;
for(int i=0;i<=n;i++){
int u=T[i]
if(dist[u]!=NINF)
for(int j=0;j<adj[i].size();j++){
int v=adj[u][j];
if(dist[v]<dist[u]+cost[u][v])
dist[v]=dist[u]+cost[u][v];
}
}
for(int i=0;i<=n;i++)
if(dist[i]>glm)
glm=dist[i];
}
int howLong(vector<string>connects,vector<string>costs){
for(int i=0;i<connects.size();i++){
for(int j=0;j<connects[i].size();j++){
adj[i].push_back(int(connects[i][j]));
cost[i].push_back(int(costs[i][j]));
}
}
int n=connects.size();
for(int i=0;i<=n;i++)
visited[i]=false;
topological_sorting(0,n);
int lm=0;
for(int i=0;i<=n;i++){
Longest_Path(i,n);
if(glm>lm)
lm=glm;
glm=0
}
return lm;
}
};
您會混淆內置數組語法和std::vector<T>
類的語法。 精確地
std::vector<int> myVec[51]
您聲明和數組int類型的51個向量 。 因此,代碼
visited[cur_ver]=true;
表示“獲取數組myVec
元素52,並為其分配true
”。 但是,該元素不是bool
類型,而是std::vector<int>
。 沒有允許將bool
值分配給矢量對象的運算符。
要指定向量的大小(這是您的意圖),請使用適當的構造函數或resize()
方法。 如果確定容器的大小是固定的並且在編譯時已知,則可以使用std::array<size_t, T>
(這是一個固定長度的數組容器,在C ++ 11中可用)。 但這不是您的代碼的情況-稍后插入元素。
因此,要修復該錯誤,請修復矢量聲明的語法,然后在類的構造函數中調整大小:
vector<int> adj;
// other vectors follow ...
// in Circuit::Circuit:
Circuit:Circuit() {
adj.resize(51); // others follow ...
}
確保用正確命名的常量替換51
。 “魔術”常數是邪惡的!
向量就像動態數組一樣,具有調整大小的能力。 在c ++中,只有兩種方法來聲明向量。
vector <int> myVector;
vector <int> myVector2(4,1000);
第二個將初始化一個初始值為1000的大小為4的向量。如果要提供大小,則可以這樣使用。
vector <int> myVector(12);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.