Edge {
int source, dest, weight;
};
struct Node {
int vertex, weight;
};
int main()
{
vector<Edge> edges =
{
{0,1,2}, {0,2,3}, {1,3,-1}, {2,3,2} // (edge1, edge2, weight)
};
}
Run Code Online (Sandbox Code Playgroud)
I want to create a function to see if the weight of the edge is negative or positive. How can I make the function?
我想创建一个函数,即使一个负权重为负,它也会输出 false。例如,如果第一个是 {0,1,-2} 而不是 {0,1,2} 它是假的
为什么要重新发明轮子?
如果我正确理解你想要什么,它是一个作品 std::all_of()
#include <vector>
#include <iostream>
#include <algorithm>
struct Edge
{ int source, dest, weight; };
int main ()
{
std::vector<Edge> edges1 { {0,1,2}, {0,2,3}, {1,3,-1}, {2,3,2} },
edges2 { {0,1,2}, {0,2,3}, {1,3,+1}, {2,3,2} };
auto l = [](auto const & elem) { return elem.weight >= 0; };
auto b1 { std::all_of(edges1.cbegin(), edges1.cend(), l) },
b2 { std::all_of(edges2.cbegin(), edges2.cend(), l) };
std::cout << b1 << std::endl; // prints 0
std::cout << b2 << std::endl; // prints 1
}
Run Code Online (Sandbox Code Playgroud)
更一般地说,一个建议:尝试使用通过标准库可用的结构和算法。