long-double 相关问题


12字节长的double如何放入64位寄存器中?

我们假设内存中有一个long double变量。根据我在网上找到的信息,它有 12 字节大。如果寄存器大小是64位,CPU如何对其进行操作?是否以某种方式划分?


java - 从语义上比较不同类型的数字

假设我有三个数字: 可比较 n1 = new Integer(432); 可比较 n2 = new Long(40); 可比较 n3 = new Double(500.12); 我想通过 Comparable 接口来比较这些数字。


相等运算符对于不相等的值返回 true

我有两个类型为 double 和 long 的变量 y 和 z。我的问题是,即使它们具有不相等的值,相等运算符也会为它们返回 true,如下面的代码片段所示: 公开课


Long 与控制器中参数类型的 long

当决定使用 Long 或 long 作为控制器/服务方法参数的类型时,我总是遇到这种困境。 我应该使用 Long 因为 Hibernate 建议使用引用类型...


将 Long 转换为 Varchar2

我正在尝试从长列插入 varchar2 列。这是下面的示例,TEXT.TEXT_COL = VARCHAR2(4000) 并且NOTE.TEXT_NOTE = LONG。 插入文本(ROW_ID,TEXT_COL) 选择 1,TEX...


PyTorch 几何 SAGEConv - 预期标量类型为 Long,但发现为 Float?

我正在尝试从模型类型的 torch_geometric 库实现图神经网络。我收到错误:“RuntimeError:预期标量类型 Long 但发现 Float”在此...


如何让编译器区分 f(double...) 和 f(int, double...)

我正在编写一个用于处理多项式的小型库。 主类称为poly,它包含4个重载构造函数。 Poly 类的对象是一个多项式的表示。 满


如何反序列化包含 List<?, ?> 作为值的 Map<?>...例如地图<Long, List<Long>?

我正在尝试使用杰克逊反序列化Map。当我尝试调用反序列化方法时,出现编译时错误。我使用的映射器是 com.fasterxml.ja...


如何获取Double的小数点后第一个数字?

我有一个像这样的Double: 339.09965653839 如何获取点后的第一个数字? 0 // 期望的结果 我试图研究类似的问题,但不幸的是我只找到了分离的方法......


Visual Basic for Applications - 检查数字是否为素数不起作用

我有以下 Visual Basic for Applications 代码: 函数 IsPrimeTrialDivision(number As Long) As Boolean 暗淡我只要 如果是数字<= 1 Then IsPrime = False Exit


Long 不能转换为 String

我想知道为什么在以下代码中出现以下异常: 公开课 AAA { 公共静态无效主(字符串[] args)抛出ParseException{ AAA a = 新 AAA(); ...


如何生成带有货币符号(例如 $)而不是货币代码(USD、EUR)的价格字符串?

这是我当前的代码: fun getMonthlyPriceString(yearlyPriceMicros: Long,currencyCode: String): String { val 格式:NumberFormat = NumberFormat.getCurrencyInstance() 格式。


为什么方法的值在select方法中不会改变?

我有一个从 Postgres 中的序列返回值的方法: public long GetSId(DatabaseFacade d,字符串序列名称) { var result = new NpgsqlParameter(":result", NpgsqlDbType.Integ...


为什么const指针可以指向非常量对象?

//示例1 常量双饼 = 3.14; // 常量对象 const double *cptr = &pie; // 指向 const 对象的指针 双 *ptr = &pie; // 错误 - 指向 const 的非 const 指针 //


我怎样才能摆脱Core中的`let`?

我有一个在内部循环中频繁调用的函数。它看起来像这样: 导入合格的 Data.Vector.Storable 作为 SV 新类型 Timedelta = Timedelta Double cklsLogDens :: SV.Vector Doub...


在C++11中用“auto”推导时,lambda的类型是什么?

我有一种看法,lambda 的类型是函数指针。当我执行以下测试时,我发现它是错误的(demo)。 #define LAMBDA [] (int i) -> long { return 0; } int 主函数 () { ...


在通常的算术转换中,无符号整数和有符号整数运算的结果在不同的编译器上是不同的

#包括 #包括 #包括 int main() { 断言(typeid(1L + 1U) == typeid(long)); std::cout << typeid(1L + 1U).name(); } I use the b...


为什么在matlab中find返回双精度值

matlab 中的 find 函数返回给定局部参数值为 true 的索引。 因此我想知道为什么返回值(对于索引)是 double 类型而不是 uint32 或 uin...


Java 泛型:当变量为 null 时检查类型

我在处理泛型类型的可能值时遇到问题。我想要一个 TimeTreeNodeDTO 应该能够处理两种类型的 TimeTree。具有 int 值的时间树和具有 double


React Native - 如何修复 Java.lang Double 无法转换为 java.lang.Boolean

我这几天遇到了一个烦人的问题(仅限Android)。 这似乎发生得很突然。我无法回避这个问题。请看下面我的gradle项目: 构建脚本...


为什么 MATLAB 中的 find 返回索引为双精度值?

MATLAB 中的 find 函数返回给定逻辑参数计算为 true 的索引。 因此我想知道,为什么返回的索引类型是 double 而不是 uint32 或 uint64 像最大的


在JS中检查另一个数组的正方形元素[重复]

我创建了一个程序来检查第二个数组是否是第一个数组的平方。在程序中,我使用了 square 变量 double 和排序元素,并检查目标是否...


运行时错误:使用 Trainer API 进行微调时,发现 dtype Long 但预期为 Float

我正在尝试使用 Huggingface Trainer API 微调 BERT 模型进行情感分析(将文本分类为正面/负面)。我的数据集有两列,文本和情感,它看起来像这样。 T...


将 VBA 字符串转换为 Double

我正在使用 VBA for word 的非常基本的编码来创建一个模板,该模板可以从窗口中的其他屏幕中提取数据。当它提取数字时,它们被格式化为字符串。我现在需要得到


关于标准输入流 std::cin 及其如何解析 double 和 ints 的问题

我正在阅读编程:使用 C++ 的原理和实践。目前我正在做第三章的练习,但是有一个问题难住了我。现在我可以让代码正常工作了,但我是


如何使用 bash 在文本文件中全局用双反斜杠替换反斜杠?

我有一个txt文件,在其中存储数据,并且还存储反斜杠转义字符。我读取了该文件的内容,然后将该值替换为 json 字段,因此我想添加 double


InvalidArgumentError:无法计算 MatMul,因为输入 #1(从零开始)预计是双张量,但实际上是浮点张量 [Op:MatMul] 名称:

input_data 的数据类型是 numpy.float64 的数组,但代码在张量流库中仍然失败,因为它不是“double”。不知道如何解决这个问题。 将张量流导入为 tf 导入


ng-bootstrap 滚动间谍在没有高度的情况下无法工作?

我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: 我在我的项目中使用 ng-bootstrap [ngbScrollSpy] 指令,如文档中所述,但它不起作用 - 滚动时活动项目不会改变。 我的代码如下: <div> <div class="sticky-top"> <ul class="nav menu-sidebar"> <li > <a [ngbScrollSpyItem]="[spy, 'about']">About</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="schedule">Schedule</a> </li> <li > <a [ngbScrollSpyItem]="spy" fragment="hotel">Information about the hotel</a> </li> </ul> </div> <div ngbScrollSpy #spy="ngbScrollSpy" > <section ngbScrollSpyFragment="about"> <h3>About</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="schedule"> <h3>Schedule</h3> <p>{{some long long text and content}}</p> </section> <section ngbScrollSpyFragment="hotel"> <h3>Information about the hotel</h3> <p>{{some long long text and content}}</p> </section> </div> </div> 我在这个 stackoverflow 问题中看到,我的问题是我没有向我的 div 提供 height,这是事实。 但我的滚动间谍部分遍布整个页面,而不是一个小 div,(导航本身是 sticky-top)。所以我不能给它高度。 我知道有替代方法 - 刷新窗口滚动上的滚动间谍,但我没有找到可以帮助我的正确代码。 你能解决我的问题吗? 为我提供刷新滚动间谍的代码/给我有关高度的提示/帮助我找到另一个相应的元素。 非常感谢! 附上 stackblitz 演示的链接 注意:我使用来自 @ng-bootstrap/ng-bootstrap 的 NgbScrollSpy (我想它是非常相似的库) 我做什么: 我将所有内容(包括导航)包装在中 <div class="wrapper" ngbScrollSpy #spy="ngbScrollSpy" rootMargin="2px" [threshold]="1.0" > <div class="sticky-top pt-4 pb-4 bg-white"> ..here the navigation... </div> ..here the sections... <section ngbScrollSpyFragment="about"> </section> //the last I use margin-bottom:2rem; <section ngbScrollSpyFragment="hotel" style="margin-bottom:10rem" </section> </div> 见“门槛”。这表明“更改”活动片段应该可见的百分比(1 是 100%) 包装类 .wrapper{ height:100%; position: absolute; top:0; } 我使用强制链接的类别 //remove all the class for the link a{ color:black; text-decoration:none; padding:8px 16px; } a.custom-active{ color:white; background-color:royalblue } 以及我使用的每个链接 <a [class.custom-active]="spy.active=='about'">About</a> 嗯,问题是如何“滚动到”。 “链接”应该作为链接使用。 第一个是指示“路由器”应该考虑“碎片” 如果我们的组件是独立组件,我们需要使用提供者,provideRouter bootstrapApplication(App, { providers: [ provideRouter([], withInMemoryScrolling({anchorScrolling:'enabled'})), ] }) 然后,我们需要考虑到我们的页面确实没有滚动,div“包装器”是谁拥有滚动。因此,我们订阅 router.events,当事件有“锚点”时,我们滚动“包装器”div constructor(router: Router) { router.events.pipe(filter((e:any) => e.anchor)).subscribe((e: any) => { (document.getElementById('wrapper') as any).scrollTop+= (document.getElementById(e.anchor)?.getBoundingClientRect().top||0) -72; //<--this is the offset }); } 在这个stactblitz中你有一个有效的例子


.NET MAUI、ios UseSafeArea 不工作 StackLayout、VerticalStackLayout 和 Grid

<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.Views.Activities.ActivityMapList" xmlns:maps="clr-namespace:Microsoft.Maui.Controls.Maps;assembly=Microsoft.Maui.Controls.Maps" xmlns:sensors="clr-namespace:Microsoft.Maui.Devices.Sensors;assembly=Microsoft.Maui.Essentials" xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls" ios:Page.UseSafeArea="False" Shell.NavBarIsVisible="False" Style="{StaticResource Key=DefaultPage}"> <ContentPage.Content> <StackLayout> <maps:Map VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"> <x:Arguments> <MapSpan> <x:Arguments> <sensors:Location> <x:Arguments> <x:Double>36.9628066</x:Double> <x:Double>-122.0194722</x:Double> </x:Arguments> </sensors:Location> <x:Double>0.01</x:Double> <x:Double>0.01</x:Double> </x:Arguments> </MapSpan> </x:Arguments> </maps:Map> </StackLayout> </ContentPage.Content> </ContentPage> StackLayout 或 Grid 内的地图控件,iOS 的 SafeArea 为 false,如图所示。 你有什么解决办法吗? 我需要在地图上使用网格或堆栈布局 默认情况下.NET MAUI 将考虑安全区域。所以使用特定于平台的UseSafeArea就是禁用安全区域。目前,将 UseSafeArea 设置为 false 不会改变行为(尽管应该如此),这是一个错误。另请参阅 MAUI github 上的问题:https://github.com/dotnet/maui/issues/5856 您还可以设置 IgnoreSafeArea 属性来实现相同的目的。但是,它不再在 .NET 7 中工作,请参阅以下问题:https://github.com/dotnet/maui/issues/12823 要解决您的问题,您需要将 IgnoreSafeArea="True" 添加到您的 Grid 或 StackLayout 并将 ios:Page.UseSafeArea="False" 添加到您的页面。这应该不是必需的,但这是对我有用的解决方法。 有关在 iOS 上禁用安全区域的文档可以在此处找到:https://learn.microsoft.com/en-us/dotnet/maui/ios/platform-specifics/page-safe-area-layout?view=net-毛伊岛-7.0 您可以设置 Page Padding 值来实现。在OnAppearing方法中,设置页面的safeInsets,如下代码: protected override void OnAppearing() { base.OnAppearing(); DeviceSafeInsetsService d = new DeviceSafeInsetsService(); double topArea = d.GetSafeAreaTop(); double bottomArea = d.GetSafeAreaBottom(); var safeInsets = On<iOS>().SafeAreaInsets(); safeInsets.Top = -topArea; safeInsets.Bottom = -bottomArea; Padding = safeInsets; } 要获取 topArea 和 bottomArea 值,您应该编写平台代码。答案末尾附有有关此内容的更详细教程。 首先你可以在Project文件夹中生成一个新的类文件并将其更改为部分类。生成两个部分方法。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaTop(); public partial double GetSafeAreaBottom(); } 然后在iOS平台生成部分文件并实现。该文件位于 Project/Platform/iOS 文件夹中,我想提一下的是,该文件是一个部分文件,因此命名空间应与上面的文件相同。生成此文件时,请删除命名空间中的 .Platforms.iOS 后缀。 public partial class DeviceSafeInsetsService { public partial double GetSafeAreaBottom() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var bottomPadding = window.SafeAreaInsets.Bottom; return bottomPadding; } return 0; } public partial double GetSafeAreaTop() { if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) { UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow(); var TopPadding = window.SafeAreaInsets.Top; return TopPadding; } return 0; } } 更多信息,您可以参考如何在.NET MAUI中编写特定于平台的代码和MauiPlatformCode示例代码 希望它对你有用。


如何在 C++/WinRT (WinUI3) 中将图像从内存读取到 ImageSource?

[1] 我想在 XAML 中显示 Image 控件的图像,但该图像来自字节数组。 我应该怎么办?图像格式可以是JPG、BMP或PNG之一。 [1] 我想在 XAML 中显示 Image 控件的图像,但该图像来自字节数组。 我该怎么办?图像格式可以是 JPG、BMP 或 PNG 之一。 <Image x:Name="img"/> void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data img().Source(???); // what should I do? } [2] 我尝试了InMemoryRandomAccessStream,但没有成功。 我知道在C#中使用MemoryStream很方便,但是如何在C++中实现它? 另一个问题是这个方法是否也适用于JPG和PNG格式的图像? void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; winrt::Windows::Storage::Streams::InMemoryRandomAccessStream stream; // How to read data from stream? bmp.SetSource(stream); img().Source(bmp); } [3] 现在功能已经实现了,但是还有两个问题 IAsyncAction MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; winrt::Windows::Storage::Streams::InMemoryRandomAccessStream stream; winrt::Windows::Storage::Streams::DataWriter dw(st.GetOutputStreamAt(0ULL)); dw.WriteBytes({ buf, size }); // This is very inefficient! co_await dw.StoreAsync(); dw.Close(); bmp.SetSource(stream); img().Source(bmp); stream.Close(); } 首先,我发现DataWriter::WriteBytes()确实是在复制数据。但我认为ImageSource只需要从我的buf中读取即可,不需要在读取之前将整个图像完全复制到流中。也许是类似MemoryView的东西,我这样想是不是错了? 其次,DataWriter和InMemoryRandomAccessStream的Close()应该在哪里调用? BitmapImage需要释放内存吗?这里有一个异步函数,我不知道应该写在哪里 [4] 根据IInspectable,我尝试了SHCreatMemStream并搜索了大量信息以提出另一个解决方案。目前的问题是,与方法[3]同样可行,但仍然会出现内存分配问题。 #include "Shlwapi.h" #include "shcore.h" #pragma comment(lib, "shlwapi.lib") void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&) { unsigned long long size; // iamge data size const unsigned char* buf; // image data winrt::Microsoft::UI::Xaml::Media::Imaging::BitmapImage bmp; IStream* stream{ SHCreateMemStream(buf, size) }; // Copying takes a lot of time static const GUID guidIRandomAccessStream = { 0x905a0fe1, 0xbc53, 0x11df, { 0x8c, 0x49, 0x00, 0x1e, 0x4f, 0xc6, 0x86, 0xda } }; winrt::Windows::Storage::Streams::IRandomAccessStream pRas{ }; CreateRandomAccessStreamOverStream(stream, BSOS_OPTIONS::BSOS_DEFAULT, guidIRandomAccessStream, (void**)&pRas); bmp.SetSource(stream); img().Source(bmp); } 通过性能测试,发现CreateRandomAccessStreamOverStream的时间是一致的,但是SHCreateMemStream消耗的时间与图像大小成正比。可以得出,SHCreateMemStream中创建流的过程也涉及到内存的复制。 我对Windows编程中的Stream不是特别熟悉。创建流的过程一定会涉及到内存复制吗?从内存加载图像可以避免额外的开销吗?还有没有类似MemoryStreamView的结构来替代吗? 还有一个问题,我知道新的图像肯定需要内存存储。 BitmapImage设置Stream为Source会接管Stream占用的内存吗? Image控件设置BitmapImage作为Source会接管BitmapImage占用的内存吗? 如果是这样的话,我可以接受Stream分配新的内存,否则仍然是一个效率问题。 谢谢!!!!!!! 使用Stream已经彻底解决了这个问题。如前四期所述。 至于附加问题: ★1 使用 CreatStreamOnHGlobal 而不是 SHCreatMemStream。 因为SHCreatMemStream在调用过程中会对传入的内存块参数进行另一次内存复制。 CreatStreamOnHGlobal 创建流后不执行内存复制。您可以先通过GlobalAlloc分配内存,写入所需的图像数据,然后调用CreatStreamOnHGlobal,无需任何时间开销。另外,可以将CreatStreamOnHGlobal的第二个参数设置为true,自动释放GlobalAlloc分配的内存。 通过进程内存监控,我发现对于同一个程序,使用CreatStreamOnHGlobal的速度是SHCreatMemStream的两倍,并且不会导致内存泄漏。 ★2 创建的Stream需要调用Release方法减少一个引用。 IRandomAccessStream作为局部变量,会自动析构,无需主动释放。 并且BitmapImage还管理一部分引用,这些引用在离开作用域后被释放。 通过测试COM对象上Release方法的返回值,发现整个程序结束后引用计数又回到了0


如何查找给定的键是否存在于 std::map 中

我正在尝试检查给定的键是否在地图中,但有些无法做到: typedef 映射::迭代器 mi; 地图米; m.insert(make_pair("f","++--")); 一对 我正在尝试检查给定的键是否在地图中,但有些做不到: typedef map<string,string>::iterator mi; map<string, string> m; m.insert(make_pair("f","++--")); pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want cout << p.first;//I'm getting error here 那么我怎样才能打印p中的内容呢? 使用 map::find 和 map::end: if (m.find("f") == m.end()) { // not found } else { // found } 要检查映射中是否存在特定键,请通过以下方式之一使用 count 成员函数: m.count(key) > 0 m.count(key) == 1 m.count(key) != 0 map::find的文档说:“另一个成员函数map::count可用于仅检查特定键是否存在。” map::count的文档说:“因为地图容器中的所有元素都是唯一的,所以该函数只能返回1(如果找到该元素)或零(否则)。” 要通过您知道存在的键从映射中检索值,请使用 map::at: value = m.at(key) 与 map::operator[] 不同,如果指定的键不存在,map::at 不会在映射中创建新键。 C++20 为我们提供了 std::map::contains 来做到这一点。 #include <iostream> #include <string> #include <map> int main() { std::map<int, std::string> example = {{1, "One"}, {2, "Two"}, {3, "Three"}, {42, "Don\'t Panic!!!"}}; if(example.contains(42)) { std::cout << "Found\n"; } else { std::cout << "Not found\n"; } } 您可以使用.find(): map<string,string>::iterator i = m.find("f"); if (i == m.end()) { /* Not found */ } else { /* Found, i->first is f, i->second is ++-- */ } C++17 通过带有初始化器的 If 语句进一步简化了这一点。 这样你就可以鱼与熊掌兼得了。 if ( auto it{ m.find( "key" ) }; it != std::end( m ) ) { // Use `structured binding` to get the key // and value. const auto&[ key, value ] { *it }; // Grab either the key or value stored in the pair. // The key is stored in the 'first' variable and // the 'value' is stored in the second. const auto& mkey{ it->first }; const auto& mvalue{ it->second }; // That or just grab the entire pair pointed // to by the iterator. const auto& pair{ *it }; } else { // Key was not found.. } m.find == m.end() // not found 如果您想使用其他API,请找到m.count(c)>0 if (m.count("f")>0) cout << " is an element of m.\n"; else cout << " is not an element of m.\n"; 我想你想要map::find。如果 m.find("f") 等于 m.end(),则未找到密钥。否则,find 返回一个指向找到的元素的迭代器。 错误是因为p.first是一个迭代器,它不适用于流插入。将最后一行更改为 cout << (p.first)->first;。 p 是一对迭代器,p.first 是迭代器,p.first->first 是键字符串。 一张地图对于给定的键只能有一个元素,所以 equal_range 不是很有用。它是为映射定义的,因为它是为所有关联容器定义的,但它对于多重映射更有趣。 template <typename T, typename Key> bool key_exists(const T& container, const Key& key) { return (container.find(key) != std::end(container)); } 当然,如果你想变得更奇特,你可以随时模板化一个函数,该函数也采用已找到的函数和未找到的函数,如下所示: template <typename T, typename Key, typename FoundFunction, typename NotFoundFunction> void find_and_execute(const T& container, const Key& key, FoundFunction found_function, NotFoundFunction not_found_function) { auto& it = container.find(key); if (it != std::end(container)) { found_function(key, it->second); } else { not_found_function(key); } } 并像这样使用它: std::map<int, int> some_map; find_and_execute(some_map, 1, [](int key, int value){ std::cout << "key " << key << " found, value: " << value << std::endl; }, [](int key){ std::cout << "key " << key << " not found" << std::endl; }); 这样做的缺点是想出一个好名字,“find_and_execute”很尴尬,我想不出更好的名字...... map<string, string> m; 检查 key 是否存在,并返回出现次数(map 中为 0/1): int num = m.count("f"); if (num>0) { //found } else { // not found } 检查key是否存在,并返回迭代器: map<string,string>::iterator mi = m.find("f"); if(mi != m.end()) { //found //do something to mi. } else { // not found } 在你的问题中,由坏的operator<<过载引起的错误,因为p.first是map<string, string>,你无法打印出来。尝试这个: if(p.first != p.second) { cout << p.first->first << " " << p.first->second << endl; } 小心地将查找结果与地图“m”的结尾进行比较,因为所有答案都有 上面完成 地图::迭代器 i = m.find("f"); if (i == m.end()) { } else { } 您不应该尝试执行任何操作,例如如果迭代器 i 等于 m.end() 则打印键或值,否则会导致分段错误。 比较 std::map::find 和 std::map::count 的代码,我认为第一个可能会产生一些性能优势: const_iterator find(const key_type& _Keyval) const { // find an element in nonmutable sequence that matches _Keyval const_iterator _Where = lower_bound(_Keyval); // Here one looks only for lower bound return (_Where == end() || _DEBUG_LT_PRED(this->_Getcomp(), _Keyval, this->_Key(_Where._Mynode())) ? end() : _Where); } size_type count(const key_type& _Keyval) const { // count all elements that match _Keyval _Paircc _Ans = equal_range(_Keyval); // Here both lower and upper bounds are to be found, which is presumably slower. size_type _Num = 0; _Distance(_Ans.first, _Ans.second, _Num); return (_Num); } find() 和 contains() 都可以使用。根据文档。两种方法平均时间为常数,最坏情况下为线性时间。 我知道这个问题已经有一些很好的答案,但我认为我的解决方案值得分享。 它适用于 std::map 和 std::vector<std::pair<T, U>>,并且可从 C++11 开始使用。 template <typename ForwardIterator, typename Key> bool contains_key(ForwardIterator first, ForwardIterator last, Key const key) { using ValueType = typename std::iterator_traits<ForwardIterator>::value_type; auto search_result = std::find_if( first, last, [&key](ValueType const& item) { return item.first == key; } ); if (search_result == last) { return false; } else { return true; } } map <int , char>::iterator itr; for(itr = MyMap.begin() ; itr!= MyMap.end() ; itr++) { if (itr->second == 'c') { cout<<itr->first<<endl; } } 如果你想比较成对的地图,你可以使用这个方法: typedef map<double, double> TestMap; TestMap testMap; pair<map<double,double>::iterator,bool> controlMapValues; controlMapValues= testMap.insert(std::pair<double,double>(x,y)); if (controlMapValues.second == false ) { TestMap::iterator it; it = testMap.find(x); if (it->second == y) { cout<<"Given value is already exist in Map"<<endl; } } 这是一项有用的技术。


Valgrind:仅对于较大的输入值,地址 0x0 不会被堆栈、分配或(最近)释放

我正在尝试实现 Dijikstra,这是我拥有的图形生成代码 #包括 #包括 #包括 #包括 我正在尝试实现 Dijikstra,这是我拥有的图形生成代码 #include <stdlib.h> #include <stdio.h> #include <limits.h> #include <math.h> #define MAX 300 int main (int argc, char *argv[]){ int v = atoi(argv[1]); int SIZE = v*v; int* adjMatrix = malloc(sizeof(int)* SIZE); graphGeneration(adjMatrix, v); free(adjMatrix); return 0; } void graphGeneration(int* adj, int numV){ int i, j, r; for(i = 0; i< numV; i++){ for(j=0; j < numV; j++){ if(i == j){ adj[i * numV + j] = 0; } else{ r = rand() % MAX; adj[i * numV + j] = r; adj[j * numV + i] = r; } } } } 当我尝试输入 1000 的 v 值时,它似乎工作正常,但是当我尝试输入 v = 10,000+ 的值时,我遇到了段错误(特别是我注意到的数字是 50,000)。运行 valgrind 会导致我在该方法的标题中出现错误。 为了方便起见,重新发布在这里: Invalid write of size 4 at 0x400800: graphGeneration by 0x4006E3: main Address 0x0 is not stack'd, malloc'd or (recently) free'd Access not within mapped region at address 0x0 有人对如何调试这个有任何想法或者这里是否有任何明显的错误? 我也在 valgrind 中注意到了这一点 Warning: silly arg (-7179869184) to malloc() 我不确定这是否相关,但这似乎也是一件奇怪的事情。 看看一些 malloc() 手册:它的参数是 size_t 类型是有原因的。 int 不能保证容纳任何可能的对象大小,size_t 可以。顺便说一句,它是无符号的——负大小没有多大意义。 所以就写吧 size_t SIZE = ((size_t)v) * v; 因为你的 v 是一个 int 你必须通过强制转换参数之一来强制这个乘法作为 size_t 完成。 稍微好一点的方法是将 v 制作为 unsigned long 并使用 strtoul() 代替 atoi()。 然后,在使用之前检查您的malloc()的结果。即使使用正确的大小参数,它仍然可能返回 NULL。如果是这样,这仅仅意味着您当时没有足够的可用内存。 毕竟,使用 v=10000 并假设 int 占用四个字节(这很常见),您已经尝试一次分配 400 MB。 他是中本聪..但是这是构建项目的投资组合 不要试图理解这一点..这会让你很快发疯..


© www.soinside.com 2019 - 2024. All rights reserved.