question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I have this gauge metric "metric_awesome" from two different instances. What i want to do, is subtract instance one from instance two like so metric_awesome{instance="one"} - metric_awesome{instance="two"} Unfortunately the result set is empty. Has anyone experienced this?
The issue here is that the labels don't match. What you want is: metric_awesome{instance="one"} - ignoring(instance) metric_awesome{instance="two"}
Prometheus
45,005,524
27
Because Prometheus topk returns more results than expected, and because https://github.com/prometheus/prometheus/issues/586 requires client-side processing that has not yet been made available via https://github.com/grafana/grafana/issues/7664, I'm trying to pursue a different near-term work-around to my similar proble...
If you're confused by brian's answer: The result of filtering with a comparison operator is not a boolean, but the filtered series. E.g. min(flink_rocksdb_actual_delayed_write_rate > 0) Will show the minimum value above 0. In case you actually want a boolean (or rather 0 or 1), use something like sum (flink_rocksdb_ac...
Prometheus
46,697,754
26
I am unable to identify what the exact issue with the permissions with my setup as shown below. I've looked into all the similar QAs but still unable to solve the issue. The aim is to deploy Prometheus and let it scrape /metrics endpoints that my other applications in the cluster expose fine. Failed to watch *v1.Endpoi...
User "system:serviceaccount:default:default" cannot list resource "endpoints" in API group "" at the cluster scope" User "system:serviceaccount:default:default" cannot list resource "pods" in API group "" at the cluster scope" User "system:serviceaccount:default:default" cannot list resource "services" in API grou...
Prometheus
67,151,953
25
I am trying out Prometheus on Mac OS X. I looked up the downloads and not having a direct indication of which version is for Mac. I tried docker to run the Prometheus on Mac. Just want to run it directly on Mac without docker. Does any one know which version to pick. There were few BSDs there for pick. I know Mac is a...
The downloads page has a build for Darwin on amd64. To quote the wikipedia page: Darwin forms the core set of components upon which macOS (previously OS X and Mac OS X), iOS, watchOS, and tvOS are based. This is the official binary for OSX. Other methods (such as brew install prometheus are also available).
Prometheus
48,433,869
24
How do you export and import data in Prometheus? How do you make sure the data is backed up if the instance gets down? It does not seem that there is a such feature yet, how do you do then?
There is no export and especially no import feature for Prometheus. If you need to keep data collected by prometheus for some reason, consider using the remote write interface to write it somewhere suitable for archival, such as InfluxDB (configured as a time-series database). Prometheus isn't a long term storage: if t...
Prometheus
46,348,758
24
How can I find the overall average of metrics over time interval ? avg(metric) = overall average value but avg_over_time(metrics[interval]) = averages value per label avg( avg_over_time(metric[scrape interval]) ) won't be same as(when the data is not continuous and denominator value is different) avg(metric) !!!! Give...
You need to calculate the average a bit more manually: sum(sum_over_time(metric[interval])) / sum(count_over_time(metric[interval])) Note that this is for data in a gauge, you'd need a different approach for data from a counter or summary.
Prometheus
51,859,464
23
I have read that Spark does not have Prometheus as one of the pre-packaged sinks. So I found this post on how to monitor Apache Spark with prometheus. But I found it difficult to understand and to success because I am beginner and this is a first time to work with Apache Spark. First thing that I do not get is what I n...
There are few ways to monitoring Apache Spark with Prometheus. One of the way is by JmxSink + jmx-exporter Preparations Uncomment *.sink.jmx.class=org.apache.spark.metrics.sink.JmxSink in spark/conf/metrics.properties Download jmx-exporter by following link on prometheus/jmx_exporter Download Example prometheus confi...
Prometheus
49,488,956
23
How can I create a receiver configuration with multiple email addresses in the "to" field?
You can put comma separated email addresses in the to field. to: 'user1@example.com, user2@example.com'
Prometheus
47,921,028
23
I have container_fs_usage_bytes with prometheus to monitor container root fs, but it seems that there is no metrics for other volumes in cAdvisor.
I confirmed that Kubernetes 1.8 expose metrics for prometheus. kubelet_volume_stats_available_bytes kubelet_volume_stats_capacity_bytes kubelet_volume_stats_inodes kubelet_volume_stats_inodes_free kubelet_volume_stats_inodes_used kubelet_volume_stats_used_bytes
Prometheus
44,718,268
23
Failed to create clusterroles. <> already assigned as the roles of "container engine admin" & "container engine cluster admin" Error from server (Forbidden): error when creating "prometheus- operator/prometheus-operator-cluster-role.yaml": clusterroles.rbac.authorization.k8s.io "prometheus-operator" is forbidden: attem...
I've got the same problem on Google Kubernetes Engine. According to the answer of enj and the comment of ccyang2005 please find the following snipet who solve my problem :) Step 1 : Get your identity gcloud info | grep Account Will output you something like Account: [myname@example.org] Step 2 : grant cluster-admin to...
Prometheus
44,349,987
23
I run a v1.9.2 custom setup of Kubernetes and scrape various metrics with Prometheus v2.1.0. Among others, I scrape the kubelet and cAdvisor metrics. I want to answer the question: "How much of the CPU resources defined by requests and limits in my deployment are actually used by a pod (and its containers) in terms of ...
We're using the container_cpu_usage_seconds_total metric to calculate Pod CPU usage. This metrics contains the total amount of CPU seconds consumed by container by core (this is important, as a Pod may consist of multiple containers, each of which can be scheduled across multiple cores; however, the metric has a pod_na...
Prometheus
48,872,042
22
Background I have installed Prometheus on my Kubernetes cluster (hosted on Google Container Engineer) using the Helm chart for Prometheus. The Problem I cannot figure out how to add scrape targets to the Prometheus server. The prometheus.io site describes how I can mount a prometheus.yml file (which contains a list of ...
You need to add annotations to the service you want to monitor. apiVersion: v1 kind: Service metadata: annotations: prometheus.io/scrape: 'true' From the prometheus.yml in the chart: prometheus.io/scrape: Only scrape services that have a value of true prometheus.io/scheme: http or https prometheus.io/path: ove...
Prometheus
45,613,660
22
I have articles and for each article I want to have read count # TYPE news_read_counter2 Counter news_read_counter2{id="2000"} 168 now the counters on the servers are saved in redis\memcached so they can get reset from time to time so after a while the redis machine is restart and the server dont have the last news_re...
Counters are allowed to be reset to 0, so there's no need to do anything special here to handle it. See http://www.robustperception.io/how-does-a-prometheus-counter-work/ for more detail. It's recommended to use a client library which will handle all of this for you. Also, by convention you should suffix counters with ...
Prometheus
37,548,412
22
On my ActiveMQ I have some Queues, which end with .error. On a Grafana Dashboard I want to list all queues without these .error-queues. Example: some.domain.one some.domain.one.error some.domain.two some.domain.two.error To list all queues I use this query: org_apache_activemq_localhost_QueueSize{Type="Queue",Destinat...
You can use a negative regex matcher: org_apache_activemq_localhost_QueueSize{Type="Queue",Destination=~"some.domain.*",Destination!~".*\.error"}
Prometheus
40,277,612
20
We graph fast counters with sum(rate(my_counter_total[1m])) or with sum(irate(my_counter_total[20s])). Where the second one is preferrable if you can always expect changes within the last couple of seconds. But how do you graph slow counters where you only have some increments every couple of minutes or even hours? Hav...
That's a correct way to do it. You can also use increase() which is syntactic sugar for using rate() that way. Can someone explain how the range selector This is only used by Prometheus, and indicates what data to work over. the Step and Resolution settings in grafana influence each other? This is used on the Graf...
Prometheus
38,659,784
20
How do I write a query that outputs average memory usage for instances over the past 24 hours? The following query displays the current memory usage 100 * (1 - ((node_memory_MemFree + node_memory_Cached + node_memory_Buffers) / node_memory_MemTotal)) For CPU, I was able to use irate 100 * (1 - avg(irate(node_cpu[24h])...
average memory usage for instances over the past 24 hours You can use avg_over_time: 100 * (1 - ((avg_over_time(node_memory_MemFree[24h]) + avg_over_time(node_memory_Cached[24h]) + avg_over_time(node_memory_Buffers[24h])) / avg_over_time(node_memory_MemTotal[24h]))) For CPU, I was able to use irate irate only look...
Prometheus
48,835,035
20
I'm trying to apply Prometheus metrics using the micrometer @Timed annotations. I found out that they only work on controller endpoints and not "simple" public and private methods. Given this example: @RestController public class TestController { @GetMapping("/test") @Timed("test-endpoint") //does create prome...
@Timed works only on public methods called by another class. Spring Boot annotations like @Timed / @Transactional need the so-called proxying which happens only between invocations of public methods. A good explanation is this one https://stackoverflow.com/a/3429757/2468241
Prometheus
71,587,610
19
We are getting to grips with alerting so from time to time need to clear out old alerts which we did by calling the HTTP API, to remove the pseudo time series where the alerts were stored, e.g.: DELETE https://prometheus/api/v1/series?match[]={__name__="ALERTS"} We have recently upgraded our Prometheus server from 1.8...
Firstly the admin API is not enabled by default in Prometheus 2. This must be made active by starting the server with the option --web.enable-admin-api There is a new endpoint in v2 at https://prometheus/api/v2/admin/tsdb/delete_series This takes a POST specifying the search criteria, e.g. for a time series with the ...
Prometheus
49,859,360
19
For a particular job in Prometheus, it seems like the typical config is something like this: static_configs: - targets: ['localhost:9090'] But in the case where I want a dynamic list of hosts, what would be the approach there? I was looking at scrape_config but that doesn't seem to accomplish what I'm after (unless I'...
There are several ways of providing dynamic targets to your Prometheus. Please refer the link here Some of them are: azure_sd_config (for AzureVM metrics) consul_sd_config (for Consul's Catalog API) dns_sd_config (DNS-based service discovery) ec2_sd_config (for AWS EC2 instances) openstack_sd_config (for Openstack Nov...
Prometheus
46,916,328
19
I am new to Prometheus and Grafana. My primary goal is to get the response time per request. For me it seemed to be a simple thing - but whatever I do I do not get the results I require. I need to be able to analyse the service latency in the last minutes/hours/days. The current implementation I found was a simple SUMM...
Your query is correct. The result will be NaN if there have been no queries in the past minute.
Prometheus
47,305,424
18
Small question regarding Spring Boot, some of the useful default metrics, and how to properly use them in Grafana please. Currently with a Spring Boot 2.5.1+ (question applicable to 2.x.x.) with Actuator + Micrometer + Prometheus dependencies, there are lots of very handy default metrics that come out of the box. I am ...
UPD 2022/11: Recently I've had a chance to work with these metrics myself and I made a dashboard with everything I say in this answer and more. It's available on Github or Grafana.com. I hope this will be a good example of how you can use these metrics. Original answer: count and sum are generally used to calculate an ...
Prometheus
67,964,176
18
I have a Grafana dashboard with template variables for services and instances. When I select a service how can I make it filter the second template variable list based on the first?
You can reference the first variable in the second variables query. I'm not certain if there is a way using the label_values helper though. First variable query: up regex: /.*app="([^"]*).*/ Second variable: query: up{app="$app"} regex: /.*instance="([^"]*).*/
Prometheus
41,773,162
18
I have a new server running Prometheus in docker-compose. I want to be able to re-load the configuration file (prometheus.yml) without have to stop and start the container. Of course since I persist the storage of promethues in a volume the stop and start isn't really a problem but it seems like overkill, especially s...
docker-compose kill -s SIGHUP prometheus does the trick, so Vishrant was certainly on to something there.
Prometheus
56,585,607
18
I know that CPU utilization is given by the percentage of non-idle time over the total time of CPU. In Prometheus, rate or irate functions calculate the rate of change in a vector array. People often calculate the CPU utilisation by the following PromQL expression: (100 - (avg by (instance) (rate(node_cpu_seconds_tota...
There are a couple of things to unwrap here. First, rate vs irate. Neither the linked question, nor the blog post address this (but Eitan's answer does touch on it). The difference is that rate estimates the average rate over the requested range (1 minute, in your case) while irate computes the rate based on the last 2...
Prometheus
55,556,051
18
Application was working correctly with version 2.2.6 but as the application is upgraded to latest version of spring boot 2.3.0 it stopped working and fails during startup. 2020-05-20T08:43:04.408+01:00 [APP/PROC/WEB/0] [OUT] 2020-05-20 07:43:04.407 ERROR 15 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error st...
In your particular case the micrometer-registry-prometheus must be in-line with spring boot's micrometer-core's version. It is 1.5.1 because Spring Boot (Actuator) pulls that dependency in with version 2.3.0. dependencies { implementation group: 'io.micrometer', name: 'micrometer-registry-prometheus', version: '1.5.1...
Prometheus
61,908,419
17
Hi everyone, I have deployed a Kubernetes cluster based on kubeadm and for the purpose of performing HorizontalPodAutoscaling based on the Custom Metrics, I have deployed prometheus-adpater through Helm. Now, i want to edit the configuration for prometheus-adpater and because i am new to Helm, i don't know how to do th...
I guess helm upgrade is that are you looking for. This command upgrades a release to a specified version of a chart and/or updates chart values. So if you have deployed prometheus-adapter, you can use command helm fetch Download a chart from a repository and (optionally) unpack it in local directory You will have ...
Prometheus
58,256,871
17
I'm using the official stable/prometheus-operator chart do deploy Prometheus with helm. It's working good so far, except for the annoying CPUThrottlingHigh alert that is firing for many pods (including the own Prometheus' config-reloaders containers). This alert is currently under discussion, and I want to silence it...
One option is to route alerts you want silenced to a "null" receiver. In alertmanager.yaml: route: # Other settings... group_wait: 0s group_interval: 1m repeat_interval: 1h # Default receiver. receiver: "null" routes: # continue defaults to false, so the first match will end routing. - match: ...
Prometheus
54,806,336
17
We are about to setup Prometheus for monitoring and alerting for our cloud services including a continous integration & deployment pipeline for the Prometheus service and configuration like alerting rules / thresholds. For that I am thinking about 3 categories I want to write automated tests for: Basic syntax checks f...
New version of Prometheus (2.5) allows to write tests for alerts, here is a link. You can check points 1 and 2. You have to define data and expected output (for example in test.yml): rule_files: - alerts.yml evaluation_interval: 1m tests: # Test 1. - interval: 1m # Series data. input_series: - series: 'up...
Prometheus
46,589,949
17
Because Prometheus only supports text metrics and many tool return metrics in json (like Finatra, Spring Boot), I created a simple proxy which translates the json into text. Because I want to use it for multiple sources, the target from which the actual metrics are to be retrieved is set via a query param. The metrics ...
This behaviour is correct, as the metrics path is a path - not an arbitrary suffix on the protocol, host and port. You're looking for the params configuration option: scrape_configs: - job_name: 'somename' params: prefix: ['finatra'] url: ['http://:9090/admin/metrics.json']
Prometheus
40,172,415
17
I have configured grafana dashboard to monitor promethus metrics for some of the spring boot services. I have a single panel and a prom query for every service on it. Now I want to add alerts for each on of those queries. But I couldn't find a way to add multiple alerts on single panel. I could add only only for one of...
You can specify the query that the alert threshold is evaluating within the 'conditions' but it will still be just one alert. As such your Alert message won't include anything to distinguish which specific query condition triggered the alert, it's just whatever text is in the box (AFAIK there's not currently any way to...
Prometheus
63,245,770
16
I have a Grafana dashboard panel configured to render the results of a Prometheus query. There are a large number of series returned by the query, with the legend displayed to the right. If the user is looking for a specific series, they have to potentially scroll through all of them, and it's easy to miss the one they...
As far as I know, You can only use the function sort() to sort metrics by value. According to this PR, Prometheus does not intend to provide the function sort_by_label(). According to this Issue, Grafana displays the query results from Prometheus without sorting. According to this Issue, Grafana supports sorting by va...
Prometheus
64,395,442
16
I am currently trying to migrate our prometheus lib to spring boot 2.0.3.RELEASE. We use a custom path for prometheus and so far we use a work around to ensure this. As there is the possibility for a custom path for the info- and health-endpoint, uses management.endpoint.<health/info>.path. I tried to specify manageme...
From the reference documentation: By default, endpoints are exposed over HTTP under the /actuator path by using the ID of the endpoint. For example, the beans endpoint is exposed under /actuator/beans. If you want to map endpoints to a different path, you can use the management.endpoints.web.path-mapping property. Als...
Prometheus
51,195,237
16
I'm trying to calculate easter sunday in PromQL using Gauss's Easter algorithm (I need to ignore some alert rules on public holidays). I can calculate the day, but I'm having a problem with the month as I need something like an if/else expression. My recording rule easter_sunday_in_april returns 1 if eastern is in apr...
The if(easter_sunday_in_april > 0) return 4 else return 3 can be expressed as the following PromQL query: (vector(4) and on() (easter_sunday_in_april > 0)) or on() vector(3) It uses and and or logical operators and on() modifier. P.S. This query can be expressed in more easy-to-understand form with MetricsQL ...
Prometheus
64,204,913
16
Consider a Prometheus metric foo_total that counts the total amount of occurences of an event foo, i.e. the metric will only increase as long as the providing service isn't restarted. Is there any way to get the timespan (e.g. amount of seconds) since the last increase of that metric? I know that due to the scrape peri...
Below is the JSON for a Singlestat panel that will display the time of the last update to the up{job="prometheus"} metric. This is not exactly what you asked for: it's the last time rather than the timespan since; it's only useful as a Singlestat panel (i.e. you can't take the value and graph it since it's not a single...
Prometheus
54,148,451
16
I would like to install Prometheus on port 8080 instead of 9090 (its normal default). To this end I have edited /etc/systemd/system/prometheus.service to contain this line: ExecStart=/usr/local/bin/prometheus \ --config.file=/etc/prometheus.yaml --web.enable-admin-api \ --web.listen-address=":8080" I.e., I am usi...
The quotes were superfluous. This line will work: ExecStart=/usr/local/bin/prometheus \ --config.file=/etc/prometheus.yaml --web.enable-admin-api \ --web.listen-address=:8080
Prometheus
47,414,593
16
I have a multi-container pod in my kubernetes deployment: java redis nginx For every of those containers, there's a container with Prometheus exporter as well. The question is how can I expose those ports to Prometheus if annotations section supports only one port per pod? annotations: prometheus.io/scrape: 'true'...
Here's an example job for Prometheus. Put it in your own config. Next, add: annotations: prometheus.io/scrape: 'true' to your pod metadata. And on every container, which provides /metrics to prom, create an appropriate port, named metrics. That's it. Prometheus would scrape only those ports, and there would be no s...
Prometheus
43,121,132
16
Is there a way to send logs to Loki directly without having to use one of it's agents? For example, if I have an API, is it possible to send request/response logs directly to Loki from an API, without the interference of, for example, Promtail?
Loki HTTP API Loki HTTP API allows pushing messages directly to Grafana Loki server: POST /loki/api/v1/push /loki/api/v1/push is the endpoint used to send log entries to Loki. The default behavior is for the POST body to be a snappy-compressed protobuf message: Protobuf definition Go client library Alternatively, if...
Prometheus
67,316,535
15
I am trying to generate Prometheus metrics with using Micrometer.io with Spring Boot 2.0.0.RELEASE. When I am trying to expose the size of a List as Gauge, it keeps displaying NaN. In the documentation it says that; It is your responsibility to hold a strong reference to the state object that you are measuring with a...
In all cases, you must hold a strong reference to the observed instance. When your createGauge() method is exited, all function stack allocated references are eligible for garbage collection. For #1, pass your atomicInteger field like this: registry.gauge("my_ai", atomicInteger);. Then increment/decrement as you wish. ...
Prometheus
50,821,924
15
I am a little unclear on when to exactly use increase and when to use sum_over_time in order to calculate a periodic collection of data in Grafana. I want to calculate the total percentage of availability of my system. Thanks.
The "increase" function calculates how much a counter increased in the specified interval. The "sum_over_time" function calculates the sum of all values in the specified interval. Suppose you have the following data series in the specified interval: 5, 5, 5, 5, 6, 6, 7, 8, 8, 8 Then you would get: increase = 8-5 = 3 s...
Prometheus
63,289,864
15
First off a little new to using helm... So I'm struggling to get the helm deployment of this: https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack To work the way I would like in my kubernetes cluster. I like what it has done so far but how can I make it scrape a custom endpoint? I...
Try this below in your custom_values.yaml and apply it. prometheus: prometheusSpec: additionalScrapeConfigs: - job_name: your_job_name scrape_interval: 15s kubernetes_sd_configs: - role: pod namespaces: names: - your_namespace relabel_confi...
Prometheus
64,452,966
15
In a prometheus alert rule, how do I check for a value to be in a certain range? for eg., (x > 80 && x <= 100); when x is a complex expression it feels unnecessary to evaluate it twice. is there another way to represent this expression?
You can do x < 100 > 80 to chain them.
Prometheus
45,766,533
15
I wish to push a multi-labeled metric into Prometheus using the Pushgateway. The documentation offer a curl example but I need it sent via Python. In addition, I'd like to embed multiple labels into the metric.
First step: Install the client: pip install prometheus_client Second step: Paste the following into a Python interpreter: from prometheus_client import CollectorRegistry, Gauge, push_to_gateway registry = CollectorRegistry() g = Gauge('job_last_success_unixtime', 'Last time a batch job successfully finished', registr...
Prometheus
40,989,737
15
I used Prometheus to measure business metrics like: # HELP items_waiting_total Total number of items in a queue # TYPE items_waiting_total gauge items_waiting_total 149 I would like to keep this data for very long term (5 years retention) and I don't need high frequency in scrape_interval. So I set up scrape_interval:...
It's not advisable to go above about 2 minutes. This is as staleness is 5 minutes by default (which is what's causing the gaps), and you want to allow for a failed scrape.
Prometheus
40,230,057
15
I have been able to obtain the metrices by sending an HTTP GET as follows: # TYPE net_conntrack_dialer_conn_attempted_total untyped net_conntrack_dialer_conn_attempted_total{dialer_name="federate",instance="localhost:9090",job="prometheus"} 1 1608520832877 Now I need to parse this data and obtain control over every pi...
There's a nice package already available to do that and it's by the Prometheus's Authors itself. They have written a bunch of Go libraries that are shared across Prometheus components and libraries. They are considered internal to Prometheus but you can use them. Refer: github.com/prometheus/common doc. There's a packa...
Prometheus
65,388,098
14
I am using counters to count the number of requests. Is there any way to get current value of a prometheus counter? My aim is to reuse existing counter without allocating another variable. Golang prometheus client version is 1.1.0.
It's easy, have a function to fetch Prometheus counter value import ( "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/log" ) func GetCounterValue(metric *prometheus.CounterVec) float64 { var m = &dto.Metric{} if err := metr...
Prometheus
57,952,695
14
I have activated the spring actuator prometheus endpont /actuator/prometheus. By adding the dependencies for micrometer and actuator and enabled prometheus endpont. How can i get there custom metrics?
You'll need to register your metrics with the Micrometer Registry. The following example creates the metrics in the constructor. The Micrometer Registry is injected as a constructor parameter: @Component public class MyComponent { private final Counter myCounter; public MyComponent(MeterRegistry registry) {...
Prometheus
50,406,296
14
I have below labels in prometheus, how to create wildcard query while templating something like “query”: “label_values(application_*Count_Total,xyx)” . These values are generated from a Eclipse Microprofile REST-API application_getEnvVariablesCount_total application_getFEPmemberCount_total application_getLOBDetailsCoun...
Prometheus treats metric names the same way as label values with a special label - __name__. So the following query should select all the values for label xyx across metrics with names matching application_.*Count_total regexp: label_values({__name__=~"application_.*Count_total"}, xyx)
Prometheus
59,684,225
13
I'm looking at Prometheus metrics in a Grafana dashboard, and I'm confused by a few panels that display metrics based on an ID that is unfamiliar to me. I assume that /kubepods/burstable/pod99b2fe2a-104d-11e8-baa7-06145aa73a4c points to a single pod, and I assume that /kubepods/burstable/pod99b2fe2a-104d-11e8-baa7-0614...
OK, now that I've done some digging around, I'll attempt to answer all 3 of my own questions. I hope this helps someone else. How to do I map this ID to the pod name I see when I run kubectl get pods? Given the following, /kubepods/burstable/pod99b2fe2a-104d-11e8-baa7-06145aa73a4c, the last bit is the pod UID, and can ...
Prometheus
49,035,724
13
I'm transforming a Spring Boot application from Spring Boot 1 (with the Prometheus Simpleclient) to Spring Boot 2 (which uses Micrometer). I'm stumped at transforming the labels we have with Spring Boot 1 and Prometheus to concepts in Micrometer. For example (with Prometheus): private static Counter requestCounter = ...
Further digging showed that only the keys of micrometer tags have to be predeclared - but the constructor really takes pairs of key/values; the values don't matter. And the keys have to be specified when using the metric. This works: private static final String COUNTER_BATCHMANAGER_SENT_REQUESTS = "batchmanager.sent.re...
Prometheus
49,170,093
13
Use helm installed Prometheus and Grafana on minikube at local. $ helm install stable/prometheus $ helm install stable/grafana Prometheus server, alertmanager grafana can run after set port-forward: $ export POD_NAME=$(kubectl get pods --namespace default -l "app=prometheus,component=server" -o jsonpath="{.items[0].me...
In the HTTP settings of Grafana you set Access to Proxy, which means that Grafana wants to access Prometheus. Since Kubernetes uses an overlay network, it is a different IP. There are two ways of solving this: Set Access to Direct, so the browser directly connects to Prometheus. Use the Kubernetes-internal IP or domai...
Prometheus
48,338,122
13
I have a Spring boot app throwing out open metric stats using micrometer. For each of my HTTP endpoints, I can see the following metric which I believe tracks the number of requests for the given endpoint: http_server_requests_seconds_count My question is how do I use this in a Grafana query to present the number numbe...
rate(http_client_requests_seconds_count{}[1m]) will provide you the number of request your service received at a per-second rate. However by using [1m] it will only look at the last minute to calculate that number, and requires that you collect samples at a rate quicker than a minute. Meaning, you need to have collecte...
Prometheus
66,282,512
13
In the below promQL query execution: "Resolution" is mentioned as 14 seconds and "total time series" is mentioned as 1 What does "resolution" with value 14 seconds mean? What is "time series"? What does "time series" with value 1 mean? What does "load time" indicate?
Resolution is the distance (in time) between points on the graph. 14s was automatically selected based on your query duration (which you've set to 1 hour). This resolution does not necessarily line up with the "real" samples, you can think of it as a sensible interpretation of your data for the given amount of time. F...
Prometheus
69,620,345
13
I have an application that will be monitored by Prometheus, but the application need the custom header key like : x-auth-token: <customrandomtoken> What should I do with prometheus.yml?
Prometheus itself does not have a way to define custom headers in order to reach an exporter. The idea of adding the feature was discussed in this GitHub issue. Tl;dr: if you need a custom header, inject it with a forward proxy (I posted an example in another answer). The prometheus-blackbox-exporter tag suggest that t...
Prometheus
66,032,498
13
This is the official prometheus golang-client example: package main import ( "log" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "cpu_temperature_celsius", ...
We just utilize promhttp handler. package main import ( "github.com/gin-gonic/gin" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) var cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{ Name: "cpu_temperature_celsius", Help: "Current te...
Prometheus
65,608,610
13
We have two different teams working on different applications.I would like send alert notifications to different slack channels via using same alerts expressions. I found some examples but not understand what is the main reason to use receiver: 'default' when try to add new route? What is the role of this and what if i...
You need to set the continue property on your route to true. By default it is false. The default behaviour of AlertManager is to traverse your routes for a match and exit at the first node it finds a match at. What you want to do is fire an alert at the match and continue to search for other matches and fire those too....
Prometheus
62,672,730
13
What's the difference between probe_success and up? I see various examples where alerting is done based on either of them (eg. site down, instance down). Am I missing something?
up indicates whether Prometheus could talk to and successfully scrape a target, such as the blackbox exporter. probe_success is a metric exposed by the blackbox exporter indicating if a probe succeeded. For alerting you need both, as if the blackbox exporter is down or timing out then that's indicated by up and if the ...
Prometheus
51,984,837
13
For Prometheus metrics collection, like title, I could not really find a use case which only can be done via the type Summary, seems that they all somehow can be done via the type Histogram also. Lets take the request concurrency metrics as example, no doubt this can be perfectly done via type Summary, but i can also a...
The Summary metric is not unique, many other instrumentation systems offer similar - such as Dropwizard's Histogram type (it's a histogram internally, but exposed as a quantile). This is one reason it exists, so such types from other instrumentation systems can be mapped more cleanly. Another reason it exists is histor...
Prometheus
51,146,578
13
I have a question about calculating response times with Prometheus summary metrics. I created a summary metric that does not only contain the service name but also the complete path and the http-method. Now I try to calculate the average response time for the complete service. I read the article about "rate then sum" a...
All of these examples are aggregating incorrectly, as you're averaging an average. You want: sum without (path,host) ( rate(request_duration_sum{status_code=~"2.*"}[5m]) ) / sum without (path,host) ( rate(request_duration_count{status_code=~"2.*"}[5m]) ) Which will return the average latency per status...
Prometheus
51,064,821
13
What is the meaning of =~ operator in prometheus metrics? Can any help me what is the exact difference between = and =~ operator? for ex . process_cpu_seconds_total{instance="test"} process_cpu_seconds_total{instance=~"test"} The results are different.
"=~: Select labels that regex-match the provided string (or substring). For example, this selects all http_requests_total time series for staging, testing, and development environments and HTTP methods other than GET." http_requests_total{environment=~"staging|testing|development",method!="GET"} Taken from the Prometh...
Prometheus
47,473,363
13
Why is Java Vector considered a legacy class, obsolete or deprecated? Isn't its use valid when working with concurrency? And if I don't want to manually synchronize objects and just want to use a thread-safe collection without needing to make fresh copies of the underlying array (as CopyOnWriteArrayList does), then is ...
Vector synchronizes on each individual operation. That's almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing ...
Vector
1,386,275
747
I can create an array and initialize it like this: int a[] = {10, 20, 30}; How do I create a std::vector and initialize it similarly elegant? The best way I know is: std::vector<int> ints; ints.push_back(10); ints.push_back(20); ints.push_back(30); Is there a better way?
If your compiler supports C++11, you can simply do: std::vector<int> v = {1, 2, 3, 4}; This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect. Alternatively, the Boost.Assign library uses non-macro magic to allow the following: #include <boost/assign/list_of.hpp...
Vector
2,236,197
723
How to check if a vector contains a given value?
Both the match() (returns the first appearance) and %in% (returns a Boolean) functions are designed for this. v <- c('a','b','c','e') 'b' %in% v ## returns TRUE match('b',v) ## returns the first location of 'b', in this case: 2
Vector
1,169,248
638
I have a vector of numbers: numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435, 453,435,324,34,456,56,567,65,34,435) How can I have R count the number of times a value x appears in the vector?
You can just use table(): > a <- table(numbers) > a numbers 4 5 23 34 43 54 56 65 67 324 435 453 456 567 657 2 1 2 2 1 1 2 1 2 1 3 1 1 1 1 Then you can subset it: > a[names(a)==435] 435 3 Or convert it into a data.frame if you're more comfortable working with that: > as.d...
Vector
1,923,273
490
How do I print out the contents of a std::vector to the screen? A solution that implements the following operator<< would be nice as well: template<container C, class T, String delim = ", ", String open = "[", String close = "]"> std::ostream & operator<<(std::ostream & o, const C<T> & x) { // ... What can I write h...
If you have a C++11 compiler, I would suggest using a range-based for-loop (see below); or else use an iterator. But you have several options, all of which I will explain in what follows. Range-based for-loop (C++11) In C++11 (and later) you can use the new range-based for-loop, which looks like this: std::vector<char>...
Vector
10,750,057
426
What are the differences between the two data structures ArrayList and Vector, and where should you use each of them?
Differences Vectors are synchronized, ArrayLists are not. Data Growth Methods Use ArrayLists if there is no specific requirement to use Vectors. Synchronization If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which modifies the list either structurally or sim...
Vector
2,986,296
418
Suppose I have a std::vector (let's call it myVec) of size N. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, myVec [100000] through myVec [100999] in a vector of size 150000. If this cannot be done efficiently with a vector, is th...
vector<T>::const_iterator first = myVec.begin() + 100000; vector<T>::const_iterator last = myVec.begin() + 101000; vector<T> newVec(first, last); It's an O(N) operation to construct the new vector, but there isn't really a better way.
Vector
421,573
404
Should I use std::sort(numbers.begin(), numbers.end(), std::greater<int>()); or std::sort(numbers.rbegin(), numbers.rend()); // note: reverse iterators to sort a vector in descending order? Are there any benefits or drawbacks with one approach or the other?
With c++14 you can do this: std::sort(numbers.begin(), numbers.end(), std::greater<>());
Vector
9,025,084
404
What are the difference between a std::vector and an std::array in C++? When should one be preferred over another? What are the pros and cons of each? All my textbook does is list how they are the same.
std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perfor...
Vector
4,424,579
396
I need to take a C++ vector with potentially a lot of elements, erase duplicates, and sort it. I currently have the below code, but it doesn't work. vec.erase( std::unique(vec.begin(), vec.end()), vec.end()); std::sort(vec.begin(), vec.end()); How can I correctly do this? Additionally, is it faster to eras...
I agree with R. Pate and Todd Gardner; a std::set might be a good idea here. Even if you're stuck using vectors, if you have enough duplicates, you might be better off creating a set to do the dirty work. Let's compare three approaches: Just using vector, sort + unique sort( vec.begin(), vec.end() ); vec.erase( unique...
Vector
1,041,620
380
Is there something in <algorithm> which allows you to check if a std:: container contains something? Or, a way to make one, for example: if(a.x == b.x && a.y == b.y) return true; return false; Can this only be done with std::map since it uses keys? Thanks
Checking if v contains the element x: #include <algorithm> if(std::find(v.begin(), v.end(), x) != v.end()) { /* v contains x */ } else { /* v does not contain x */ } Checking if v contains elements (is non-empty): if(!v.empty()){ /* v is non-empty */ } else { /* v is empty */ }
Vector
3,450,860
375
What are the good ways of finding the sum of all the elements in a std::vector? Suppose I have a vector std::vector<int> vector with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?
Actually there are quite a few methods. int sum_of_elems = 0; C++03 Classic for loop: for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it; Using a standard algorithm: #include <numeric> sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0); Important...
Vector
3,221,812
365
vector<int> myVector; and lets say the values in the vector are this (in this order): 5 9 2 8 0 7 If I wanted to erase the element that contains the value of "8", I think I would do this: myVector.erase(myVector.begin()+4); Because that would erase the 4th element. But is there any way to erase an element based off ...
How about std::remove() instead: #include <algorithm> ... vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end()); This combination is also known as the erase-remove idiom.
Vector
3,385,229
356
I noticed in Effective STL that vector is the type of sequence that should be used by default. What's does it mean? It seems that ignore the efficiency vector can do anything. Could anybody offer me a scenario where vector is not a feasible option but list must be used?
std::vector std::list Contiguous memory. Non-contiguous memory. Pre-allocates space for future elements, so extra space required beyond what's necessary for the elements themselves. No pre-allocated memory. The memory overhead for the list itself is constant. Each element only requires the space for the ele...
Vector
2,209,224
314
When I multiply two numpy arrays of sizes (n x n)*(n x 1), I get a matrix of size (n x n). Following normal matrix multiplication rules, an (n x 1) vector is expected, but I simply cannot find any information about how this is done in Python's Numpy module. The thing is that I don't want to implement it manually to pre...
Simplest solution Use numpy.dot or a.dot(b). See the documentation here. >>> a = np.array([[ 5, 1 ,3], [ 1, 1 ,1], [ 1, 2 ,1]]) >>> b = np.array([1, 2, 3]) >>> print a.dot(b) array([16, 6, 8]) This occurs because numpy arrays are not matrices, and the standard operations *, +, -, ...
Vector
21,562,986
290
In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustrup himself suggests not to use arrays. But are there significant performance differences?
Using C++ arrays with new (that is, using dynamic arrays) should be avoided. There is the problem that you have to keep track of the size, and you need to delete them manually and do all sorts of housekeeping. Using arrays on the stack is also discouraged because you don't have range checking, and passing the array aro...
Vector
381,621
257
I'm using multitreading and want to merge the results. For example: std::vector<int> A; std::vector<int> B; std::vector<int> AB; I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?
AB.reserve( A.size() + B.size() ); // preallocate memory AB.insert( AB.end(), A.begin(), A.end() ); AB.insert( AB.end(), B.begin(), B.end() );
Vector
3,177,241
255
I've always thought it's the general wisdom that std::vector is "implemented as an array," blah blah blah. Today I went down and tested it, and it seems to be not so: Here's some test results: UseArray completed in 2.619 seconds UseVector completed in 9.284 seconds UseVectorPushBack completed in 14.669 seconds The whol...
Using the following: g++ -O3 Time.cpp -I <MyBoost> ./a.out UseArray completed in 2.196 seconds UseVector completed in 4.412 seconds UseVectorPushBack completed in 8.017 seconds The whole thing completed in 14.626 seconds So array is twice as quick as vector. But after looking at the code in more detail t...
Vector
3,664,272
250
So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, first, last) is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values?
Try this: vector<Type>::iterator nth = v.begin() + index;
Vector
671,423
249
I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following: print *(myVector._M_impl._M_start)@myVector.size() To print only the first N elements, do: print *(myVector._M_impl._M_start)@N Explanation This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the po...
Vector
253,099
244
Ok, this is really difficult to confess, but I do have a strong temptation at the moment to inherit from std::vector. I need about 10 customized algorithms for vector and I want them to be directly members of the vector. But naturally I want also to have the rest of std::vector's interface. Well, my first idea, as a l...
Actually, there is nothing wrong with public inheritance of std::vector. If you need this, just do that. I would suggest doing that only if it is really necessary. Only if you can't do what you want with free functions (e.g. should keep some state). The problem is that MyVector is a new entity. It means a new C++ devel...
Vector
4,353,203
244
I have found an interesting performance regression in a small C++ snippet, when I enable C++11: #include <vector> struct Item { int a; int b; }; int main() { const std::size_t num_items = 10000000; std::vector<Item> container; container.reserve(num_items); for (std::size_t i = 0; i < num_items; ++i) { ...
I can reproduce your results on my machine with those options you write in your post. However, if I also enable link time optimization (I also pass the -flto flag to gcc 4.7.2), the results are identical: (I am compiling your original code, with container.push_back(Item());) $ g++ -std=c++11 -O3 -flto regr.cpp && perf...
Vector
20,977,741
240
What is the cheapest way to initialize a std::vector from a C-style array? Example: In the following class, I have a vector, but due to outside restrictions, the data will be passed in as C-style array: class Foo { std::vector<double> w_; public: void set_data(double* w, int len){ // how to cheaply initialize th...
Don't forget that you can treat pointers as iterators: w_.assign(w, w + len);
Vector
2,434,196
233
Are all of the following statements true? vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack vector<Type*> vect; //vect will be on stack and T...
vector<Type> vect; will allocate the vector, i.e. the header info, on the stack, but the elements on the free store ("heap"). vector<Type> *vect = new vector<Type>; allocates everything on the free store (except vect pointer, which is on the stack). vector<Type*> vect; will allocate the vector on the stack and a bun...
Vector
8,036,474
233
Is there a built-in vector function in C++ to reverse a vector in place? Or do you just have to do it manually?
There's a function std::reverse in the algorithm header for this purpose. #include <vector> #include <algorithm> int main() { std::vector<int> a; std::reverse(a.begin(), a.end()); return 0; }
Vector
8,877,448
226
Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this: let mut a = vec![1, 2, 3]; let b = vec![4, 5, 6]; for val in &b { a.push(val); } Does anyone know of a better way?
The structure std::vec::Vec has method append(): fn append(&mut self, other: &mut Vec<T>) Moves all the elements of other into Self, leaving other empty. From your example, the following code will concatenate two vectors by mutating a and b: fn main() { let mut a = vec![1, 2, 3]; let mut b = vec![4, 5, 6]; ...
Vector
40,792,801
226
I have a dataframe such as: a1 = c(1, 2, 3, 4, 5) a2 = c(6, 7, 8, 9, 10) a3 = c(11, 12, 13, 14, 15) aframe = data.frame(a1, a2, a3) I tried the following to convert one of the columns to a vector, but it doesn't work: avector <- as.vector(aframe['a2']) class(avector) [1] "data.frame" This is the only solution I coul...
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments. A data frame is a list. When you subset a data frame using the name of a column and [, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column,...
Vector
7,070,173
223
It seems that Vector was late to the Scala collections party, and all the influential blog posts had already left. In Java ArrayList is the default collection - I might use LinkedList but only when I've thought through an algorithm and care enough to optimise. In Scala should I be using Vector as my default Seq, or try...
As a general rule, default to using Vector. It’s faster than List for almost everything and more memory-efficient for larger-than-trivial sized sequences. See this documentation of the relative performance of Vector compared to the other collections. There are some downsides to going with Vector. Specifically: Updat...
Vector
6,928,327
218
I want to initialize a vector like we do in case of an array. Example int vv[2] = {12, 43}; But when I do it like this, vector<int> v(2) = {34, 23}; OR vector<int> v(2); v = {0, 9}; it gives an error: expected primary-expression before ‘{’ token AND error: expected ‘,’ or ‘;’ before ‘=’ token respectively.
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do: std::vector<int> v { 34,23 }; // or // std::vector<int> v = { 34,23 }; Or even: std::vector<int> v(2); v = { 34,23 }; On compilers that don't support this feature (initializer lists) yet you can emulate this with an a...
Vector
8,906,545
217
Can anyone tell me how to find the common elements from multiple vectors? a <- c(1,3,5,7,9) b <- c(3,6,8,9,10) c <- c(2,3,4,5,7,9) I want to get the common elements from the above vectors (ex: 3 and 9)
There might be a cleverer way to go about this, but intersect(intersect(a,b),c) will do the job. EDIT: More cleverly, and more conveniently if you have a lot of arguments: Reduce(intersect, list(a,b,c))
Vector
3,695,677
216
Suppose I have a line segment going from (x1,y1) to (x2,y2). How do I calculate the normal vector perpendicular to the line? I can find lots of stuff about doing this for planes in 3D, but no 2D stuff. Please go easy on the maths (links to worked examples, diagrams or algorithms are welcome), I'm a programmer more than...
If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx). Note that no division is required, and so you're not risking dividing by zero.
Vector
1,243,614
214
The question's pretty self-explanatory really. I know vaguely about vectors in maths, but I don't really see the link to C++ vectors.
It's called a vector because Alex Stepanov, the designer of the Standard Template Library, was looking for a name to distinguish it from built-in arrays. He admits now that he made a mistake, because mathematics already uses the term 'vector' for a fixed-length sequence of numbers. C++11 compounds this mistake by int...
Vector
581,426
210
R offers max and min, but I do not see a really fast way to find another value in the order, apart from sorting the whole vector and then picking a value x from this vector. Is there a faster way to get the second highest value, for example?
Use the partial argument of sort(). For the second highest value: n <- length(x) sort(x,partial=n-1)[n-1]
Vector
2,453,326
197
I am running into issues trying to use large objects in R. For example: > memory.limit(4000) > a = matrix(NA, 1500000, 60) > a = matrix(NA, 2500000, 60) > a = matrix(NA, 3500000, 60) Error: cannot allocate vector of size 801.1 Mb > a = matrix(NA, 2500000, 60) Error: cannot allocate vector of size 572.2 Mb # Can't go sm...
Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix package for e.g.) for sparse matrices. Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc() to clear now unused memory, or, better only c...
Vector
5,171,593
196
I'm trying to learn R and I can't figure out how to append to a list. If this were Python I would . . . #Python vector = [] values = ['a','b','c','d','e','f','g'] for i in range(0,len(values)): vector.append(values[i]) How do you do this in R? #R Programming > vector = c() > values = c('a','b','c','d','e','f','g'...
Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided". As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop....
Vector
22,235,809
196
So, I have the following: std::vector< std::vector <int> > fog; and I am initializing it very naively like: for(int i=0; i<A_NUMBER; i++) { std::vector <int> fogRow; for(int j=0; j<OTHER_NUMBER; j++) { fogRow.push_back(0); } fog.push_back(fogRow); } And it feels very wrong... Is there ano...
Use the std::vector::vector(count, value) constructor that accepts an initial size and a default value: std::vector<std::vector<int> > fog( ROW_COUNT, std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value If a value other than zero, say 4 for example, was required to be the default then: std::vect...
Vector
17,663,186
194
I'm trying to use std::vector as a char array. My function takes in a void pointer: void process_data(const void *data); Before I simply just used this code: char something[] = "my data here"; process_data(something); Which worked as expected. But now I need the dynamicity of std::vector, so I tried this code instead...
&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken). Assu...
Vector
6,485,496
186
I am trying to efficiently make a copy of a vector. I see two possible approaches: std::vector<int> copyVecFast1(const std::vector<int>& original) { std::vector<int> newVec; newVec.reserve(original.size()); std::copy(original.begin(), original.end(), std::back_inserter(newVec)); return newVec; } std::vector<in...
They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names. My favourite is: a = b; Where a and b are vectors.
Vector
644,673
180
I read that Vectors are not seqs, but Lists are. I'm not sure what the rationale is for using one over the other. It seems that vectors are used the most, but is there a reason for that?
Once again, it seems I've answered my own question by getting impatient and asking it in #clojure on Freenode. Good thing answering your own questions is encouraged on Stackoverflow.com :D I had a quick discussion with Rich Hickey, and here is the gist of it. [12:21] <Raynes> Vectors aren't seqs, right? [12:21] <rhi...
Vector
1,147,975
169
Item 18 of Scott Meyers's book Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library says to avoid vector <bool> as it's not an STL container and it doesn't really hold bools. The following code: vector <bool> v; bool *pb =&v[0]; will not compile, violating a requirement of STL containe...
For space-optimization reasons, the C++ standard (as far back as C++98) explicitly calls out vector<bool> as a special standard container where each bool uses only one bit of space rather than one byte as a normal bool would (implementing a kind of "dynamic bitset"). In exchange for this optimization it doesn't offer a...
Vector
17,794,569
167
Is it possible to iterate a vector from the end to the beginning? for (vector<my_class>::iterator i = my_vector.end(); i != my_vector.begin(); /* ?! */ ) { } Or is that only possible with something like that: for (int i = my_vector.size() - 1; i >= 0; --i) { }
One way is: for (vector<my_class>::reverse_iterator riter = my_vector.rbegin(); riter != my_vector.rend(); ++riter) { // do stuff } rbegin()/rend() were especially designed for that purpose. (And yes, incrementing a reverse_iterator moves it backward.) Now, in theory, your method (using begin()/end() & --i...
Vector
3,610,933
164